基本运算符
算术运算符 + - * /
print(1 + 2 )
3
x = 10
y = 20
res = x + y
print(res)
30
比较运算符
pwd = '123'
print(pwd != '123')
print(pwd == '123')
False
True
l1 = [1, 'a', 3]
l2 = [3]
print(l1 < l2) # False
True
赋值运算符
age = 19
age = age + 1
print(age)
20
逻辑运算符
print(3 > 3 and 1 > 2 or 2 > 1)
True
身份运算符
x = 257
y = x
z = 257
print(f'x is y:{x is y}')
print(f'x == y:{x == y}')
print(f'x is z:{x is z}')
print(f'x == z:{x == z}'
x is y:True
x == y:True
x is z:False
x == z : True
位运算符
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c = 0
c = a & b
# 12 = 0000 1100
print("1 - c 的值为:", c)
1 - c 的值为:12
成员运算符
a = 10
b = 20
list = [1, 2, 3, 4, 5]
if (a in list):
print("1 - 变量 a 在给定的列表中 list 中")
else:
print("1 - 变量 a 不在给定的列表中 list 中")
1 - 变量 a 不在给定的列表 list 中
python运算符优先级
a = 20
b = 10
c = 15
d = 5
e = 0
e = (a + b) * c / d #( 30 * 15 ) / 5
print("(a + b) * c / d 运算结果为:", e)
(a + b) * c / d 运算结果为: 90.0
流程控制之 if 判断
1.语法
if
if 条件:
代码1
代码2
代码3
...
# 代码块(同一缩进级别的代码,例如代码1、代码2和代码3是相同缩进的代码,这三个代码组合在一起就是一个代码块,相同缩进的代码会自上而下的运行)
cls = 'human'
gender = 'female'
age = 18
if cls == 'human' and gender == 'female' and age > 16 and age < 22:
print('开始表白')
print('end...')
开始表白
end...
if...else
if 条件:
代码1
代码2
代码3
...
else:
代码1
代码2
代码3
...
cls = 'human'
gender = 'female'
age = 38
if cls == 'human' and gender == 'female' and age > 16 and age < 22:
print('开始表白')
else:
print('阿姨好')
阿姨好
if...elif...else
if 条件1:
代码1
代码2
代码3
...
elif 条件2:
代码1
代码2
代码3
...
elif 条件3:
代码1
代码2
代码3
...
...
else:
代码1
代码2
代码3
...
2. if的嵌套
# if的嵌套
cls = 'human'
gender = 'female'
age = 18
is_success = False
if cls == 'human' and gender == 'female' and age > 16 and age < 22:
print('开始表白')
if is_success:
print('那我们一起走吧...')
else:
print('我逗你玩呢')
else:
print('阿姨好')
开始表白
我逗你玩呢
流程控制 while 循环
1. 语法
while 条件
code 1
code 2
code 3
...
while True:
print('*1'*100)
print('*2'*100)
2.while+break
while True:
print('1')
print('2')
break
print('3')
3.while +continue
while True:
if 条件1:
code1
code2
code3
...
else:
code1
code2
code3
...
continue
4.while循环的嵌套
# 退出内层循环的while循环嵌套
while True:
user_db = 'nick'
pwd_db = '123'
inp_user = input('username: ')
inp_pwd = input('password: ')
if inp_user == user_db and pwd_db == inp_pwd:
print('login successful')
while True:
cmd = input('请输入你需要的命令:')
if cmd == 'q':
break
print(f'{cmd} 功能执行')
else:
print('username or password error')
print('退出了while循环')
# 退出双层循环的while循环嵌套
while True:
user_db = 'nick'
pwd_db = '123'
inp_user = input('username: ')
inp_pwd = input('password: ')
if inp_user == user_db and pwd_db == inp_pwd:
print('login successful')
while True:
cmd = input('请输入你需要的命令:')
if cmd == 'q':
break
print(f'{cmd} 功能执行')
break
else:
print('username or password error')
print('退出了while循环')
username: nick
password: 123
login successful
请输入你需要的命令:q
退出了while循环
5.tap控制循环退出
(中间变量)控制while循环