python number guessing game

42

'''
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!')
import random

num = random.randint(1, 9)

while True:

    try:
        guess = int(input("\nPlease enter a guess from 1-9: "))

        if 0 < guess < 10:

            if guess > num:
                print("\nYou guessed too high")

            elif guess < num:
                print("\nYou guessed too low")

            elif guess == num:
                print("\nYou guessed correctly")

                while True:
                    u_input = input("\nWould you like to play again? y/n: ")

                    if u_input == 'n':
                        exit()

                    elif u_input == 'y':
                        num = random.randint(1, 9)
                        break

                    elif u_input != 'y' and u_input != 'n':
                        print("\nError: Please select a valid option")

        elif guess < 1 or guess > 9:
            print("\nError: Please enter a number from 1-9")

    except ValueError:
        print("\nError: Please enter a number")

Comments

Submit
0 Comments