在python中,循环语句

・3 分钟阅读



1. while

语法-

while expression :
 # statement

例子

num = 1
while num<=5 :
 print("num :",num)
 num+=1
print("Bye")

输出

num : 1
num : 2
num : 3
num : 4
num : 5
Bye

2,else

语法-

while expression :
 # statement
else:
 # else statement

例子-

  • 没有break关键字
num = 1
while num<=5 :
 print("num :",num)
 num+=1
else:
 print(num,"is greater than 5")
print("Bye")

输出

num : 1
num : 2
num : 3
num : 4
num : 5
6 is greater than 5
Bye
  • 使用break关键字
num = 1
while num<=5 :
 print("num :",num)
 如果 num == 3:
 break
 num+=1
else:
 print(num,"is greater than 5")
print("Bye")

输出

num : 1
num : 2
num : 3
Bye

3. for

当for循环执行时,它将第一个item存储在循环variable中,并在下一次执行。

语法-

for variable in sequence :
 # statement

例子

names = ["Sonarika","Yogesh","Vishal","Anil"]
for n in names :
 print("name :",n)
print("Bye")

输出

name : Sonarika
name : Yogesh
name : Vishal
name : Anil
Bye

使用numeric value range方法迭代循环。

例子

names = ["Sonarika","Yogesh","Vishal","Anil"]
for n in range(len(names)):
 print("name :",name[n])
print("Bye")

输出

name : Sonarika
name : Yogesh
name : Vishal
name : Anil
Bye

4. for else

语法-

for variable in sequence :
 # statement
else:
 # false statement

例子

  • 没有break关键字
names = ["Sonarika","Yogesh","Vishal","Anil"]
for n in names :
 print("name :",n)
else: 
 print("List is empty")
print("Bye")

输出

name : Sonarika
name : Yogesh
name : Vishal
name : Anil
List is empty
Bye
  • 使用break关键字
names = ["Sonarika","Yogesh","Vishal","Anil"]
for n in names :
 如果 n =="Vishal":
 break
 print("name :",n)
else:
 print("List is empty")
print("Bye")

输出

name : Sonarika
name : Yogesh
Bye
Xajhqffl profile image