.While 循环
虽然循环用于迭代执行代码块,直到满足特定条件,但只要条件保持不变,请确保重复继续。
#Syntax of while loop
while condition:
# Code block to be executed repeatedly举个例子:
在下面的代码中,循环将提示用户重复输入其名称,直到他们提供非空输入。输入非空名称后,循环将中断,程序将打印输入的名称。
name = input("Enter your name: ")
while name == '':
print("Please provide a name")
name = input("Enter your name: ")
print("Your name is:", name)
在下面的代码中,循环将反复执行,询问用户的名称,直到他们输入“Quit”。
name= input("Enter your name")
while not name =='Quit':
print("Please provide a name")
name=input("Enter your name")
print(name)
让我们使用 While Loop 做一些程序。
- 打印从用户定义的数字开始到 5 的数字。
#Print up to 5
i=int(input("Enter any number below 5"))
while i<=5:
print(i)
i=i+1
print("the end")
2. 以相反的顺序打印数字。
#Printing in reverse order
i=5
while i>1:
print(i)
i=i-1
print("the end")
3. 在列表中查找小于 20 的数字,同时使用带有 if-else 语句的循环。
#While loop with if-else statement
#To find the numbers which are below 20
a=[2,40,6,25,10]
i=0
x=len(a)
while i<x:
if a[i]<20:
print(a[i])
i=i+1
else:
i=i+1
4. 再举一个例子,将列表中的所有数字相加 2。
#Add 2 with all the numbers in the list
a = [2, 40, 6, 25, 10]
j = []
i = 0
while i < len(a):
modified_num = a[i] + 2
j.append(modified_num)
i += 1
print(j)
# Flow control with while loop
num = 10
while num > 0:
print(num)
num -= 2
请注意,如果 while 条件处理不当,可能会发生无限循环。因此,必须小心处理 while 循环。
# Example 4: Infinite loop
while True:
print("This is an infinite loop!")
嵌套循环:
嵌套 while 循环意味着将一个 while 循环放在另一个循环中。这允许创建更复杂的循环结构,其中一个循环控制另一个循环的执行。
# Example 5: Nesting while loops
row = 1
while row <= 3:
col = 1
while col <= 3:
print(row, col)
col += 1
row += 1
中断和继续语句:
中断和继续是在循环中用于改变其行为的控制流语句。
中断语句:
- 当在循环(包括 while 循环)中遇到时,无论循环的状况如何,中断都会立即退出循环。
- 它通常用于在满足特定条件时过早终止循环。
#break means the loop will stop execution without letting the other statements execute
num = 1
while num <= 10:
if num == 5:
break # Exit the loop when num equals 5
print(num)
num += 1
continue语句:
- 在循环中遇到时,continue 将跳过当前迭代的循环中的剩余代码,并继续下一次迭代。
#continue will continue the loop without letting the other statements execute
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
while 循环 else 语句:
在 Python 中,您可以将 else 子句与 while 循环一起使用。当循环条件变为 false 时,将执行 else 块。
#While loop with else statement
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")