Alfred H. Alfred H. - 1 month ago 8
Python Question

How to get a user to exit out the while loop

I am trying to a while loop gooing, but then i went the user to enter 5 to exit out of the loop. I am in python 3

def main():
print("Welcome to the List Info Checker")
printMenu()
printValue = input("Please enter a number between 1 and 5(inclusive): ")
while printValue != 5:
if printValue == 1:
print("1")
elif printValue == 2:
# allTheSame()
print("2")
elif printValue == 3:
# allDifferent()
print("3")
elif printValue == 4:
# sortThis()
print("4")

main()

Answer

There are 2 ways to break out of a while loop

  1. Have the statement change in some way so that it is no longer True

  2. use the break command to break out of the 'lowest level loop'

Because the user input is only asked before the loop there is no way it could change after the loop started causing an endless loop. If the input was inside the loop it could be broken by the user putting a 5 in because it is asked every time the loop restarts:

printValue = input("Please enter a number between 1 and 5(inclusive): ")

while printValue != 5:



    if printValue == 1:
        print("1")
    elif printValue == 2:
       # allTheSame()
        print("2")
    elif printValue == 3:
       # allDifferent()
        print("3")
    elif printValue == 4:
       # sortThis()
        print("4")
    printValue = input("Please enter a number between 1 and 5(inclusive): ")