在一个条件语句中两次更改数据类型(Python)

huangapple go评论63阅读模式
英文:

Changing data types twice in one conditional statement (Python)

问题

很基本的问题,但我正在尝试编写一个简单的while循环,首先需要一个int类型的输入。但为了跳出循环,我希望能够输入字符串'quit'。我该怎么做?

active = True
while active:
    age = input("请输入您的年龄:")
    if age.lower() == 'quit':
        print("退出程序")
        active = False
    else:
        age = int(age)
        if age < 3:
            print("票价免费。\n")
        elif 3 <= age <= 12:
            print("票价为10美元。\n")
        elif age > 12:
            print("票价为15美元。\n")
英文:

Pretty basic question, but I am trying to write a simple while loop in which I first need an input as int.
But in order to break out of said loop, I want to be able to write 'quit' which is a string. How do I do this?

active = True
while active:
    age = int(input(&quot;Please state your age: &quot;))
    if age &lt; 3:
        print(&quot;The ticket is free.\n&quot;)
    elif 3 &lt;= age &lt;= 12:
        print(&quot;The ticket is 10 dollars.\n&quot;)
    elif age &gt; 12:
        print(&quot;The ticket is 15 dollars.\n&quot;)
    elif age == &#39;quit&#39;:
        print(&quot;Quit program&quot;)
        active = False

I tried putting the age in the last elif in a str(age) function, which I believed would turn input age back to a string, but it gives a value error. Any tips?

答案1

得分: 0

你可以捕获ValueError异常,但为什么总是在不需要引发异常的情况下将str转换为int时引发异常呢?最好的方法是使用isdecimal()

active = True
while active:
    age_input = input("请输入您的年龄:")
    if age_input == 'quit':
        print("退出程序")
        active = False
    elif age_input.isdecimal():
        age = int(age_input)
        if age < 3:
            print("门票免费。\n")
        elif 3 <= age <= 12:
            print("门票为10美元。\n")
        else:
            print("门票为15美元。\n")
    else:
        print("无效输入。请输入整数或 'quit'。\n")

更多信息

似乎不需要active变量。你可以使用while True,然后在检测到“quit”时使用quit()exit()查看更多信息

英文:

You could catch the ValueError exception, but why always raise an exception casting the str into int when it is not needed to raise it?
The best approach is to use isdecimal():

active = True
while active:
    age_input = input(&quot;Please state your age: &quot;)
    if age_input == &#39;quit&#39;:
        print(&quot;Quit program&quot;)
        active = False
    elif age_input.isdecimal():
        age = int(age_input)
        if age &lt; 3:
            print(&quot;The ticket is free.\n&quot;)
        elif 3 &lt;= age &lt;= 12:
            print(&quot;The ticket is 10 dollars.\n&quot;)
        else:
            print(&quot;The ticket is 15 dollars.\n&quot;)
    else:
        print(&quot;Invalid input. Please enter an integer or &#39;quit&#39;.\n&quot;)

More info

It doesn't seem active variable is needed. You could use while True and then use quit() or exit() when "quit" is detected. See more info

答案2

得分: -1

你需要先检查 age 是否是一个字符串,然后检查它是否是一个整数。你得到一个 ValueError 是因为你调用了 int(input()),当输入不是整数时就会发生错误。你可以先检查字符串是否是 &quot;quit&quot;,然后再继续程序,为了防止出现 ValueError,即使用户输入的不是 &quot;quit&quot; 或整数,也可以将代码的其余部分包装在 try ... except ... 中。

active = True
while active:
    age_input = input("请输入您的年龄:")
    if age_input == 'quit':
        print("退出程序")
        active = False
    else:
        try:
            age = int(age_input)
            if age < 3:
                print("票价免费。\n")
            elif 3 <= age <= 12:
                print("票价为10美元。\n")
            elif age > 12:
                print("票价为15美元。\n")
        except ValueError:
            print("无效输入。请输入整数或 'quit'。\n")
英文:

You need to check if age is a string first, then check if it is an integer. You're getting a ValueError because you're calling int(input()), which causes the error when the input is not an integer. You can first check if the string is &quot;quit&quot; before continuing with the program and also to prevent ValueError's from occurring even if the user types something that isn't &quot;quit&quot; or an integer, wrap the rest of the code in a try ... except ....

active = True
while active:
    age_input = input(&quot;Please state your age: &quot;)
    if age_input == &#39;quit&#39;:
        print(&quot;Quit program&quot;)
        active = False
    else:
        try:
            age = int(age_input)
            if age &lt; 3:
                print(&quot;The ticket is free.\n&quot;)
            elif 3 &lt;= age &lt;= 12:
                print(&quot;The ticket is 10 dollars.\n&quot;)
            elif age &gt; 12:
                print(&quot;The ticket is 15 dollars.\n&quot;)
        except ValueError:
            print(&quot;Invalid input. Please enter an integer or &#39;quit&#39;.\n&quot;)

huangapple
  • 本文由 发表于 2023年3月15日 20:23:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744643.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定