''' Purpose: play guess a number ''' # specify max number # n = 100000 # start the game # print( 'Think of a number from 0 to', n ) # While Loops # Loops that run infinitely unless the condition is set to False # The condition in parentheses must be True in order for the loop to continue running # and repeating the statements indented into it # while ( condition ): # repeated statements # condition = False (this will stop the loop) still_looking_for_number = True lowest_possible_value = 0 highest_possible_value = 100000 print( 'Think of a number between', lowest_possible_value, 'and', highest_possible_value ) print() while( still_looking_for_number == True ): # The while loop will run so long as this boolean is True middle_value = ( lowest_possible_value + highest_possible_value ) // 2 # Ask the user if the middle value is their number prompt = 'Is your number ' + str( middle_value ) + ' (yes/no)? ' reply = input( prompt ) # The user will answer yes or no # If we have guessed the number (reply was 'yes'), we want to stop asking the user! We found it! if ( reply == 'yes' ): print( 'We got it!' ) still_looking_for_number = False # Set the variable that keeps running the loop to False so we exit the while loop # If not (reply was 'no'), we need to keep guessing. else: # This part resets the range of guessing to ask again! (based on the lowest possible value and highest possible value) # We want to ask the user if it's less than or greater than the middle value we just guessed prompt = 'Is your number less than ' + str( middle_value ) + ' (yes/no)? ' reply = input( prompt ) # Ask the user is their number is less than the middle value # If the user said it's less than the current middle value if ( reply == 'yes' ): # We need to reset the range for our guess so it's now the current lowest_possible_value to the current_middle - 1 highest_possible_value = middle_value - 1 else: # reply == 'no' (greater than middle_value) # We need to reset the range for our guess so it's now middle_value + 1 to the current highest_possible_value lowest_possible_value = middle_value + 1 print( 'Thanks for playing!' ) # So we used a while loop in order to keep asking the user continuously (repeats statements indented into it) # until we set the while loop conditional variable to False (and we only set it to False when we found the number # and we no longer want to keep asking the user questions) # We ask the user if their number is the middle value # If it is, great we won! # If not, reset the range # If it's less than the middle number, # We know the new highest_possible_value is middle_value - 1 # If it's greater than the middle number, # We know the new lowest_possible_value is the middle_value + 1 # Ask based on that new range and newly calculated middle value each time through the while loop until we find # the number!