Home > OS >  Need help getting the input to loop after a failed validation in Python
Need help getting the input to loop after a failed validation in Python

Time:10-18

I'm making a program for school, and in one part I'm unable to get the input to loop back so that the user can edit their answer, and it just skips ahead to the next input after displaying the error message. I've tried every fix I can think of, but nothing seems to be working.

Here's the code and how it runs:

enter image description here

CodePudding user response:

Use continue to go back to the start of the loop:

while True:
  InvDateStr = input("sfsdofjsadofj")

  if InvDateStr == "": # this error should be first
    print("can't be blank")
    continue

  try:
    InvDate = # baifaisjfoa
  except:
    print("that error")
    continue

  break

# rest of code

CodePudding user response:

Fix:

while True: InvDateStr = input("Enter the invoice date (YYYY-MM-DD): ")

if InvDateStr == "":
    print("Invoice date cannot be blank. Please re-enter.")


try:
    InvDate = datetime.datetime.strptime(InvDateStr, "%Y-%m-%d")
except:
    print("Date must be in YYYY-MM-DD format. Please re-enter.")
    continue

break
  • Related