流程控制
1、if 判断
a. 单分支
if 条件:
满足条件后要执行的代码
- age_of_oldboy = 50
- if age_of_oldboy > 40 : print('too old, time to end')
- 输出:
- too old,
- time to end
b. 双分支
if 条件:
满足条件执行代码
else:
if 条件不满足就走这段
- age_of_oldboy = 50
- if age_of_oldboy > 100 : print('too old, time to end')
- else: print('impossible')
- 输出:
- impossible
c. 多分支
if 条件:
满足条件执行代码
elif 条件:
上面的条件不满足就走这个
elif 条件:
上面的条件不满足就走这个
elif 条件:
上面的条件不满足就走这个
else:
上面所有的条件不满足就走这段
- age_of_oldboy = 91
- if age_of_oldboy > 100 : print('too old, time to end')
- elif age_of_oldboy > 90 : print('age is: 90') elif age_of_oldboy > 80 : print('age is 80')
- else: print('impossible')
- 输出:
- age is : 90 #如果一个
- if或者elif成立,就不再往下判断
2、whil 循环
a.while 语法
while 条件: #只有当 while 后面的条件成立时才会执行下面的代码
执行代码...
- count = 1
- while count <= 3 : print(count) count += 1
- 输出:
- 1
- 2
- 3
练习:打印 10 内的偶数
- count = 0
- while count <= 10 :
- if count % 2 == 0 : print(count) count += 1
- 输出:
- 0
- 2
- 4
- 6
- 8
- 10
while ...else 语句
当 while 循环正常执行完,中间没有被 break 中止的话,就会执行 else 后面的语句
- count = 1
- while count <= 3 :
- if count == 4 :
- break print(count) count += 1
- else: #
- while没有被
- break打断的时候才执行
- else的子代码 print(' === ======>')
b. 循环控制
break 用于完全结束一个循环,跳出循环体执行循环后面的语句
continue 终止本次循环,接着还执行后面的循环,break 则完全终止循环
例:break
- count = 1
- while count <= 100 :
- if count == 10 :
- break#跳出本层循环 print(count) count += 1
- 输出:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9 #当count = 10时,就跳出本层循环
例:continue
- count = 0
- while count < 5 :
- if count == 3 : count += 1
- continue print(count) count += 1
- 输出:
- 0
- 1
- 2
- 4 #当count = 3时,就跳出本次循环,不打印3,进入下一次循环
使用 continue 实现打印 10 以内的偶数
- count = 0
- while count <= 10 :
- if count % 2 != 0 : count += 1
- continue print(count) count += 1
c. 死循环
while 是只要后边条件成立 (也就是条件结果为真) 就一直执行
一般写死循环可以:
while True:
执行代码。。。
还有一种:(好处是可以使用一个变量来控制整个循环)
tag=True
while tag:
执行代码。。。
whiletag:
执行代码。。。
- count = 0 tag = True
- while tag:
- if count > 2 : print('too many tries')
- break user = input('user: ') password = input('password: ')
- if user == 'egon'and password == '123': print('login successful')
- while tag: cmd = input(' >> :')
- if cmd == 'q': tag = False
- continue print('exec % s' % cmd)
- else: print('login err') count += 1
持续更新中。。。
来源: http://www.bubuko.com/infodetail-2163294.html