0

As described in the title, I am unable to break out of the python (while) loop, and unsure why?

def display_menu(gbook):
    """
    """
    
    print("")
    print("Please choose an option below:")
    print("")
    print("1. Record a grade")
    print("2. Print all grades")
    print("3. Calculate GPA")
    print("4. Exit")
    print("_________________________________________")

    while True:
        print("")
        choice = input("Please select a numbered option from above")
   
        if re.match(r'^\d+$', choice):
            choice = int(choice)
            if choice in [1, 2, 3, 4]:
                break
  
    
        if choice == "1":
           record_grade(gbook)
        elif choice == "2":
           print_grades(gbook)
        elif choice == "3":
          calculate_gpa(gbook)
        elif choice == "4":
          exit()
        else:
          print("Invalid choice. Please try again.")

I was expecting once the proper entry was made, that I would be broken out of the loop.

Palinuro
  • 184
  • 1
  • 1
  • 15
  • So if you want to break out of the while loop on the event the user enters 4, replace ```exit()``` with ```break``` – itprorh66 Feb 22 '23 at 20:30
  • Is the problem that you always break or that you can't break. Cause it looks like you break if you enter a valid command. – JonSG Feb 22 '23 at 20:33
  • 1
    Your logic doesn't make sense. If they enter 1 through 4 you break out. Then none of the `if` statements will succeed (even if you fix the string vs. int problem), because you broke out in all those cases. – Barmar Feb 22 '23 at 20:48
  • The `if` statements at the end shouldn't be inside the `while` loop. – Barmar Feb 22 '23 at 20:48
  • 1
    You don't need regex to [check if a string is a number](https://stackoverflow.com/a/40097699/15032126). – Ignatius Reilly Feb 22 '23 at 20:50
  • As @Barmar said, the last `if` statements should go outside the `while` loop, except the last one: let the `print("Invalid choice. Please try again.")` inside the loop and after `break`, so it gets printed only when the response is not valid. – Ignatius Reilly Feb 22 '23 at 20:57
  • [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Ignatius Reilly Feb 22 '23 at 20:59

3 Answers3

1

You have 2 problems:

  1. See the answer of @NiziL

  2. You are comparing an integer to a string, that is always False

        choice = int(choice)
        # choice now is an integer !
        if choice in [1, 2, 3, 4]:
            break
    
     # now you compare it with a string,
     if choice == "1":
    

You should compare numbers with numbers such as choice == 1

Caridorc
  • 6,222
  • 2
  • 31
  • 46
  • If they enter "1" at the prompt what should happen since int("1") is in [1,2,3,4]? – JonSG Feb 22 '23 at 20:53
  • @JonSG I did not run it, but I expect it to break out of the loop – Caridorc Feb 22 '23 at 20:55
  • I think that is the crux of the issue. If you enter a valid command then the first if statement breaks one out of the loop and the second if statement is never done. – JonSG Feb 22 '23 at 20:57
  • 1
    @JonSG true, so most likely the condition on the if is reversed, so it should be `if choice not in [1, 2, 3, 4]: break` so it repeats when the input is wrong – Caridorc Feb 22 '23 at 20:59
1

The last if/elif section won't be reached.

Either you match de regexp, and so transform choice into an integer which can't be equals to a string (== "1" instead of == 1), or you won't match the rexgep, and so can't match == "1".
Hence, you'll either break the loop, or print "Invalid choice"

On a side note, try to avoid while True. It's really useful in very few cases, and the following version is far more readable:

choice = -1
while not choice in ["1", "2", "3", "4"]:
    choice = input("...")
NiziL
  • 5,068
  • 23
  • 33
0

Based on my observation, the break statement is executed only when the user enters a valid integer option from the given menu. If the user enters a string option that is not an integer, the program fails to break out of the loop and keeps executing. To address this issue, you can relocate the break statement to the end of the if block that verifies valid integer options and eliminate the if block that checks for string options.

K4nj
  • 114
  • 4