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

Question:

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

Asked By: jonahpocalypse

||

Answers:

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
Answered By: Samathingamajig

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
Answered By: jonahpocalypse
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.