仅当它是某个变量时如何转换用户输入?

How do I convert an user input only if its a certain variable?

好的,我有下面显示的代码,我在其中询问用户温度。他们显然必须回答数字,但如果他们不回答,我想开个玩笑。如何仅转换特定类型的变量?

base_temp = input("What is the temperature outside?:" )
if base_temp == str:
    print("ok that is not a real temperature.")
    print("you stupid liar i HATE you.")
else: temp = int(base_temp)

if temp >= 0 and temp <= 30 :
    print("that's nice. Go outside. NOW!")
if temp >= 31 or temp < -10 :
    print("okay you can stay inside.")
    print("you still need to go outside though, stinky.")

您可以使用内置的 isdigit() 函数,如果给定的字符串仅包含数字,则该函数 returns 为真,例如:

if base_temp.isdigit():
    print("valid temp")
else:
    print("invalid temp")

使用异常处理来做到这一点。稍微修改一下代码,希望对你有帮助。

它也可以处理负数。

base_temp = input("What is the temperature outside?:" )

try:
    temp = int(base_temp)
    if temp >= 0 and temp <= 30 :
        print("that's nice. Go outside. NOW!")
    if temp >= 31 or temp < -10 :
        print("okay you can stay inside.")
        print("you still need to go outside though, stinky.")
        
except ValueError:
    print("ok that is not a real temperature.")
    print("you stupid liar i HATE you.")