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.")
CodePudding user response:
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")
CodePudding user response:
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.")