for循环

1

对于列表magicians中的每位魔术师,使用for循环将魔术师名单中的所有名字打印出来

程序代码

# magicians.py

magicians=['alice','david','carolina']
for magician in magicians:
  print(magician)

代码解释

先定义一个列表magicians,然后,又定义了一个for循环。定义循环的这行代码让Python从列表magicians中取出一个名字,并将其存储在变量magicians中。最后,让Python打印前面存储到变量magician中的名字。

运行结果

python中怎么在while中按键盘结束循环 python如何结束while循环_Python


2

一个Python字典可能只包含几个键-值对,也可能包含数百万个键-值对。鉴于字典可能包含大量的数据,Python支持对字典遍历,而遍历字典的方式有:遍历字典的所有键-值对

程序代码

#programing_languages.py

# 定义一个编程语言字典
programing_languages={
        'Guido van Rossum':'Python',
        'Sun':'Java',
        'D.Richie and K.Thompson':'C',
        'Bjame Sgoustrup':'C++',
        'Rasmus Lerdorf':'PHP'
        }

print("\n")

# 遍历字典的所有键-值对
for designer,language in programing_languages.items():
    print(language.title()+"'s designer is "+designer.title()+".")

print("\nThe following designers have been mentioned:\n")

# 遍历字典中的所有键
for designer in programing_languages.keys():
    print(designer.title())

print("\nThe following languages have been mentioned:\n")

# 遍历字典中的所有值
for language in programing_languages.values():
    print(language.title())

运行结果

python中怎么在while中按键盘结束循环 python如何结束while循环_for循环_02


while循环

for循环用于针对集合中的每个元素的一个代码块,而while循环不断地运行,知道指定的条件满足为止。

1

循环打印数字1到5

程序代码

#counting.py

current_number=1
while current_number<=5:
  print(current_number)
  current_number+=1

代码解释

首先将变量current_nmuber设置为1,指定从1开始数。接下来的while循环被设置成这样:只要current_number小于或等于5,就接着运行这个循环。循环中的代码的作用是:打印变量current_number的值,再使用代码current_number+=1(代码current_number=current_number+1的简写)将其值加1。

只要满足条件current_number<=5,Python就接着运行这个循环。由于1小于5,因此Python打印1,并将current_number加1,使其为2;由于2小于5,因此Python打印2,并将current_number加1,使其为3,以此类推。一旦current_number大于5,循环将停止,整个程序也将到此结束。

运行结果

python中怎么在while中按键盘结束循环 python如何结束while循环_Python_03


2

要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果即可,可使用break语句break语句用于控制程序流程,可使用它来控制哪些代码行将执行,哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。