top of page
  • Pinterest
  • Facebook
  • Instagram

NumberGuessing

  • Writer: Lim Long Teck
    Lim Long Teck
  • Jun 24, 2021
  • 2 min read

Updated: Dec 30, 2021

Write a program that simulates a number guessing game. It first generates a random number between 1 and 100. It then prompts user to guess the correct number. User can enter -1 to end the game or the game will end after 5 tries.


Program:

import random

n = random.randint(1,100)

print('Welcome to Number Guessing Game')

num = int(input('Try1: Enter a number between 1 and 100 (or -1 to end): '))

if n == num:

print('Bingo you\'ve got it right')

elif num == -1:

print('Game over. The correct answer is:', n)

else:

if num > n:

print(num, 'is too high.')

elif num < n:

print(num, 'is too low.')

else:

print('Bingo, you\'ve got it right!')

a = 2

while a <= 5:

num = int(input('Try {}: Guess again, enter a number between 1 and 100 (or -1 to end): '.format(a)))

a = a+1

if num == -1:

print('Game over. The correct answer is:', n)

break

elif num > n:

print(num, 'is too high.')

elif num < n:

print(num, 'is too low.')

else:

print('Bingo, you\'ve got it right!')

break

if a == 6:

print('Game over. The correct answer is:', n)

print('\nBye-bye!')

Output:

Welcome to the Guessing Game

Try 1: Enter a number between 1 and 100 (or -1 to end): 80

80 is too high.

Try 2: Guess again, enter a number between 1 and 100 (or -1 to end): 20

20 is too low.

Try 3: Guess again, enter a number between 1 and 100 (or -1 to end): 60

60 is too high.

Try 4: Guess again, enter a number between 1 and 100 (or -1 to end): 40

40 is too high.

Try 5: Guess again, enter a number between 1 and 100 (or -1 to end): 45

45 is too high.

Game over. The correct answer is : 34


Bye-Bye!


----------------------------------------------------or---------------------------------------------


Welcome to the Guessing Game

Try 1: Enter a number between 1 and 100 (or -1 to end): 45

45 is too low.

Try 2: Guess again, enter a number between 1 and 100 (or -1 to end): 79

79 is too high.

Try 3: Guess again, enter a number between 1 and 100 (or -1 to end): 60

60 is too low.

Try 4: Guess again, enter a number between 1 and 100 (or -1 to end): 72

Bingo, you've got it right!


Bye-Bye!




Recent Posts

See All
CountLetters

Write a Python program to - Prompt user to input a sentence - Count the occurrence of each letter in the input sentence - Save the result...

 
 
 
BirthdayParadox

The Birthday Paradox asks the question, “If you asked random people their birthday, how many people do you expect to ask before you find...

 
 
 
ChristmasTree

Write a program to prompt the user for a character and a number, and then print a Christmas tree accordingly. Program: char =...

 
 
 

Comments


bottom of page