python入门-WHILE循环

Posted baker95935

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python入门-WHILE循环相关的知识,希望对你有一定的参考价值。

1 使用while循环

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

 

2 让用户选择退出

prompt = "tell me somthing, and i will repeat it back to you"
prompt = "
Enter ‘quit‘ to end the program"

message = ""
while message != quit:
    message=input(prompt)

    if message!=quit:
        print(message)

 

3 使用标志

prompt = "tell me somthing, and i will repeat it back to you"
prompt = "
Enter ‘quit‘ to end the program"

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

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

 

4 使用break退出循环

prompt = "
Please enter the name of a city you have visited:"
prompt += "
(enter ‘quit‘ when you are finished.)"

while True:
    city = input(prompt)

    if city == quit:
        break
    else:
        print("I‘d love to go to" + city.title() + "!")

 

5 在循环中使用continue

current_number = 0
while current_number < 10:
    current_number += 1
    if current_number % 2 ==0:
        continue

    print(current_number)

 

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

unconfirmed_users = [alice,brian,candace]
confirmed_users = []

while unconfirmed_users:
    current_user = unconfirmed_users.pop()

    print("verifying user:" + current_user.title())
    confirmed_users.append(current_user)

print("
 the following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

 

7 删除特定的列表元素

pets = [dog,cat,dog,goldfish,cat,rabbit,cat]
print(pets)

while cat in pets:
    pets.remove(cat)

print(pets)

 

8使用用户输入来填充字典

responses = {}
polling_active = True

while polling_active:
    name = input("
 what is your name?")
    response = input("which mountain would you like to climb someday")

    responses[name] = response

    repeat = input("would you like to let another person respond?(yes or no")
    if repeat == no:
        polling_active = False

print("
 --poll results--")
for name,response in responses.items():
    print(name + "would like to climb" + response + ".")

 

以上是关于python入门-WHILE循环的主要内容,如果未能解决你的问题,请参考以下文章

python基础入门while循环 格式化 编码初识

python入门—认识while循环及运用

python入门到精通python循环语句While,for的使用

python入门到精通python循环语句While,for的使用

值得收藏!16段代码入门Python循环语句

python入门-WHILE循环