首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法计算出这个无限的循环

无法计算出这个无限的循环
EN

Stack Overflow用户
提问于 2022-05-11 17:52:46
回答 3查看 38关注 0票数 -1

我有这样的代码:

代码语言:javascript
复制
active = True
print("Hello, this is the pricing system for the theater.")
print("Depending on your age, your pricing will vary.")
print("Please type 'exit' to termiante the program")
toddler = "Below 3 = Free." 
kid = "3-2 = $10"
big_kid = "12+ = $15"
prompt = "Please enter your age: "

while active:
    message = input(prompt)
    if message == "exit":
        break
    if message != type(int):
        print("Int only")
        continue
    message = int(message)

    if message < 3:
        print(toddler)
    elif message > 3 and message < 12:
        print(kid)
    else:
        print(big_kid)

我基本上是想告诉python,如果输入的值不是整数,请返回开始,输入一个int。然而,即使用户确实放置了int,它仍然告诉我“仅为int”。我在这里做错什么了?

EN

回答 3

Stack Overflow用户

发布于 2022-05-11 17:56:54

尝试使用message.isnumeric()而不是使用!=操作符检查它

票数 1
EN

Stack Overflow用户

发布于 2022-05-11 17:57:43

条件type(int)不能为真,因为您有来自inputstr,您宁愿尝试str.isdigit()

代码语言:javascript
复制
while True:
    message = input(prompt)
    if message == "exit":
        break
    if message.isdigit():
        print("Int only")
        continue
        
    message = int(message)
    if message < 3:
        print(toddler)
    elif 3 <= message < 12:
        print(kid)
    else:
        print(big_kid)
票数 1
EN

Stack Overflow用户

发布于 2022-05-11 17:58:27

您也可以使用try-except块。

代码语言:javascript
复制
active = True
print("Hello, this is the pricing system for the theater.")
print("Depending on your age, your pricing will vary.")
print("Please type 'exit' to termiante the program")
toddler = "Below 3 = Free." 
kid = "3-2 = $10"
big_kid = "12+ = $15"
prompt = "Please enter your age: "

while active:
    message = input(prompt)
    print(message)
    if message == "exit":
        break
    try:
        int(message)
    except ValueError:
        print("Int only")
        continue
    message = int(message)

    if message < 3:
        print(toddler)
    elif message > 3 and message < 12:
        print(kid)
    else:
        print(big_kid)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72205525

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档