程序流程控制if判断
1.if
1.单个if也就是单分支结构
2.若是if不成立的话,就正常的进入程序下面的语句,由于流程代码是自顶向下的
3.单个if的话,就只有1次判断,判断结果是真那就执行if下面的语句块
<代码块1>
if <条件>:
<代码块2> # 当条件为True的时候执行代码块2而后执行代码块3,不然不执行代码块2直接执行代码块3 # tab
<代码块3> # 当条件不成立时直接运行代码块3
cls = 'human'
if cls == 'human' :
print('开始表白')
print('end...')
2.if····else
1.if····else时双分支结构
2.if...else表示if成立的时候会进入if下面的语句块也就是代码会干什么,else表明条件不成立时应该进入else下面对应的语句块。
<代码块1>
if <条件>:
<代码块2> # 当条件为True的时候执行代码块2而后执行代码块3 # tab
else:
<代码块4> # 当条件不成立时,运行代码块4,而后再运行代码块3
<代码块3> # 当条件不成立时首先运行代码块4,而后运行代码块3
<代码块1>
if <条件>:
<代码块2> # 当条件为True的时候执行代码块2而后执行代码块3 # tab
else:
<代码块4> # 当条件不成立时,运行代码块4,而后再运行代码块3
<代码块3> # 当条件不成立时首先运行代码块4,而后运行代码块3
age = 38
if age > 16 and age < 22:
print('开始表白')
else:
print('阿姨好')
3.if···elif···else
1.if···elif···else是多分支结构
2.if...elif...else表示if条件1成立代码干什么,elif条件2成立干什么,elif条件3成立干什么,else...不然干什么。
<代码块1>
if <条件1>:
<代码块2> # 当条件1为True的时候执行代码块2而后执行代码块3 # tab
elif <条件2>:
<代码块5> # 当条件1不成立条件2成立,执行代码块5,而后执行代码块3
...
elif <条件n>:
<代码块n>
else:
<代码块4> # 当if和elif的全部条件都不成立时,执行代码块4,而后执行代码块3
<代码块3>
cls = 'human'
gender = 'female'
age = 28
if cls == 'human' and gender == 'female':
print('开始表白')
elif cls == 'human' and gender == 'female' and age > 22 and age < 30:
print('考虑下')
else:
print('阿姨好')
4.if的嵌套
1.if 的嵌套是好比咱们要去写一篇做文,若是能够写完做文,若是不能够写完做文又该怎么样。若是咱们能够写完做文,咱们是否是能够判断做文里有没有错别字,若是有的话怎么样,没有的话又怎么样,可是查找错别字是创建在咱们可不能够写完的基础上,这就是if的嵌套。
if 条件1:
if 条件2:
else:
.....
# 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('阿姨好')
练习
# 成绩评判
score = input("your score: ")
score = int(score)
if score >= 90:
print('优秀')
# elif score >= 80 and score < 90:
elif score >= 80:
print('良好')
# elif score >= 70 and score < 80:
elif score >= 70:
print('普通')
else:
print('差')
# 模拟登陆注册
user_from_db = 'nick'
pwd_from_db = 123
user_from_inp = input('username: ')
user_from_inp = input('password: ')
if user_from_inp == user_from_db and pwd_from_inp == pwd_from_db:
print('login successful')
else:
print('username or password error')