(Python) Basic way on how to end code if incorrect user input?

this is my first time trying code. I viewed a basics on the foundations of python and I decided to start with something simple. I’m making a Fahrenheit to Celsius calculator and vise versa. As you can see in the code below, I want the program to stop running if the user inputs the incorrect variable at the two times they are asked for user input. I used an if, elif, and else statement if the user doesn’t display an A or B, however, anything that I tried handling the integer asked always ends the code in a ValueError. Basically, if the user inputs a letter instead of a number I want the code to say "please try again!"

```
# printing all conversion options
print("Conversion Options")
print("A. Celcius to Fahrenheit")
print("B. Fahrenheit to Celcius")

# Selecting the options
option = input("Select Option A or B: ")

# Value of Degree in conversion
value = float(input("Enter Degree Amount: "))

# Conversion and option
if option == 'A':
new_value = (value * 1.8) + 32

elif option == 'B':
    new_value = (value - 32) * 5/9

else:
    print("You did not select A or B. Try again!")
exit()

# Enjoy your results
print("Conversion is now complete!")
print(new_value,"degrees")
```

>Solution :

You need input validation. I’ve gone with the try except method of doing this but you can also capture the input first and then check if its a numbers instead of relying on the exception. I’ve also added validation to option so that users don’t have to input a number if the option is wrong from the start.

# printing all conversion options
print("Conversion Options")
print("A. Celcius to Fahrenheit")
print("B. Fahrenheit to Celcius")

# Selecting the options
option = input("Select Option A or B: ")
if option not in ['A', 'B']:
    print('Not a valid option. Try again')
    exit(1)

# Value of Degree in conversion
try:
    value = float(input("Enter Degree Amount: "))
except ValueError as e:
    print('Not a valid number. Try again')
    exit(1)

# Conversion and option
if option == 'A':
    new_value = (value * 1.8) + 32
elif option == 'B':
    new_value = (value - 32) * 5/9
else:
    print("You did not select A or B. Try again!")
    exit()

# Enjoy your results
print("Conversion is now complete!")
print(new_value, "degrees")

Leave a Reply