""" Authors: Sohie Lee Purpose: CS111 Lab Hi/Lo guessing game while loop practice Consulted: Filename: hiLo.py """ import random def getUsersGuess1(): """ Asks the user for a numerical guess v1 without error checking """ # Assumes good input guess = int(input('Take a guess: ')) return guess def getUsersGuess(): """ Asks the user for a numerical guess v2 w/ error checking """ guess = input('Take a guess: ') while not isGuessValid(guess): print ('Sorry, that is not a valid input. Try again.') guess = getUsersGuess() return int(guess) def isGuessValid(guess): """ Returns boolean if input is valid (number b/n 1 & 50) """ return str(guess).isdigit() and int(guess) <= 50 and int(guess) >= 1 # ------- Version 1.0 Uses break when the user guesses correctly ------- def hiLo(): """ Version 1.0 Uses break when the user guesses correctly. Plays an interactive hiLo game where the user tries to guess a secretNumber number """ maxGuesses = 5 guessesSoFar = 0 secretNumber = random.randint(1,50) # inclusive # When debugging, cheat: #print ('secretNumber number: ' + str(secretNumber)) # Explain rules print('Try to guess the number I am thinking of between 1 & 50.') print('You have ' + str(maxGuesses) + ' chances.') while guessesSoFar < 5: guess = getUsersGuess() guessesSoFar += 1 if guess == secretNumber: print('Wahooo! You guessed my secret number number!') print('And it only took you ' + str(guessesSoFar) + ' guesses!') break # exit the while loop elif guess > secretNumber: print ('Too high...') else: print ('Too low...') # end of while loop # Conclusion: # Did the user run out of guesses # or did the user guess the right number? if guessesSoFar >= 5 and guess != secretNumber: print ('Sorry, you have run out of guesses.') print ('The secretNumber number was ' + str(secretNumber) + '.') # ------- Version 2.0 Uses a variable when the user guesses correctly ------- def hiLo(): """ Version 2.0 Does not use break, uses a variable instead Plays an interactive hiLo game where the user tries to guess a secretNumber number """ maxGuesses = 5 guessesSoFar = 0 secretNumber = random.randint(1,50) # inclusive done = False # Explain rules print('Try to guess the number I am thinking of between 1 & 50.') print('You have ' + str(maxGuesses) + ' chances.') while (guessesSoFar < 5) and (not done): guess = getUsersGuess() guessesSoFar += 1 if guess == secretNumber: print('Wahooo! You guessed my secret number number!') print('And it only took you ' + str(guessesSoFar) + ' guesses!') done = True # This prevents while loop from executing again elif guess > secretNumber: print ('Too high...') else: print ('Too low...') # end of while loop # Conclusion: # Did the user run out of guesses # or did the user guess the right number? if guessesSoFar >= 5 and guess != secretNumber: print ('Sorry, you have run out of guesses.') print ('The secretNumber number was ' + str(secretNumber) + '.')