繁体   English   中英

如何使用条件测试退出while循环?

[英]How to use a conditional test to exit a while loop?

首先介绍一下程序本身:

  • 条件测试开始while循环(我必须使用条件测试来开始和结束循环,没有标志并且没有break语句)
  • 询问用户年龄(用户输入)
  • 根据用户输入,它会打印出不同的答案

我的问题是,如果用户输入为“ quit”,我希望程序结束。 用户输入除“ quit”外始终是一个int,因为该程序会检查用户的年龄。

这是我的代码:

prompt = "\nPlease enter your age to see the price for a ticket. \nEnter 'quit' when done: "

age = ""

while age != "quit":
    age = input(prompt)
    age = int(age)
    if age < 3:
        print("Your ticket is free.")
    elif age > 3 and age < 12:
        print("Ticket is $10")
    else:
        print("Ticket is $15")

这是我输入“ quit”作为输入时遇到的错误:

Please enter your age to see the price for a ticket.  Enter 'quit' when done: quit 
Traceback (most recent call last):   File "while_loops.py", line 60, in <module>
    age = int(age) ValueError: invalid literal for int() with base 10: 'quit'

在此先感谢您的时间和精力! 最好的问候HWG。

在尝试转换为int之前,请检查quit 在无限循环中运行,并在读取输入quit时中断它。

prompt = "\nPlease enter your age to see the price for a ticket. \nEnter 'quit' when done: "

while True:
    age = input(prompt)
    if age == "quit":
        break
    age = int(age)
    if age < 3:
        print("Your ticket is free.")
    elif age > 3 and age < 12:
        print("Ticket is $10")
    else:
        print("Ticket is $15")

符合附加标准的替代方案

不要使用'break'或变量作为标志

使用异常

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

    try:
        age = int(ageStr)
        if age < 3:
            print("Your ticket is free.")
        elif age > 3 and age < 12:
            print("Ticket is $10")
        else:
            print("Ticket is $15")
    except ValueError:
        pass

使用继续。
注意:这很不好,因为您在代码中指定并两次检查“退出”,并且控制流程过于复杂。

prompt = "\nPlease enter your age to see the price for a ticket. \nEnter 'quit' when done: "

age = ""

while age != "quit":
    age = input(prompt)
    if age == "quit":
        continue

    age = int(age)
    if age < 3:
        print("Your ticket is free.")
    elif age > 3 and age < 12:
        print("Ticket is $10")
    else:
        print("Ticket is $15")
while True:
    age = input("\nPlease enter your age to see the price for a ticket. \n Enter 'quit' when done: '"
    if age == 'quit':
        break
    # continue with the rest of your code

只需检查输入是否为“退出”,如果是,则跳出无限循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM