pythonintegernegative-number

how to check if an input is an integer (including negative and decimal inputs)


I want to convert an input from Celsius to Fahrenheit but I don't understand how to accept negative and decimal inputs while also eliminating the non digit inputs like 'abc'.

temp = input('enter a temperature in C: ')

if temp.isdigit():
    temp = int(temp)
    print(f'{temp * 1.8 + 32} F')
else:
    print('not a temp')

Solution

  • You can do something like this. I dont know if its the best approach, but it should work

    def is_valid_temperature(temperature):
        try:
            float(temperature)  # Convert the inputted temperature to a float
            return True
        except ValueError: # If its something like abc, this will catch the exception and return False
            return False
    
    def convert_celsius_to_fahrenheit():
        temp = input('Enter a temperature in Celsius: ')
        
        if is_valid_temperature(temp):
            temp = float(temp)  # Now that we know that it's valid and it will not crash, we can convert the input to float.
            fahrenheit = temp * 1.8 + 32
            print(f'{temp}°C is equal to {fahrenheit}°F')
        else:
            print('Invalid input. Please enter a valid number.')
    
    # Call the function with our program
    convert_celsius_to_fahrenheit()
    

    If you want, you can do an improvement: Do separation of concerns, by separating the user input from the convert_celsius_to_fahrenheit function.