今日是学习python的第004课,本节课主要学习了流程控制的if、while、for。
if判断
一、什么时if判断?
判断一个条件如果成立则做……如果不成立则做……
二、为何要有if判断?
让计算机能够像人一样具有判断的能力
三、如何用if判断
语法1:
if 条件1: #先判断条件1是否成立,依据是看布尔值,如果为真就会运行下面的子代码块
code1 #代码块,什么是代码块,在python中用同一缩进级别来标识一个代码块
code2 #同一代码块的运行特点是按照从上至下的顺序依次运行
code3
......
例如:
age=18
if age == 18: #条件成立
print('你好') #先运行这一条子代码
print('加个微信吧') #再运行这一条子代码
print('转身离开') #最后运行这一条代码
age=18
if age != 18: #条件不成立
print('你好')
print('加个微信吧')
print('转身离开') #跳过if之代码块,直接运行这一条代码
语法2:
if 条件: #先判断条件是否成立,如果成立运行if下面的子代码块
code1
code2
code3
......
else: #如果条件不成立,则运行else下面的子代码块
code1
code2
code3
......
例如:
age=18
sex='female'
speci='human'
is_beautiful=True
if age > 16 and age <28 and sex == 'female' and speci == 'human' and is_beautiful: #代码过长可以用\分隔回车
print('开始表白...') #条件成立,运行子代码
else:
print('转身离开')
语法3
if 条件1: #先判断条件是否成立,成立则运行子代码块,否则运行code4
if 条件2: #再次判断条件是否成立,成立则运行子代码块,否则运行code4
code1
code2
code3
code4
code5
......
例如:
age=18
sex='female'
speci='human'
is_beautiful=True
is_successful=True
if age > 16 and age <28 and sex == 'female' and speci == 'human' and is_beautiful: #代码过长可以用\分隔成几段
print('开始表白...') #条件成立,运行子代码
if is_successful: #条件成立,运行子代码
print('在一起')
else:
print('黯然销魂')
else:
print('转身离开')
语法4
if 条件1: #判断条件,成立运行子代码块1,不成立运行条件2
子代码块1
elif 条件2: #判断条件,成立运行子代码块2,不成立运行条件3,依次类推
子代码块2
elif 条件3: #当运行到条件3时,说明条件1和条件2一定是不成立的
子代码块3
elif 条件4:
子代码块4
......
else: #上面的条件都不成立,才会运行else
子代码块5
对于一个if判断语法来说,if是必须的,elif和else是可选的,如果写全的话,elif一定是放在中间、else一定是放在最后的
例:成绩查询
score = input('your score..:')
score = int(score)
if score >= 90:
print('优秀')
elif score >=80 and score <90: #and条件不需要,因为前面一个条件不成立,分数一定是<90分,只需要判断分数是否>=80
print('良好')
elif score >=70 and score <80: #and条件不需要,因为前面一个条件不成立,分数一定是<80分,只需要判断分数是否>=70
print('普通')
else:
print('很差')
while循环
一、什么是循环
循环指的是重复做某件事的过程
二、为何要有循环
为了让计算机能够像人一样重复做某件事
三、如何用循环
while循环的语法(while循环又称条件循环,循环的次数取决于条件)
while 条件:
子代码块1
子代码块2
子代码块3
**#while循环运行原理,先判断条件是否成立,成立后运行子代码块1>子代码块2>子代码块3,然后回到判断条件是否成立,如果还成立则再次依次运行子代码块,运行完子代码块后再回到判断条件是否成立。直到条件为False,循环结束**
例如:用户登陆认证功能
print('start...')
while True:
name=input('input your name..:')
pwd=input('input your password..:')
if name == 'mycash' and pwd == '123':
print('login successful')
else:
print('name or password err')
print('end...')