目录
Python是一种流行的编程语言,它有很多特性和优点。
其中之一就是它的控制流语句,它可以让程序根据不同的条件或循环执行不同的操作。
在这篇文章中,我们将介绍另外两种常用的控制流语句:
while循环和break语句。
while 循环
while循环是一种条件循环语句,它可以让程序重复执行某个代码块,直到一个条件不成立。while循环的基本结构如下:
while condition:
# do something while condition is True
其中,condition是一个布尔表达式,它可以是一个变量,一个比较运算符(如==, !=, <, >等),一个逻辑运算符(如and, or, not等),或者它们的组合。如果condition为True,则执行while后面缩进的代码块;如果condition为False,则退出循环。
例如,我们可以用 while 循环来计算一个数的阶乘:
# get a positive integer from user input
n = int(input("Enter a positive integer: "))
factorial = 1 # initialize the factorial variable to 1
i = 1 # initialize the loop counter to 1
while i <= n: # loop until i is greater than n
factorial = factorial * i
i = i + 1
print(n, "! =", factorial) # print the result
break 语句
break语句是一种跳出语句,它可以让程序提前结束当前的循环。break语句通常和if语句配合使用,来判断是否满足某个终止条件。break语句的基本结构如下:
for item in iterable:
if condition:
break # exit the loop if condition is True
# do something with item
或者
while condition:
if another_condition:
break # exit the loop if another_condition is True
# do something while condition is True
其中,condition 和 another_condition 都是布尔表达式;item 是一个临时变量;iterable 是一个可迭代对象。
例如,我们可以用 while 循环和 break 语句来实现一个猜数字游戏:
import random # import the random module to generate a random number
# generate a random number between 1 and 10 and assign it to answer
answer = random.randint(1, 10)
guess = None
while True: # start an infinite loop
guess = int(input("Guess a number between 1 and 10: "))
if guess == answer: # check if the guess is equal to the answer
print("You got it!")
break # exit the loop
elif guess < answer: # check if the guess is less than the answer
print("Too low.")
else: # check if the guess is greater than the answer
print("Too high.")
总结
在这篇文章中,我们介绍了另外两种常用的Python控制流语句:while 循环和break 语句。它们可以让程序根据不同的条件或循环执行不同的操作。
参考文档
PS:
本文首发于公众号: 程序熵, 更多精彩文章请点击关注 code-shang