while 语句的三种控制/结束循环方式

while语句若一直满足条件,则会不断的重复下去。但有时,我们需要停止循环,则可以用下面的三种方式:

1.在while语句中设定条件语句,条件不满足,则循环自动停止:
ie: 只输出3的倍数的循环;范围:0到20.

current_number = 0

while current_number < 20:
    current_number += 1
    if current_number % 3 != 0:
        continue

    print(current_number)

敲黑板,敲黑板,重点在这里:

  1. 先将起始数字设为0,符合while条件语句中小于20的要求,开始进入循环;
  2. 循环中,每次将数字加1,然后进行测试;
  3. 运用if语句来检测加1后的数值,如果结果不等于0(也就是说不能被3整除,有余数)则会忽略下面的代码,并返回到循环的开头,而当除以3余数为0时,则会输出数字。
    输出结果:
    while 语句的三种控制/结束循环方式

2: break语句可以使用户退出循环:

prompt = "\nWhat is your favorite city?"
prompt += "\n(Enter 'quit' when you are finished.)"

while True:
    city = input(prompt)

    if city == 'quit':
        break
    else:
        print("I love" +city.title() + "!")

此循环在用户输入quit后会停止。


  1. 利用标识来控制while语句的结束时间
    ie: 假设我们需要点一些火锅的配菜,并在点单结束后退出点菜循环
prompt = "\nWhat would you like to order for your hotpot?"
prompt += "\n(Please enter 'quit' when you are finished.)"

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

    if message == 'quit':
        active = False
    else:
        print(message.title() +" added.")

先将acitve 定义为True,则可直接进入while循环。当输入quit时,active变为false,循环结束。否则会直接输出“XX added.”

转载于:https://blog.51cto.com/13595859/2074481

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值