Python 编程提供两种循环:for 循环和while 循环。结合break 和 continue 等循环控制语句,我们可以创建各种形式的循环。
无限循环
我们可以使用 while 语句创建无限循环。如果 while 循环的条件始终为 True
,就会得到一个无限循环。
示例 #1:使用 while 的无限循环
# An example of infinite loop
# press Ctrl + c to exit from the loop
while True:
num = int(input("Enter an integer: "))
print("The double of",num,"is",2 * num)
输出
Enter an integer: 3 The double of 3 is 6 Enter an integer: 5 The double of 5 is 10 Enter an integer: 6 The double of 6 is 12 Enter an integer: Traceback (most recent call last):
条件在顶部的循环
这是一个没有 break 语句的普通 while 循环。while 循环的条件在顶部,当条件为 False
时,循环终止。
条件在顶部的循环流程图

示例 #2:条件在顶部的循环
# Program to illustrate a loop with the condition at the top
# Try different numbers
n = 10
# Uncomment to get user input
#n = int(input("Enter n: "))
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is",sum)
运行程序后,输出将是
The sum is 55
条件在中间的循环
这种循环可以通过无限循环以及循环体中间的条件 break 来实现。
条件在中间的循环流程图

示例 #3:条件在中间的循环
# Program to illustrate a loop with condition in the middle.
# Take input from the user until a vowel is entered
vowels = "aeiouAEIOU"
# infinite loop
while True:
v = input("Enter a vowel: ")
# condition in the middle
if v in vowels:
break
print("That is not a vowel. Try again!")
print("Thank you!")
输出
Enter a vowel: r That is not a vowel. Try again! Enter a vowel: 6 That is not a vowel. Try again! Enter a vowel: , That is not a vowel. Try again! Enter a vowel: u Thank you!
条件在底部的循环
这种循环确保循环体至少执行一次。它可以通过无限循环以及末尾的条件 break 来实现。这类似于 C 语言中的 do...while 循环。
条件在底部的循环流程图

示例 #4:条件在底部的循环
# Python program to illustrate a loop with the condition at the bottom
# Roll a dice until the user chooses to exit
# import random module
import random
while True:
input("Press enter to roll the dice")
# get a number between 1 to 6
num = random.randint(1,6)
print("You got",num)
option = input("Roll again?(y/n) ")
# condition
if option == 'n':
break
输出
Press enter to roll the dice You got 1 Roll again?(y/n) y Press enter to roll the dice You got 5 Roll again?(y/n) n