简体   繁体   English

只有当它是某个变量时,我如何转换用户输入?

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

okay so I have the code shown below, where I ask the user for the temperature.好的,所以我有下面显示的代码,我在其中向用户询问温度。 they obviously have to anwser in numbers, but I want to put in a joke response for if they don't.他们显然必须回答数字,但如果他们不这样做,我想开个玩笑。 how can I convert a variable only if it's of a certain type?仅当变量属于某种类型时,如何才能转换它?

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.")

You could use the built in isdigit() function which returns true if the given string consists of only digits, so for an ex:您可以使用内置的isdigit()函数,如果给定的字符串仅包含数字,则该函数返回 true,因此对于 ex:

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

Use exception handling to do this.使用异常处理来做到这一点。 modified the code a bit, hope it helps.稍微修改了一下代码,希望对你有帮助。

it can also handle negative numbers.它还可以处理负数。

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.")

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

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