Python自学笔记——4.运算符

运算符

  1. 算术运算符
  2. 赋值运算符
  3. 比较运算符
  4. 逻辑运算符
  5. 成员运算符

算数运算符


a = 2
b = 3
c = 5
d = -5
f = 'abc'
g = 'def'

m = [a, a, a, a, c, a, c, d, f, f]
n = [b, b, b, b, b, c, a, a, g, b]
o = ['+', '-', '*', '/', '%', '**', '//', '//', '+', '*']
for i in range(0, 10):
    x, y = m[i], n[i]
    if i == 0 : z =x + y
    elif i == 1 : z = x - y
    elif i == 2 : z = x * y
    elif i == 3 : z = x / y
    elif i == 4: z = x % y
    elif i == 5: z = x ** y
    elif i == 6: z = x // y
    elif i == 7: z = x // y
    elif i == 8: z = x + y
    elif i == 9: z = x * y
    print(f'x = {m[i]}, y = {n[i]}, x {o[i]} y = {z}')


#字符串拼接其他形式
print(f'abc{g}')
print('abc{x}'.format(x = g))

  • /向下取整除
  • 字符串相加即为拼接
  • 字符串×数字n时,会把字符串复制n次拼接到一起
  • 字符串拼接也可用 (f'abc{g}' 或者 'abc{x}'.format(x = g)

赋值运算符


a = 2
b = 3
c = 5
d = -5
f = 'abc'
g = 'def'

m = [a, a, a, a, c, a, c, d, f, f]
n = [b, b, b, b, b, c, a, a, g, b]
o = ['+=', '-=', '*=', '/=', '%=', '**=', '//=', '//=', '+=', '*=']
for i in range(0, 10):
    x, y = m[i], n[i]
    if i == 0 : x += y
    elif i == 1 : x -= y
    elif i == 2 : x *= y
    elif i == 3 : x /= y
    elif i == 4: x %= y
    elif i == 5: x **= y
    elif i == 6: x //= y
    elif i == 7: x //= y
    elif i == 8: x += y
    elif i == 9: x *= y
    print(f'x = {m[i]}, y = {n[i]}, x {o[i]} y ----> x = {x}')

  • 运算方式同算数运算符

比较运算符

a = 1
b = 2
print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)

  • 比较运算符的返回结果为 True 或者 False

逻辑运算符

a = True
b = False
c = 0
d = 1
e = 2

print(a and a)
print(a and b)
print(b and a)
print(b and b)
print(c and d)
print(d and c)
print(d and e)
print(e and d)

print(a or a)
print(a or b)
print(b or a)
print(b or b)
print(c or d)
print(d or c)
print(d or e)
print(e or d)

print(not a)
print(not b)
print(not c)
print(not d)
print(not e)
  • and 全真为真,一假为假
  • or 全假为假,一真为真

成员运算符

a = '123456'
b = ['1', '2', '3', '4', '5', '6']
c = ('1', '2', '3', '4', '5', '6')
x = '2'
y = '7'
print(x in a)
print(x in b)
print(x in c)
print(y in a)
print(y in b)
print(y in c)

print(x not in a)
print(x not in b)
print(x not in c)
print(y not in a)
print(y not in b)
print(y not in c)

  • 成员运算符的返回结果为 True 或者 False

你可能感兴趣的:(Python自学笔记——4.运算符)