Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading