Python中while语句的一般形式:
while 判断条件:
语句
例如,下面的while 循环从1数到5:
current_number = 1 while current_number <= 5: print(current_number) current_number += 1
一旦current_number 大于5,循环将停止,整个程序也将到此结束:
1
2
3
4
5
要立即退出while 循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break 语句。
例如:prompt = "\nPlease enter the name of a city you have visited:" prompt += "\n(Enter 'quit' when you are finished.) "
❶ while True: city = input(prompt) if city == 'quit': break else: print("I'd love to go to " + city.title() + "!")输出结果:
Please enter the name of a city you have visited: (Enter 'quit' when you are finished.) New York I'd love to go to New York!
Please enter the name of a city you have visited: (Enter 'quit' when you are finished.) San Francisco I'd love to go to San Francisco!
Please enter the name of a city you have visited: (Enter 'quit' when you are finished.) quit
要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue 语句,它不像break 语句那样不再执行余下的代码并退出整个循环。
例如:
current_number = 0
while current_number < 10: ❶ current_number += 1 if current_number % 2 == 0: continue print(current_number)输出结果:
1
3
5
7
9
Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
for循环的一般格式如下:
for <variable> in <sequence>: <statements> else: <statements>
如果你需要遍历数字序列,可以使用内置range()函数。它会生成数列,例如:
实例
>>>for i in range(5,9) : print(i) 5 6 7 8 >>>