Section 5: Writing a Complete Program, Guess the Number
A Guess Game
The output we need:
Hello, What is your name?
Al
Well, Al, I am thinking of a number between 1 and 20.
Take a guess.
10
Your guess is too low.
Take a guess
5
Your guess is too high.
Take a guess.
6
Good job, Al! You guessed my number in 5 guesses!
importrandom# Ask for Player name and greet themplayerName=input('Hello, What is your name?\n')print(f"Well, {playerName}, I am thinking of a number between 1 and 20.")secretNumber=random.randint(1,20)# print(f"Debug: Secret Number is {secretNumber}")fornumberOFGuessesinrange(1,7):# Max number of Guesses allowedplayerGuess=int(input('Take a Guess\n'))ifplayerGuess<secretNumber:print('Your Guess is too low.')elifplayerGuess>secretNumber:print('Your Guess is too high')else:breakifplayerGuess==secretNumber:print(f'Good job,{playerName}! You guessed my number in {numberOFGuesses} guesses!')else:print(f"Nope. The number I was thinking of was {secretNumber}.")
F-Strings
In this course we were taught about string concatenation using + operator. But that is cumbersome, and we need to convert non-strings values to strings values for concatenation to work.
In python 3.6, F-strings were introduced, that makes the strings concatenation a lot easier.
print(f"This is an example of {strings} concatenation.")
{} We can put our variable name, which will be automatically converted into string type. As you can see, this approach is much more cleaner.
A Guess Game — Extended Version
Let’s take everything we learned so far, write a guess game which has the following qualities:
An error checking
Asking player to choose the lower and higher end of number for guessing game.
Let player exit the game using sys.exit() module or pressing q(uit) button on their keyboard.
Using built-in function title() method, convert a string into title case, where the first letter of each word is capitalized, and the rest are in lowercase.
An extra feature which I want to implement is telling the player, how many guesses they will get. As taught in Algorithm: Binary Search course, offered by Khan Academy. We can calculate max number of guesses using this formula:
For guess between (1, 20), the n = 20:
Here is the extended version, I might have gone a bit over the board.
importrandomimportmathimportsysimporttimedefquitGame():# Message to print when CTRL+C keys are pressedprint('\nThanks for Playing, quiting the game...')sys.exit()# Greeting the Playertry:print('Welcome to Guess the Number Game. \nYou can Quit the game any time by pressing CTRL+C keys on your keyboard')playerName=input('Hello, What is your name?\n').title()print(f"Well, {playerName}, let's choose our start and end values for the game.")exceptKeyboardInterrupt:quitGame()# Asking Player for Guessing Range and Error CheckingwhileTrue:try:lowerEndOfGuess=int(input('Choose your start number: '))higherEndOfGuess=int(input('Choose your end number: '))iflowerEndOfGuess>higherEndOfGuess:# Otherwise our random function will failprint('Starting number should be less than ending number')continuebreakexceptValueError:print('Only Intergers are allowed as a start and end values of a Guessing Game.')exceptKeyboardInterrupt:quitGame()# Haing Fun and choosing the secret numbertry:print('Wait, a moment, I m gearing up for the battle.')time.sleep(2)print("Don't be stupid.I'm not stuck., I'm still thinking of what number to choose!")time.sleep(3)print('Dont dare to Quit on me')secretNumber=random.randint(lowerEndOfGuess,higherEndOfGuess)time.sleep(2.5)print('Shshhhhhhh! I have chosen my MAGIC NUMBER!')time.sleep(1.5)print("It's your turn")time.sleep(1.5)exceptKeyboardInterrupt:quitGame()# print(f"Debug: Secret Number is {secretNumber}")# Calculating maximum number of possible guessestotalGuesses=higherEndOfGuess-lowerEndOfGuessmaxPossibleGuesses=math.ceil(math.log2(totalGuesses))print(f"You have {maxPossibleGuesses} guesses to Win the Game.")time.sleep(1.5)# Game LogicfornumberOFGuessesinrange(1,maxPossibleGuesses+1):try:playerGuess=int(input('Take a Guess!\n'))ifplayerGuess<secretNumber:print('Your Guess is too low!')elifplayerGuess>secretNumber:print('Your Guess is too high!')else:breakexceptValueError:print('Only integers are allowed as valid game guess.')exceptKeyboardInterrupt:quitGame()# Ending the Gametry:ifplayerGuess==secretNumber:print(f'Good job,{playerName}! You guessed my number in {numberOFGuesses} guesses!')else:print(f"You lose! Number of guesses are exhausted. The number I was thinking of was {secretNumber}.")exceptNameError:print('Please, try again, something went wrong!')