PYTHON中的while()循环

1、举个例子,你可以使用while()循环来数数:

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

从1数到5:

1
2
3
4
5

2、那么如何让用户选择何时退出呢?

prompt="\nTell me something, and I will repeat it back to you:"
prompt+="\nEnter 'quit' to end the program."
message=""
while message!='quit':
    message=input(prompt)
    print(message)

这里我们定义了一条提示消息,告诉用户他有两个选择:要么输入一条消息,要么输入退出值(这里是quit)

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program.Hello everyone1
Hello everyone1

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program.Hello again
Hello again

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

Process finished with exit code 0

3、使用bresk退出循环

要立即退出while循环,不再运行循环中的余下代码,也不管条件测试的结果如何,可使用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()+"!")
Please enter the name of a city you have visited: 
(Enter 'quit' when you are finished)new york
I'd love to go to New York!

Please enter the name of a city you have visited: 
(Enter 'quit' when you are finished)san francisco
I'd love to go to San Francisco!

Please enter the name of a city you have visited: 
(Enter 'quit' when you are finished)quit

Process finished with exit code 0

4、在循环中使用continue

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

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

    print(current_number)

结果:

1
3
5
7
9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值