try:
int(days)
except:
print('Invalid input. A integer value was expected. Try again.')
days = (input("Enter the number of days: ", ))
How do I make this try statement loop until true?
try:
int(days)
except:
print('Invalid input. A integer value was expected. Try again.')
days = (input("Enter the number of days: ", ))
How do I make this try statement loop until true?
I suggest putting your logic in the try
block, and ONLY printing the error message on exception:
while True:
try:
days = int(input("Enter the number of days: "))
break
except ValueError:
print("Invalid input. An integer value was expected. Try again.")
Also, you should never use a bare except
. It is generally considered bad practice.
Wrap it in a while
loop like this:
while True: # Don't exit until `break` is reached!
days = input("Enter the number of days: ", ) # Move this here so `days` is always defined
try:
num_days = int(days) # Save to a variable for later use
break # If the conversion succeeded, it will run this and exit the loop
except ValueError: # If the conversion failed (always specify a specific exception!), print the below:
print('Invalid input. A integer value was expected. Try again.')
Make a while statement and a variable to end it after int(days):
days = int(input("Enter the number of days: "))
done = False
while done == False:
try:
int(days)
done = True
except:
print('Invalid input. A integer value was expected. Try again.')
days = (input("Enter the number of days: ", ))