jonahpocalypse
jonahpocalypse

Reputation: 77

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

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

Upvotes: 0

Views: 173

Answers (2)

jonahpocalypse
jonahpocalypse

Reputation: 77

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

Upvotes: 0

Samathingamajig
Samathingamajig

Reputation: 13293

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

Upvotes: 1

Related Questions