繁体   English   中英

我应该如何使用“继续”命令来避免 python 中的无限循环?

[英]How should I use a 'continue' command to avoid an infinite loop in python?

我试图让程序接受一个年龄值,打印票价的响应,然后返回到输入提示以请求另一个年龄。

每次我输入年龄输入时,我都会得到一个无限循环? 我怎样才能以不同的方式处理它? 继续帮助吗?

为草率的格式等道歉; 这是我关于堆栈溢出的第一篇文章,我

ticket_age = input("\nTell me your age and I will sell you a ticket")


active = True
while active:
    age = int(ticket_age)

    if age < 3:
        print("You get a free ticket")


    elif age >= 3 and age <= 12:
        print("That will be $10 please")

    elif age > 12:
        print("That will be $15 please")

在您的程序中,您应该在while循环内的某处将active变量的值更改为false以破坏它。

试试这个:

ticket_age = input("\nTell me your age and I will sell you a ticket")


active = True
while active:
    age = int(ticket_age)

    if age < 3:
        print("You get a free ticket")


    elif age >= 3 and age <= 12:
        print("That will be $10 please")

    elif age > 12:
        print("That will be $15 please")

    else:
        break

欢迎! 正如评论所说,我们需要更多关于你要做什么的信息。 如果这只是一个简单的检查,那么您甚至不需要 while 循环。 您可以单独使用 if 语句,或者如果您想循环,您可以循环访问多个输入。 在您的情况下,您可以通过将活动值设置为 false 来退出。 否则,作为一些指针:在您使用的此类循环中,您不必设置active = True然后while active: ,您可以简单地执行while True: 但是你将不得不以某种不同的方式退出它。 也可以在收到输入后直接转换,比如ticket_age = int(input("\\nTell me your age and I will sell you a ticket")) ,或者str(input(..)) 对于第二个循环,您可以使用这样的语法: if 3 <= number <= 12:

您应该在循环内使用输入来执行该操作


while True:
    ticket_age = input("\nTell me your age and I will sell you a ticket")
    age = int(ticket_age)

    if age < 3:
        print("You get a free ticket")


    elif age >= 3 and age <= 12:
        print("That will be $10 please")

    elif age > 12:
        print("That will be $15 please")

暂无
暂无

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

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