Search code examples
pythonvariables

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

Solution

  • You could use the built in isdigit() function which returns true if the given string consists of only digits, so for an ex:

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