九、Control Flow(控制流)
- if 语句
- while 语句
- for 循环
- break 语句
- continue 语句
# 2018.3.27
"""
Control Flow
There're 3 control flow statements in python-
if,for,while
"""
# 1.The if statement Ex.A guessing game!
"""
Notice:
1.int(input())这一句中假设input的字符串中含有valid
integer value, 那么int作用就是将字符串转换为整型;
2.indentation(缩进)在python中非常重要! 下面statements
中if条件语句后的语句块每行如果不indent, 就成为不了语句
块, if就失去了意义. 一般python会自动缩进.
3.if语句的条件语句不需要括号, 注意条件后面的colon(冒号)
4.与C/C++相比, python中不存在switch语句, 其完全可以由if
语句代替, 后面的dictionary会更加方便.
"""
number = 23
guess = int(input('Enter an integer : '))
if guess == number:
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
elif guess < number:
print('No, it is a little higher than that')
else:
print('No, it is a little lower than that')
print('Done')
# This last statements is always executed after the if statement is executed.
if True:
print('Yes, it is true')
# 2018.3.27
# 2.The while statement: a looping statement
# Ex.Guessing game again!
"""
Notice:
1.与if语句每次猜都需要run相比,while语句可以循环执行直到结
果正确为止.
2.while语句可以有else clause(分句), 该clause在while循环跳
出后执行.这点与C/C++不同.
"""
number = 23
running = True
while running:
guess = int(input('Guess the number is : '))
if guess==number:
print('You got it!')
running = False
elif guess < number:
print('No, it is a little higher than that.')
else:
print('No, it is a little lower than that.')
else:
print('The while loop is over.')
print('Done')
# 2018.3.27
# 3.The for..in statement: a looping statement
"""
Ex.Sequence
Notice:
1.垂直显示5个i,
2.垂直显示五个j(注意多了else)
3.垂直显示1 2 3 4 5
4.垂直显示1 3 5(这里的step(步距)必须是整数)
5.显示[0,1,2,3,4,5]
同样注意colon, else选择性使用
Summery: for i in range(1,6): 等同于C中的
for(i=1;i<6;i++)
"""
# 1
for i in range(1,6):
print('i')
print('The for loop is over.')
#2
for j in range(1,6):
print('j')
else:
print('The for loop is over.')
# 3
for k in range(1,6):
print(k)
else:
print('The for loop is over.')
# 4
for k in range(1,6,2):
print(k)
else:
print('The for loop is over.')
# 5
print(list(range(6)))
# 2018.3.27
# 4.The break statement
"""
Notice:
1.强制跳出while或for循环, 跳出后else分句将不会被执行
2.在for loop中i取得第一个值后break, 因此只显示了1,
else语句同样无效.
"""
while True:
s = input('Enter something : ')
if s == 'quit':
print('Length of the string is',len(s))
else:
print('The while loop is over.')
print('Done')
"""
for i in range(1,6):
print(i)
break
else:
print('You SEE, this else sentence is redundant with a break.')
"""
# 2018.3.27
# 5.The continue statement
"""
Notice:
1.continue执行后,while loop继续执行(包含continue
后的所有process),直到满足break之前的条件, 跳出.
2.不管对for还是while,continue都是对循环而言的
3.单独执行语句块2, 结果显示为:4
慢慢体会!
"""
# 1
while True:
s = input('Enter something : ')
if s == 'quit':
break
if len(s) <= 3:
print('Too small')
continue
print('Input is of sufficient length')
# 2
for i in range(1,6):
if i < 4:
continue
elif i < 6:
print(i)
break
print('Out')
【声明】本博文为学习笔记,含有个人修改成分,并非完全依照《a byte of python》,仅供参考。若发现有错误的地方,请不吝赐教,谢谢。同时,我也会不定期回顾,及时纠正。#