''' Purpose: show a while statement ''' # set loop decision variable # this is our looking variable, set it to True by default # this is the condition to keep running the while loop runs # here we are looking for a 'yes' or a 'no' looking_for_a_yes_or_no = True # while loop is how you do the same actions (repeat) for some uncertain amount of time # until the testing expression is no longer True (aka the testing expression is False) # while ( testing expression ) : # while we are still looking for a 'yes' or a 'no' # we want to keep asking the user until we get a valid string that's either 'yes' or 'no' # if the user enters some other string, keep asking. Otherwise, we can stop asking # we don't know how long the loop will run for, that's why we use the while loop, instead of # a for loop while ( looking_for_a_yes_or_no == True ) : # repeat while looking # get cleaned up response reply = input( 'Enter (yes / no): ' ) # ask for an input while we are still looking # want to look for exactly 'yes' or 'no' reply = reply.strip() reply = reply.lower() print( 'reply =', reply ) # check for valid response. if ( reply in [ 'yes', 'no' ] ) : # if the reply is the string 'yes' or the string 'no' # got one - then we end our search --> end the while loop looking_for_a_yes_or_no = False # SET OUR LOOKING VARIABLE TO FALSE --> we are no longer looking # so it is False that we are still looking for a yes or no # --> while loop will exit --> go to line 46 # if the truth condition is not updated, THIS WILL RUN FOREVER (eventually crashes) # if this if statement is True, then we ignore the else part else: # else = reply is not the string 'yes' or the string 'no' print( 'reply was no good' ) # the while loop will restart if reply was not 'yes' or 'no' # when while loop finishes, print the reply print( reply ) # way 2 # ask for an input first reply = input( 'Enter yes/no: ' ) reply = reply.strip() reply = reply.lower() # while reply is not a string 'yes' or 'no' # 2 ways to express this condition: # reply not in ['yes', 'no] # reply != 'yes' or reply != 'no' (reply not equal to 'yes' OR reply not equal to 'no') while ( reply not in ['yes', 'no'] ): # print a message print( 'reply was no good' ) # then ask again and UPDATE THE VARIABLE THAT YOU USE IN THE CONDITIONAL # STATEMENT IN THE WHILE STATEMENT # if you do not update reply, then reply will continue to be the # string when you first asked the user # you NEED to update reply to the new value so that the while can eventually end # when the new reply string is a 'yes' or 'no' reply = input( 'Enter yes/no: ' ) reply = reply.strip() reply = reply.lower() # once reply is a string 'yes' or 'no', then print the reply print( reply )