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