首页 > 解决方案 > Python3:如何获得用户的重复响应并再次运行循环

问题描述

首先,我真的很抱歉提出这样一个微不足道的问题。我对编程完全陌生。我正在尝试学习一些 Python。我正在关注的书是“ Python Crash Course - 2nd Edition ”。我希望你和我裸露。我试图解决一个问题。问题如下,

电影院根据一个人的年龄收取不同的票价。3岁以下的人,门票免费;如果他们在 3 到 12 岁之间,则票价为 10 美元;如果他们超过 12 岁,票价为 15 美元。编写一个循环,询问用户的年龄,然后告诉他们电影票的价格。

我的目标

其实我解决了这个问题。当用户输入不是 int 时,我还设法通过使用 isdigit() 方法进行了一些错误处理,这在问题中没有被问到。现在我正在尝试实现类似我的程序应该要求用户进行第二次响应的东西。如果用户说是,我的循环应该再次运行,如果不是,它应该结束。我真的很抱歉弄了这么久。我只是想尽可能清楚。提前致谢!

注释块是我尝试过的。

编码:

print ("**********Welcome to Super Cinemas**********")
prompt = ("Enter your age to check for ticket price. ")
prompt += ("Enter 'exit' to quit. " )

age = input (prompt)
while age != 'exit':
    if age.isdigit() != True:
        print("Invalid input, please try again..")
        age = input (prompt)
    elif age.isdigit() == True: 
        age = int (age)
        if age < 3:
            print ("Voila, your tickets are free!")
            break
        elif age >= 3 and age <= 12:
            print ("The cost of the ticket is $10")
            break
        elif age >= 13 and age <= 90:       
            print ("The cost of the ticket is $15")
            break
        else: 
            print ("Sorry, exceeding age limits..")
            break
    # repeat = input ("Do you wanna check more? y/n ")
    # if repeat == 'y':
        # continue
    # else:
        # break

标签: python

解决方案


首先,您有一个获取年龄并给出结果的循环,因此获取年龄应该在 while 循环内。

您的年龄验证错误,假设您没有输入正确的年龄(非数字)并且程序要求另一个,但它会要求在之后继续循环而不是给出结果,这可以通过使用 continue 而不是得到另一个年龄。

如果您没有breakand continue,您的 while 循环将继续直到输入 end .

您不需要处理年龄的 if 语句中的 break 语句,如果其中任何一个被执行,则不会检查其他语句。你为什么使用它们?

如果你得到'y',循环会自动继续,所以你不需要显式地放置 continue 语句。

您可以简化一些表达式:

age >= 13 and age <= 903 <= age <= 12

if age.isdigit() != Trueif not age.isdigit()

代码

while True:
    age = input(prompt)
    if age.isdigit() != True:
        print("Invalid input, please try again..")
        continue
    elif age.isdigit() == True: 
        age = int(age)
        if age < 3:
            print("Voila, your tickets are free!")
        elif age >= 3 and age <= 12:
            print("The cost of the ticket is $10")
        elif age >= 13 and age <= 90:
            print("The cost of the ticket is $15")
        else: 
            print("Sorry, exceeding age limits..")
    repeat = input("Do you wanna check more? y/n ")
    if repeat != 'y':
        break

推荐阅读