Python学习入门之While循环

Python学习入门之While循环

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

current_num = 1
while current_num <= 10:
    print(current_num)
    current_num += 1

让用户选择何时退出

prompt = "\nTell me something,and I wil repeat it back to you "
prompt += "\n( Enter 'quit' to exit the program ): "

active = True
message = ""
while active :
    message = input(prompt)

    if message != "quit":
        print(message)
    else:
        active = False

使用break退出循环

使用break语句立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何。

prompt = "\nPlease enter the name of the city you have visited "
prompt += "\n( Enter 'quit' to exit the program ): "

while True:
    city = input(prompt)
    if city == "quit":
        break
    else:
        print("I'd like to go to " + city.title()+"!")

在循环中使用continue

使用continue 语句返回到循环开头,并根据条件测试结果决定是否继续执行循环,不像break语句那样不再执行余下的代码并退出整个循环

number = 0
while number < 10:
    number += 1
    if number % 2 == 0:
        continue
    print(number)

每一个while 循环都必须有停止运行的途径。避免编写无限循环,务必对每一个while循环进行测试,确保它按预期那样结束。

使用while 循环来处理列表和字典

在列表之间移动元素

unconfirm_user = ["zr","hc","ws","hj","fz"]
confirm_user = []

while unconfirm_user:
    current_user = unconfirm_user.pop()
    print("Verifying user : " + current_user)
    confirm_user.append(current_user)

print("\nThe follwing user have been confirm: ")
for user in confirm_user:
    print(user)

删除包含特定值的所有列表元素

favority_language = ["C++","java","java","C","python","java","C#","python"]
while "java" in favority_language:
    favority_language.remove("java")

print(favority_language)

使用用户输入来填充字典

reponses = {}
while True:
    name = input("\nWhat's your name: ")
    reponse = input("which mountain would you like to climb someday:")
    reponses[name] = reponse

    repeat = input("Would you like to let another person respond?(yes/no)")
    if repeat == "no":
        break

print("---------Poll result----------- ")
for name,reponse in reponses.items():
    print(name + " would you like to climb " + reponse)

猜你喜欢

转载自blog.csdn.net/fzx1123/article/details/86321482