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 not make the program restart after a value error?

So I recently started coding and just learned about ‘try’ and ‘except’ for ‘ValueError’. I made this calculator but it restarts if you don’t input an int on the ‘second’ input. How do I make it ask for pnly the ‘second’ variable instead of asking for the first one again?

while True:
    try:
        first = int(input("First: "))
        second = int(input("Second: "))
        sum = first + second
        print(f"Sum: {sum}")
        break
    except ValueError:
        print("I didn't understand that")

I tried this but it just asked for the second variable then restarted the program

while True:
    try:
        first = int(input("First: "))
        second = int(input("Second: "))
        sum = first + second
        print(f"Sum: {sum}")
        break
    except ValueError:
        print("I didn't understand that")
        int(input("Second: "))

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

>Solution :

Use a separate while with try/except blocks for the two prompts. And since you are doing the same thing multiple times, put the common part in a function

def get_input(prompt, cast_to=int):
    while True:
        try:
            return cast_to(input(prompt))
        except ValueError:
            print("I didn't understand that")

first = get_input("First: ")
second = get_input("Second: ")
sum = first + second
print(f"Sum {sum}")
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