Click here to Skip to main content
15,921,454 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
The code is meant to be able to produce a random number and tell you if you are higher or lower. I want to be able to limit the amount of guesses made to find it.

import random
MAX_NUM = 100
max_tries_allowed = 10
print("\tWelcome to 'Guess My Number !'")
print(f"\nI'm thinking of a number between 1 and {MAX_NUM}")
print("Try to guess it in as few attempts as possible. \n")
# Set the initial values
the_number = random.randrange(MAX_NUM) + 1
guess = None
tries = 0
#guessing loop
while (guess != the_number):
 guess = int(input("Take a guess: "))
 if (tries == max_tries_allowed):
  print("You lose")
 elif (guess > the_number):
 tries += 1
print("You guessed it! The number was ", the_number)
print("And it only took you ",tries, " tries!\n")
input("\n\nPress the Enter key to exit")

What I have tried:

I am a begineer coder but I have got the base program to work but the only thing that doesn't is the limited amount of guesses made.

1 solution

You're very close with this. Your while loop condition needs to be extended so that it doesn't just look at whether the number matches the guess. It also needs to check to see whether you have gone past the maximum number of allowed tries. Rearrange your while clause like this:
found = false
while (found == false and tries < max_tries_allowed)
  guess = int(input("Take a guess: "))
  tries += 1
  if (guess = the_number):
    found = true
  if (guess > the_number):
  elif (guess < the_number):
    found = true
if (found == false):
  print("You didn't find the number")
Something like that should help.
Share this answer
Maciej Los 16-Mar-24 16:00pm    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900