top of page
learn_data_science.jpg

Data Scientist Program

 

Free Online Data Science Training for Complete Beginners.
 


No prior coding knowledge required!

'Guess the number' game.

'Guess the number' is a simple game in which the user is asked to guess a random number between 1 and 100, and if that number matches with the number randomly generated by the program, he/she wins the game. The user is given seven attempts to guess the correct number. This game can be created using simple python codes of loops and conditionals.


Step 1: First import the 'random' package so that we can generate a random number between 1 and 100, with the randint method. The generated number is assigned to the variable 'num'.


import random
num = random.randint(1, 100)

Step 2: Initialise and set the count to 0.


count = 0

Step 3: Create a while loop that breaks immediately if the 'guess' is equal to the 'num' or else carries on until the count reaches seven.



while count<7:
    guess = int(input("Guess a number: "))
    count += 1
    if guess == num:
        print("Correct guess. CONGRATULATIONS!!")
        print("The correct number was %d." %num)
        break
    elif guess < num:
        print("Too low.")
    else:
        print("Too high.")

Step 4: Finally, create a condition where 'guess' is not equal to 'num', so that a message is printed after the unsuccessful seventh attempt is over.


if guess != num:
    print("Sorry. The correct number was %d." %num)
    print("Better luck next time.")



The full program code:


#Guess the number game
import random
num = random.randint(1, 100)


count = 0
print("Guess the number. You will have 7 attempts to make the correct guess.")


while count<7:
    guess = int(input("Guess a number: "))
    count += 1
    if guess == num:
        print("Correct guess. CONGRATULATIONS!!")
        print("The correct number was %d." %num)
        break
    elif guess < num:
        print("Too low.")
    else:
        print("Too high.")


if guess != num:
    print("Sorry. The correct number was %d." %num)
    print("Better luck next time.")



The example of the output:


Guess the number. You will have 7 attempts to make the correct guess. 
Guess a number: 55 
Too high. 
Guess a number: 25 
Too high. 
Guess a number: 15 
Too high. 
Guess a number: 7 
Too high. 
Guess a number: 5 
Correct guess. CONGRATULATIONS!! 
The correct number was 5.

0 comments

Recent Posts

See All

Comments


bottom of page