For loop python guessing game

For loop python guessing game
Onyejiaku Theophilus Chidalu

Overview

The while loop in python is used to execute a code block multiple times. They are often used in building interactive programs and games.

In this shot, we want to create a guessing game that will return a congratulatory message to a user after making a correct guess. We will use the while loop in writing this code.

Code

Let’s try the below-given code by providing the input in the, Enter the input below, block:

correct_guess=9

guess_count=0

guess_limit=3

while guess_count

guess = int(input('Guess a number: '))

guess_count += 1

if guess == correct_guess:

print('Congratulations! You won!')

break

else:

print('sorry you lost')

Python - guessing game using while loop

Output

The output on successful guess will be:

Guess a number: 9
Congratulations! You won!

Explanation

Here’s the explanation of the above-given code:

  • Lines 1-3: We are creating integer variables

  • Line 4: Using the while loop, we stated a condition that the variable guess_count should be less than the variable guess_limit. In other words, the number of guesses the user has to make should not exceed 3.

  • Line 5: We request the user input the correct guess and convert it to an integer value simultaneously.

  • Line 6: We increment the variable guess_count by 1.

  • Line 7: We are using the if statement within the loop stating that if the user made a guess, that is equal to the value of the correct_guess.

  • Line 8: We are displaying/printing the congratulatory message if the condition at line 7 is true.

  • Line 9: We use the break statement to terminate the loop.

  • Line 10: We are using the else statement to return another output if the conditions provided in the previous codes are not met, or they are false.

  • Line 11: We are displaying/printing the sorry message.

RELATED TAGS

python

loop

while

game

communitycreator

CONTRIBUTOR

For loop python guessing game
Onyejiaku Theophilus Chidalu

In this exercise, you will be making “Guess The Number” game yourself with the help of for loop in Python. The idea is simple, we will generate a random number with the help of randint() function from 1 to 100 and ask the user to guess it. After every guess, the user will be told if the number is above or below the randomly generated number. The user will win if they guess the number in five attempts.

First of all, we have to import the random module so that we can use randint() function to generate a random number.

 
import random
 

Now, we will ask the user to enter their name using the input() function and then storing it in the player_name variable.

print("Hello, please enter your name.")
player_name = input()
 

The next step is to generate a random number using randint() function. Since randint() is one of the functions inside the random module, we must call it with random.randint() and then storing it in the secret_number variable. For this program, a random number would be generated between 1 and 100 like this.

secret_number = random.randint(1,100)
 

Welcoming the user and printing the instructions using the print() function.

print("Thanks, " + player_name + ". Please enter any number between 1 and 100. Remember, you have only 5 attempts")
 

Now we will instruct the user to enter their number (guess) and store it in the guess variable. Note that the input() function always returns a string, so we have to convert it into integer using the int() function. Using for loop and the range() function, we will restrict the user to 5 attempts. Whenever the user makes a wrong guess, for loop will start over and ask the user to guess the number again. Since the user has only 5 attempts, this block of code will stop after the fifth attempt and jump over to the next one. Similarly, if the user is able to guess the number correctly, the break statement will immediately take us out from the for block.

for total_guesses in range(5):
    guess = int(input())    
    if guess < secret_number:
        print("Your guess is below the number, please guess again")
    elif guess > secret_number:
              print("Your guess is above the number, please guess again")
    else: 
        break
 

Once the execution in for loop starts either because it has looped five times or the user was able to guess the number correctly, the next step is to print the results. This block of code will execute if the user guessed the number correctly.

 
if guess == secret_number:
    total_guesses = str(total_guesses + 1)
    print(player_name + ", it took you " + total_guesses + " attempts to guess the number")
 

And if the user runs out of their guesses (5), this block of code will execute.

 
if guess != secret_number:
    secret_number = str(secret_number)
    print("Nope, the number I was thinking was " + secret_number + ".")
 

Source Code

import random

print("Hello, please enter your name.")
player_name = input()

secret_number = random.randint(1,100)
print("Thanks, " + player_name + ". Please enter any number between 1 and 100. Remember, you have only 5 attempts")


for total_guesses in range(5):
    guess = int(input())    
    if guess < secret_number:
        print("Your guess is below the number, please guess again")
    elif guess > secret_number:
              print("Your guess is above the number, please guess again")
    else: 
        break

if guess == secret_number:
    total_guesses = str(total_guesses + 1)
    print(player_name + ", it took you " + total_guesses + " attempts to guess the number")

if guess != secret_number:
    secret_number = str(secret_number)
    print("Nope, the number I was thinking was " + secret_number + ".")
 

Posted from Data Science With Python SteemPress : http://datasciencewithpython.info/python-exercise-001-make-a-guess-the-number-game/

How do you make a guessing game in Python?

Algorithm.
Define the range of the numbers. ... .
Generate a random integer from the above range ( 1-100 )..
Start the game by displaying the user a message saying “Guess the number from X to Y”. ... .
Initialize a variable to 0 to count the total number of chances that the user has taken to guess the number correctly..

What is number guessing game in Python?

In this game, the program generates random number but this number is not visible to the player. Player tries to guess the number. If the player enters the same number that is generated by system then program displays the winning message and game ends there.

How do you use the break function in Python?

'Break' in Python is a loop control statement. It is used to control the sequence of the loop. Suppose you want to terminate a loop and skip to the next code after the loop; break will help you do that. A typical scenario of using the Break in Python is when an external condition triggers the loop's termination.