码迷,mamicode.com
首页 > 编程语言 > 详细

python入门-WHILE循环

时间:2018-07-07 20:24:15      阅读:521      评论:0      收藏:0      [点我收藏+]

标签:选择   als   print   ase   nis   tin   nconf   number   response   

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 = "\nEnter ‘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 = "\nEnter ‘quit‘ to end the program"

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

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

 

4 使用break退出循环

prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(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("\n 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("\n 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("\n --poll results--")
for name,response in responses.items():
    print(name + "would like to climb" + response + ".")

 

python入门-WHILE循环

标签:选择   als   print   ase   nis   tin   nconf   number   response   

原文地址:https://www.cnblogs.com/baker95935/p/9277739.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!