Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python random number guessing game

'''
Note that if the player types something other than a number, the
program will crash. If you want to fix this, use try and except to
catch the error and tell the player it was invalid.
'''

import random

number = random.randint(1, 100) # Generate random number
num_of_guesses = 0 # Number of guesses player took
guess = 0 # Player's current guess

# Introduce player to game
print('Welcome to my number guessing game!')
print('I have come up with a number between 1 and 100, guess what it is.')

running = True
while running:
  
  guess = int(input('Guess: '))
  num_of_guesses += 1
  
  if guess > number:
    print('Too high, try again.')
  elif guess < number:
    print('Too low, try again.')
  else:
    print('Good job!')
    print(f'It only took you {num_of_guesses} tries')
    running = False # Exits out of while loop
    
print('Thanks for playing!')
Source by www.codegrepper.com #
 
PREVIOUS NEXT
Tagged: #python #random #number #guessing #game
ADD COMMENT
Topic
Name
5+8 =