-2

I'm building a budget tool. If the user were to enter the wrong number for the budget, the whole program crashes and gives an error message. I would like to add a loop or something else to have the program loop back and ask the question again, rather than it crashing if given intangible information. I've tried while loops but it doesn't seem to work


while answer != "yes" or answer == "Yes" or answer == "YES":
   print("Hmmm, okay. Try again.")
   answer = input("Ready to budget your travel expenses? ")

budget = int(input("What's your budget? $")**
Harper Avery
  • 11
  • 1
  • 4
  • What is the error message it gives? – M-Chen-3 Feb 09 '21 at 23:58
  • 1
    Error Message: Traceback (most recent call last): File "main.py", line 70, in budget = int(input("What's your budget? $")) ValueError: invalid literal for int() with base 10: 'gh' – Harper Avery Feb 10 '21 at 00:00
  • 1
    Your comparisons in the `while` conditions are inconsistent, and the conjunctions are wrong. – Prune Feb 10 '21 at 00:10

1 Answers1

1

Put the input instead a while True loop, and break once you get the input you're looking for. Here's a simple example:

while True:
     answer = input("Ready to budget your travel expenses? ")
     if answer.lower() == "yes":
         break
     print("Hmmm, okay.  Try again.")

while True:
    try:
        budget = int(input("What's your budget? $"))
        break
    except ValueError:
        print("Nope, that's not a number.")
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • 1
    The beginning part of the code works correctly. However, when the budget code is set u with "int," if the user enters letters instead of numbers, the program crashes – Harper Avery Feb 10 '21 at 00:01
  • What do you want it to do instead? – Samwise Feb 10 '21 at 00:04
  • the problem is with the budget variable – Harper Avery Feb 10 '21 at 00:04
  • when the user is prompted to enter a number for the budget, if they enter a letter.. the program crashed. Instead, I need to make it ask until a number s given – Harper Avery Feb 10 '21 at 00:05
  • 1
    Just use the same technique that was used for getting the "yes". I'll update the answer, hopefully seeing two examples in a row will help. :) – Samwise Feb 10 '21 at 00:06