0

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")
```
1
  • Side note: your use case seems better fit for sys.exit (requires import sys line) rather than exit see further discussion stackoverflow.com/questions/6501121/… Commented May 26, 2022 at 7:58

2 Answers 2

4

Basically, if the user inputs a letter instead of a number I want the code to say "please try again!"

The best way to do this is to isolate that in a function:

def ask_user(prompt, verify, convert, reprompt="please try again!", limit=5):
    value = input(prompt)
    if verify(value):
        return convert(value)
    for i in range(limit):
        print(reprompt)
        value = input(prompt)
        if verify(value):
            return convert(value)
    raise RuntimeError('Exceeded input attempt limit')

    
Sign up to request clarification or add additional context in comments.

1 Comment

Really just a small suggestion for improvement: Replace the iteration variable i with an underscore since it is not used.
0

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")

Some questions in the comments:

ValueError as e: assigns the exception to the variable e. We can then handle the exception and do some logging or do something else with the exception:

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

output:

Enter Degree Amount: t
Exception message: 
could not convert string to float: 't'
Not a valid number. Try again

3 Comments

I like the validation for the option, thank you. Can you clarify on why the first two exits contain a 1 in the parenthesis or what 'as e' stands for?
the param to exit() is the return code of the application. exit code 0 is success. As in everything worked fine. exit code that is non 0 means something broke. Its just a nice way to show the running app that something broke. In this case its because the input was invalid.
the except ValueError as e: means catch the exception of type ValueError and assign the exception to the variable e. Ive updated the answer with some info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.