在Python 中有三种控制流语句——if、for 和while。 1.if语句
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‘)
输出:
Enter an integer : 50
No, it is a little lower than that
Done
Enter an integer : 22
No, it is a little higher than that
Done
Enter an integer : 23
Congratulations, you guessed it.
(but you do not win any prizes!)
Done
elif事实上是把两个相关联的if else-if else语句结合为一个if-else-else语句,使程序更简单,并且减少所需的缩进数量。
2.while语句
number = 23 Running = True while Running: Guess = int(input("Enter an integer:")) if Guess == Number: print("Congratulations, you guessed it.") elif Guess < Number: print("No, it is a little higher.") else: print("No, it is a little lower.") else: print("the while loop is over.") print("Done")
输出:
Enter an integer : 50 No, it is a little lower. Enter an integer : 22 No, it is a little higher. Enter an integer : 23 Congratulations, you guessed it. The while loop is over. Done
while 语句有一个可选的else 从句,他将始终被执行,除非循环永远循环下去。
3.for循环
for i in range(1,5): print(i) else: print("The for loop is over")
输出:
1
2
3
4
The for loop is over
在这里,提供两个数,range返回一个序列的数,这个序列从第一个数开始到第二个数位置,range(1,5)给出序列[1,2,3,4]。默认range的步长为1。如果为range提供第三个数,那么它将作为步长,例如,range(1,5,2)给出序列[1,3],步长为2。range的范围不包括第二个数。
for i in range(1,5)等价于for i in [1,2,3,4],把序列的里的每个数赋值给i,一次一个。这个程序中打印的是i的值。
else是可选的,如果包含else,他总在for循环结束后执行一次,除非遇到break语句。
时间: 2025-01-04 21:05:29