1

I want to validate an input to see whether it is a number (integer) or not. This is my code:

temp = input("Today's temperature:  ")

if int(temp):
    temperature = int(temp)
    if temperature >= 40:
        print("Too hot")
    elif temperature >= 30:
        print("Normal temperature")
    else:
        print("Too cold")
else:
    print("Invalid temperature")

If I enter a valid number, it will print the messages. However, if I enter a non-integer (alphabetical), I will get an error

Traceback (most recent call last):
  File "D:\test\Python\test2\conditional.py", line 3, in <module>
    if int(temp):
ValueError: invalid literal for int() with base 10: 'hi'

What should I do to validate the number and not get an error?

Is there a function or is there a library to do this?

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

1

✅ First I'd check whether the input is a digit with isdigit()
✅ Then I'd check whether the input is an instance of integer with isinstance()

# Since inputs are accepted as str by default, first we check if its a digit

if temp.isdigit(): 
    if isinstance(temp, int):
        # rest of your code

temp = input("Today's temperature:  ")

if temp.isdigit():
    if isinstance(temp, int):
        temperature = int(temp)
        if temperature >= 40:
            print("Too hot")
        elif temperature >= 30:
            print("Normal temperature")
        else:
            print("Too cold")
    else:
        print("Invalid temperature")
anjandash
  • 797
  • 10
  • 21