Number Guessing Game | Python

PLAY THE GAME HERE

For my next Python project, I built a Number Guessing Game. The computer will choose a secret number between 1 and 100. Then, the player must select between ‘easy’, ‘hard’, and ‘extreme’ modes, which determines how many guesses are allowed.

This was a fun project to build and get my feet wet with global variable declaration. Let’s take a look at the code…

First, the header logo is imported from the ascii module and the random module is imported for secret number generation. The randomly selected integer is then stored in a variable called ‘secret_number’ and ‘turns’ is set to the value 0.

Next, I defined a function called start_game(), which prints the ASCII logo header and a welcome message. The user’s difficulty selection is then stored in a variable aptly named ‘difficulty’.

An ‘if’ statement then checks which difficulty the user selected and assigns the proper value to ‘turns’. Otherwise, a message is printed advising that an invalid selection was made and the start_game() function is called to restart the prompts and allow the user to enter an appropriate selection.

Finally, the value of ‘turns’ is returned.

Next, another function named get_guess() is defined, which prints a message advising the number of turns currently available and requests the player make their guess. This value is stored in a variable ‘user_guess’ and is returned by the function.

One final function is defined as check_guess() which first decrements ‘turns’ by 1. An ‘if’ statement is then used to check whether the user has exhausted their turn limit. If so, a message advising such is displayed. Otherwise, the ‘elif’ statements then check whether the user’s guess is equal to, greater than, or less than the value stored in ‘secret_number’ and prints the appropriate feedback.

After defining all of our functions, start_game() is called to initiate the prompts and set the value for ‘turns’. Then, a ‘while’ loop continues to call get_guess() and check_guess() until turns hold a value of 0.


You can view and download the source code for this project on my GitHub by clicking here. Thank you for your time!

Previous
Previous

Higher/Lower Game | Python

Next
Next

Black Jack Game: Part 2 | Python