Home > other >  do not understand two lines of code from Python
do not understand two lines of code from Python

Time:03-07

I do not understand the quite_program = False and quite_program = True. What do they mean? For this code, I think it will execute the code chunk, while not quit_program but I do not know how to understand it. It means if quit_program is not False? I kind of confuse and thanks so much for your help.

def print_menu():
    print("Today's Menu:")
    print('   1) Gumbo')
    print('   2) Jambalaya')
    print('   3) Quit\n')

quit_program = False

while not quit_program :
    print_menu()
    choice = int(input('Enter choice: '))
    if choice == 3 :
        print('Goodbye')
        quit_program = True
    else :
        print('Order: ', end='')
        if choice == 1 :
            print('Gumbo')
        elif choice == 2 :
            print('Jambalaya')
        print()

CodePudding user response:

The variable quit_program = False is defined so that when the code reaches the while loop and checks if the condition is True, it enters the loop (because not False = True). Once inside the loop, it will continue running and checking for this condition every time it starts. If quit_program is changed to True, then the next time it checks the condition at the start of the while loop, it will determine it is False (not True = False) and skip the loop. Since there is no more code after the loop, the program ends normally.

CodePudding user response:

In your program, quit_program is used to stop the execution of the program as desired. When checking while loop condition initially quit_program = False then not quit_program gives True.

The while loop keeps exciting until the quit_program = True. If quit_program = True then not quit_program gives False and then while loop will ends the execution(running). It means this while loop ends only if the choice == 3 condition is True.

Therefore, your program is executing(running) until you give the input as 3.

CodePudding user response:

that's pretty simple..just like in any other programming language like C , CPP, JAVA...we often use 'flag' right?...BIngoo ...so just like that here they've made use of the 'quit_program' boolean type variable.. clearly:

while not quit_program :

means in a while loop there's also a 'not' that means whenever the condition satisfies its going to return false...so while not quit_program(quit_program is false ..so it returns true-> you get to enter the loop..there you go on printing the stuff in the

def print_menu():

cool? so next on, the code goes on executing next set of lines in the code->

choice = int(input('Enter choice: '))
if choice == 3 :
    print('Goodbye')

after this, the quit_program if set to true!!! here's the catch-> from now on->>> while not quit_program : will be returning False!!

  • Related