Number guessing game

Victor Cruzat

Data Entry Specialist
Backend Engineer
Frontend Engineer
Python
from random import randint

EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5


# Function to check users answer
def check_answer(user_guess, actual_answer, turns):
  """Checks answer against guest and returns the number of guesses remaining"""
  if user_guess > actual_answer:
    print("Too high.")
    return turns - 1
  elif user_guess < actual_answer:
    print("Too low.")
    return turns - 1
  else: 
    print (f"You got it! The actual answer was {actual_answer}.")


#function to set difficulty
def set_difficulty():
  level = input(f"Choose a difficulty. Type 'easy' or 'hard': ")
  if level == "easy":
    return EASY_LEVEL_TURNS
  else:
    return HARD_LEVEL_TURNS

def game():
  print ("Welcome to The Number Guessing Game!")
  print ("I'm thinking of a number between 1 and 100.")
  answer = randint(1, 100)
  print (f"Pssst, the correct answer is {answer}")

  turns = set_difficulty()


  guess = 0
  while guess != answer:
    print(f"You have {turns} attempts remaining to guess the number.")
    #Let the user guess a number
    guess = int(input("Make a guess: "))
    #function to check user's guess against actual answer
    turns = check_answer(guess, answer, turns)
    if turns == 0:
      print (f"You've run out of guesses, you lose.")
      return
    elif guess !="answer":
      print ("Guess again.")
    #Track the number of turns and reduce by 1 if they get it wrong.


game()
Partner With Victor
View Services

More Projects by Victor