分支
if-else
python中不需要用花括号来指定流程控制语句的作用范围,而是直接靠语句的位置来体现
mood = True
if mood:
print('go to left')
print('go away')
mood = False
if mood:
print('go to left')
print('go away')
进一步应用:
account = 'account'
password = '123456'
print('please input account')
user_account = input()
print('please input password')
user_password = input()
if account == user_account and password == user_password:
print('success')
else:
print('fail')
if - elif - else
a = input()
a = int(a)
if a == 1:
print('apple')
elif a == 2:
print('orange')
elif a == 3:
print('banana')
else:
print('shopping')
注:此处直接输入数字会被直接识别为字符串str形式,所以必须强制转化为int类型才能继续比较
循环
while 循环
- while可以与else 搭配使用
counter = 0
while counter <= 10:
counter += 1
print(counter)
else:
print('EOR')
for循环
- for循环主要用来遍历序列,集合,元组,字典中的元素
a = ['apple', 'orange', 'banana']
for x in a:
print(x)
打印子列表
a = [['apple', 'orange', 'banana'], (1, 2, 3)]
for x in a:
for y in x:
print(y)
for - else和break联用
break会直接跳出当前循环
a = [1, 2, 3]
for x in a:
if x == 2:
break
print(x)
else:
print('EOR')
特殊情况:
a = [['apple', 'orange', 'banana'], (1, 2, 3)]
for x in a:
for y in x:
if y == 'orange':
break
print(y)
else:
print('fruit is gone')
上述两种都是for- else循环为什么一个碰到break会退出而另一个不会?
因为第一个是单层for循环,而第二个是双层for循环。
只有当跳出所有的for循环后,else内的内容才会被跳过