流程控制之if判断

1.流程控制--if判断

语法1:if后面跟判断语句,条件成立则继续进行下面的代码块,条件不成立则不执行
if 条件:
代码1 # 代码块,根据缩进来看执行顺序。
代码2
代码3
...

cls='human'
sex='female'
age=18

if cls == 'human' and sex == 'female' and age > 16 and age < 22:
print('开始表白')

print('end....')



语法2:if ... else... if后面的判断语句成立,则执行if下面的语句。如果if判断为False,则执行else语句。
if 条件:
代码1
代码2
代码3

else:
代码1
代码2
代码3


cls='human'
sex='female'
age=38

if cls == 'human' and sex == 'female' and age > 16 and age < 22:
print('开始表白')
else:
print('阿姨好')

print('end....')


语法3 if...elif...else if后面的条件判断不成立,则进行下一个条件判断,即elif后面的条件判断,不成立则继续下去,
直到条件成立,否则会执行else。

if 条件1:
代码1
代码2
代码3
...
elif 条件2:
代码1
代码2
代码3
...
elif 条件3:
代码1
代码2
代码3
...
............
else:
代码1
代码2
代码3
...

例题1
'''
如果:成绩>=90,那么:优秀

如果成绩>=80且<90,那么:良好

如果成绩>=70且<80,那么:普通

其他情况:很差

'''

score=input('your score: ') #score='73'
score=int(score) #score=73
if score >= 90:
print('优秀')
elif score >= 80:
print('良好')
elif score >= 70:
print('普通')
else:
print('很差')

例题2

user_from_db='egon'
pwd_from_db='123'

user_from_inp=input('username>>>: ')
pwd_from_inp=input('password>>>: ')

if user_from_inp == user_from_db and pwd_from_inp == pwd_from_db:
print('login successfull')
else:
print('user or password error')



if的嵌套 if嵌套if,只有上一次层的if判断成立,才会执行嵌套的if。

cls='human'
sex='female'
age=18
is_success=False # 重点:False赋值给一个变量,变量可以作为if的判断语句使用。

if cls == 'human' and sex == 'female' and age > 16 and age < 22: # if判断条件成立,执行下一层的if
print('开始表白...')
if is_success: # is_success设定为False,if语句不会往下执行,直接执行else。
print('在一起') # 如果想要执行这条语句,在上一条if语句后面加上is_success =True。
else:
print('我逗你玩呢....')
else:
print('阿姨好')

print('end....') #这个和if语句同级缩进,执行顺序一样,执行完if,会执行print()。

原文地址:https://www.cnblogs.com/Roc-Atlantis/p/9104674.html