首页 > 编程语言 > 详细

python while 循环学习

时间:2020-06-14 10:42:59      阅读:53      评论:0      收藏:0      [点我收藏+]

 >要求输入偶数,限制错误3次

p = int(input("请输入偶数 :"))

while p % 2 ==0:
    print("一次就对了 \n。")

    break
else:
    int(input("请在输入一次: "))

    while p % 2 == 0:
        print("输入正确。")
        break
    else:
        p = int(input("最后一次机会: "))
        if p % 2 == 0:
            print("恭喜您,终于输对了.")
        else:
            print("请3天后再试。")

请输入偶数 :3
请在输入一次: 5
最后一次机会: 7
请3天后再试。

 

 >未达到条件一直循环

#只要current_number 小于5就一直循环
current_number = 1

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


1
2
3
4
5

 

>以while True来循环,False来截止程序

prompt = "\nTell 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)




Tell me somthing, and I will repeat it back to you : 
Enter quit to end the program.w
w

Tell me somthing, and I will repeat it back to you : 
Enter quit to end the program.quit

 

>break 跳出循环

prompt = "\nTell me somthing, and I will repeat it back to you : "
prompt += "\nEnter ‘quit‘ to end the program."

while True:
    city = input(prompt)
    if city == "quit":
        break
    else:
        print("I‘d love to go to " + city.title()+ "!") #这里千万不要再加输入,否则quit后需要再次执行quit

Tell me somthing, and I will repeat it back to you : 
Enter ‘quit‘ to end the program.wuhang
I‘d love to go to Wuhang!

Tell me somthing, and I will repeat it back to you : 
Enter ‘quit‘ to end the program.guangzhou
I‘d love to go to Guangzhou!

Tell me somthing, and I will repeat it back to you : 
Enter ‘quit‘ to end the program.quit
 

 

>continue

# -个从1数到10,但是只打印其中的奇数循环

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

    print(current_number)


1
3
5
7
9

技术分享图片

 

>while 循环列表,最佳到新的列表

#创建一个待验证用户
#和一个存储验证用户的列表

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

#验证每个用户直到,用户验证完成为止
#每个验证过的用户都会移动到已经验证过的用户列表
while unconfirmed_users:
    current_user = unconfirmed_users.pop()

    print("Verifying user: " + current_user.title())
    confiremed_users.append(current_user)

print(confiremed_users)
print(unconfirmed_users)
# Verifying user: Candace
# Verifying user: Brian
# Verifying user: Alice
# [‘candace‘, ‘brian‘, ‘alice‘]
# []



#显示已验证用户
for confirmed_user in confiremed_users:
    print(confirmed_user.title())

# Candace
# Brian
# Alice

 

>

python while 循环学习

原文:https://www.cnblogs.com/zhenyu1/p/13123582.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!