Learn how to code a beginner random number guessing game python using functions, while loops, if statements, importing a library, and accepting user input

# Tutorial: Number Guessing Game in Python

Dylan | May 10, 2019 In this post we’ll be walking through creating a text-based number guessing game in Python. This little game is a great project for beginners just learning the ropes of programming or Python.

##### This project incorporates:
• While Loops
• If Statements
• Functions
• Using a Library (random)
• Collecting User Input

#### Quick Breakdown!

The general idea behind the game is to have the computer generate a random number that the human player must attempt to guess. If the player guesses a number larger than the random number, the program prints ''Guess a lower number: '', prompting the player to enter another guess. If the guess is too low, the program prints ''Guess a higher number: '' prompting the player to guess again.

This cycle continues until the player enters the correct number. The score is the number of guesses that the player needed to correctly guess the secret number. Like golf, in this game the lower the score, the better. I would strongly recommend trying to create this game on your own before looking over my version of it. This is a fantastic challenge for beginners and you’re very likely to learn something by comparing your final project to mine. Don’t worry if this project seems too challenging for your current level, let’s dive into the code!

#### Importing a Library

``from random import randint``

We begin by importing the function randint from the library random. We will use the randint function to generate the random integer that the player will try to guess.

#### Generating a Random Number and Taking User Input

``secret_number = randint(1, 1000)guess = int(input("Guess a number between 1 and 1000:"))``

Here we use the imported randint function to generate a random number and store it in the variable secret_number. The function randint takes two parameters: first, the minimum possible number you want to be generated and second, the maximum possible number. In this case, we want our player to only guess numbers between 1 and 1000, so we pass the integers 1 and 1000.

In the third line, we accept the player input using the built-in Python function input. We pass the string ''Guess a number between 1 and 1000:'' to the function and when the program requests a guessed number from the player, this text will appear so the player knows what to enter. Finally, the entire input is encased in int() which conveniently converts the player-supplied string into an integer type. We do this to be able to perform greater than and less than operations on the number later.

#### While Loops and If Statements

``guess_count = 1while secret_number != guess:   if guess > secret_number:      guess = int(input("Guess a lower number: "))   elif guess < secret_number:      guess = int(input("Guess a higher number: "))   guess_count += 1``

In line 5, we define and initiate the variable guess_count equal to zero. This variable will store the number of guesses required for the play to guess the correct number. The variable begins at 1 because the player has already guessed one number to initiate the game.

In line 6, we begin a while loop that will continue as long as the condition secret_number != guess is True. That is, as long as the secret number is not the same as the player’s previous guess. == continues the while loop if the first variable is equal to the second, while != continues if the first variable is not equal to the second.

Line 7 checks if the player’s guess is greater than the generated secret_number. If it is, then in line 8, the guess variable’s data is updated to the string inputted by the player after being prompted to ''Guess a lower number:''. Again this data is converted into an integer type by the built-in int() function.

Line 9 executes only if line 7’s condition was false and guess was not greater than secret_number. This time, if guess is less than secret_number, line 10 updates the variable guess to whatever the user inputs after being prompted to “Guess a higher number:”.

Finally, line 11 increments the value of guess_count by one. ''guess_count += 1'' is equivalent to ''guess_count = guess_count + 1''. We must increment this variable to keep track of the player’s score every time the player makes a new guess.

After executing line 11, the loop returns to line 6 to recheck the condition of secret_number != guess. If guess does not equal the secret number, the entire body of the loop will execute again, prompting the player to enter another number.

#### Printing and Formatting Strings

``print(f"Yay! You won in {guess_count} turns!")``

Finally, after the player guesses the secret number and the while loop condition secret_number != guess is no longer true, the program exits the while loop and prints the string ''Yay! You won in x_number turns!''. You can format the string by placing an f before the string quotation marks. Including this little f character permits you to insert variables directly into the string. You do this by encasing the variable in brackets {}. Python will automatically convert the integer guess_count into a string. You can insert as many variables this way into the string as you want.

Finally, let’s encapsulate this entire game into a function called play_game().

#### Declaring a Function

``def play_game():   secret_number = randint(1, 1000)   guess = int(input("Guess a number between 1 and 1000:"))   guess_count = 1   while secret_number != guess:      if guess > secret_number:         guess = int(input("Guess a lower number: "))      elif guess < secret_number:         guess = int(input("Guess a higher number: "))      guess_count += 1print(f"Yay! You won in {guess_count} turns!")``

We can define a function with the Python keyword def. We leave the parentheses empty because our function will not require any outside information to run.
Now if we call play_game() and run our script, we will immediately be prompted to ''Guess a number between 1 and 1000:''. Yay! Our program was successful!

#### Improve the Game: Additional Challenges!

1. Can you improve the program to make the minimum and maximum possible secret_number depend on two variables passed to the play_game() function? Your function should look something like play_game(min_number, max_number). Make sure to update your randint function and first prompt to input a guess.

2. Can you write another while loop to ask the player if they would like to play again. If the player enters p, a fresh new game begins. If they enter anything else, the program ends.

After giving these two improvements a shot, you can check the Nimble Coding GitHub Repository for my solution to these two additional challenges!

Please share how this project went for you. Is anything unclear? Ask in the comments below! As always, happy coding from Nimble Coding.