How to create guess counter in guessing game - python

I'm trying to make a number guessing game where when you guess the number right, it tells you how many guesses it took.
I've tried several loops but can't figure out how to get my "guesses" to increase.
import random
rand_num = random.randrange(1,201)
def guess_game():
guess = int(input("Please enter your guess: "))
guesses = 1
if guess == rand_num:
print("Hit!\nIt took you " + str(guesses) + " guesses!")
elif guess < rand_num:
print("Your guess is too low.")
guesses = guesses + 1
guess_game()
else:
print("Your guess is too high")
guesses = guesses + 1
guess_game()
guess_game()
For example, desired output should be something like this:
"Hit! It took you 5 guesses"
But it only says 1 guesses no matter how many tries it took.

Your code doesn't work because you keep calling guess_game() after every guess, effectively starting a new game after every guess.
When the user finally guesses correctly, it's always after 1 guess in that new game and then all games end at once, but never does the code reach the line where it prints the number after more than one guess in any of those games.
There's many different ways to fix this, but the main issue here is that (like many new programmers) you didn't realise calling a function doesn't just get the program to jump to your new code, it creates an entirely new space for the program to work in (each call to the function gets its own 'scope') and returns from that once the function is done, with the previous scope unchanged in most cases.

Every time you call guess_game(), you are essentially resetting the game.
Instead, you want to enclose your game in a while loop which it only exits when the game is over. I have written a working version for you here:
import random
rand_num = random.randrange(1,201)
def guess_game():
guesses = 1
while(True):
guess = int(input("Please enter your guess: "))
if guess == rand_num:
print("Hit!\nIt took you " + str(guesses) + " guesses!")
return 0
elif guess < rand_num:
print("Your guess is too low.")
guesses = guesses + 1
else:
print("Your guess is too high")
guesses = guesses + 1
guess_game()

Your Code is not working well because you have initialize guesses=1 in function when you call the function in itself (Recursion) the value of variable guesses is reset.
import random
rand_num = random.randrange(1,201)
guesses=0 #initialize it outside function
def guess_game():
guess = int(input("Please enter your guess: "))
global guesses
guesses+=1
if guess == rand_num:
print("Hit!\nIt took you " + str(guesses) + " guesses!")
elif guess < rand_num:
print("Your guess is too low.")
guess_game()
else:
print("Your guess is too high")
guess_game()
guess_game()

Related

My while loop won't stop after a condition

I made a dice game and you have 3 goes and, if you don't guess it with the 3 goes, it will show you the number and say you lost but for me it only shows it if you don't guess it in 4 goes.
import random
import time
guess=3
print ("Welcome to the dice game :) ")
print ("You have 3 guess's all together!")
time.sleep(1)
dice=random.randint(1, 6)
option=int(input("Enter a number between 1 and 6: "))
while option != dice and guess > 0:
option=int(input("Wrong try again you still have " + str(guess) + " chances remaining: "))
guess=guess-1
if guess == 0:
print ("You lost")
print ("The number was " + str(dice))
if option == dice:
print ("You win and got it with " + str(guess) + " guess remaining")
and the result is:
Welcome to the dice game :)
You have 3 guess's all together!
Enter a number between 1 and 6: 4
Wrong try again you still have 3 chances remaining: 4
Wrong try again you still have 2 chances remaining: 4
Wrong try again you still have 1 chances remaining: 4
You lost
The number was 2
A cleaner way to write this would be
import random
import time
guesses = 3
print("Welcome to the dice game :) ")
print("You have 3 guesses all together!")
time.sleep(1)
dice = random.randint(1, 6)
while guesses > 0:
option = int(input("Enter a number between 1 and 6: "))
guesses -= 1
if option == dice:
print(f"You win and got it with {guesses} guess(es) remaining")
break
if guesses > 0:
print("Wrong try again you still have {guesses} guess(es) remaining")
else:
print("You lost")
print(f"The number was {dice}")
The loop condition only tracks the number of guesses remaining. If you guess correctly, use an explicit break to exit the loop. The else clause on the loop, then, is only executed if you don't use an explicit break.
You're giving the user an extra chance with this line: option=int(input("Enter a number between 1 and 6: ")). Try declaring guess=2 instead.
Your code clearly grants the initial guess (before the loop), and then three more (within the loop). If you want it to be 3 guesses, then simply reduce your guess counter by 1.

How to fix guessing game

The objective is to create a simple program that generates a number between 1 and 100, it will then ask the user to guess this, if they guess outside of the number range it should tell them to guess again, if not it should tell them whether their guess was too high or too low, prompting them to guess again. Once they do guess the correct number it should tell them they've won and the number of tries it took for them to guess it correctly.
Here is what I have so far
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
return play_game
else:
print("Invalid number.")
return play_game()
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
play_game()
The issue I'm currently running into is when it checks to see if their guess was between 1-100 instead of moving on to weather or not their number was too how or to low, it stays and loops.
If anyone could help me with this issue and review the code in general I'd appreciate it.
I think the problem is with some indentation and some logical problems in the flow.
When you call play_game() from inside the game, it starts a completely different game
with different random_number.
A good code that satisfies your condition might look like the following
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
else:
print("Invalid number.")
play_game()
You could re-adjust your code:
1. if no. within range, run your high, low, match checks
2. break if guess matches the no
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 0
while True:
count += 1
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
break
else:
print("Invalid number, try again")
play_game()
The issue you are running into is because of incorrect indentation. The if-else statements that check whether the number is within the valid range are at the same indentation level as the while loop and thus are not executed within it. Simply indenting should fix the problem.
Furthermore, you have called play_game without parenthesis, making it incorrect syntax for a function call. However, rather than checking if the number is greater than 0 and lesser than 100, it would more optimal to check whether number is lesser than 0 or greater than 100, and if that is the case, print invalid number and call play_game().
It would look something like this:
while True:
if guess < 0 and guess > 100:
print ("Invalid number.")
return play_game()
The rest of your code looks good. I've also attached the link on the section of indentations of the Python documentation here.

How do I keep track of a user's guesses in Python? attempts= attempts + 1 is not working

I need to keep track of the number of guesses a user inputs in a simple guessing game.
I have tried using attempts= 0 and then setting attempts to = attempts + 1. Even when I do this, the code will print "You have guessed in 1 attempts" even when the user has guessed in more attempts than one.
Code:
attempts = 0;
print("Hello, welcome to the game. You will be choosing a number
between 1 and 100. You can only guess up to 10 times.")
for tries in range(tries_allowed):
print("You only get 10 tries.")
break
while attempts < 10:
guess = int(input("Please guess a number"));
attempts_used= attempts + 1;
if guess > random_number:
print("Guess is too high, try a smaller number");
elif guess < random_number:
print("Guess is too low, try a higher number");
elif guess == random_number:
attempts_used=str(attempts_used)
print("Correct- you win in", attempts_used, "guesses");
exit();
else:
if tries_allowed == 10:
print("You failed to guess in time")
my_list= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list.append(attempts_used)
print(my_list)
You never update the attempts variable, you've created a new one called attempts_used, you don't need to do this.
Just use attempts everywhere you're using attempts_used
Note: Whilst you're at it you should get rid of what is known as a "magic number", or a hard coded limit in your while loop
while attempts < tries_allowed:
Cleaned up your code a bit, shows the += counting method working for your script.
As others have said, the original code is creating an entirely new variable attempts_used that is simply attempts + 1, and attempts remains 0.
It could also be attempts = attempts + 1, += means the same thing.
To make a int a str in python for printing purposes, it does not need to be stored to a separate variable, just call str() around it, unless you plan to use the string separately.
import random
random_number = random.randint(1,100)
attempts = 0
tries_allowed = 10
print("Hello, welcome to the game. You will be choosing a number between 1 and 100")
print("You only get " + str(tries_allowed) + " tries.")
my_list = []
while attempts < tries_allowed:
guess = int(input("Please guess a number: "))
if guess in my_list:
print("You have already guessed " + str(guess))
continue
attempts += 1
my_list.append(guess)
if guess > random_number:
print("Guess is too high, try a smaller number")
elif guess < random_number:
print("Guess is too low, try a higher number")
elif guess == random_number:
print("Correct- you win in", str(attempts), "guesses")
break
else:
if attempts == 10:
print("You failed to guess in time")
for item in my_list:
print(item)
Your "attemps" variable stays on 0, so attemps_used(attempts + 1) will always be 1. You have to merge both of the variables in only one in order to control it (attempts=attempts+1)
Code which also checks previous input and prints a message.
import random
# Hello World program in Python
attempts = 0
print("Hello, welcome to the game. You will be choosing a number between 1 and 100. You can only guess up to 10 times.")
random_number = random.randint(1, 101)
#print(random_number)
my_list= []
for tries in range(10):
print("You only get 10 tries.")
guess = int(input("Please guess a number: "))
if guess in my_list:
print("You already guessed this number!!")
my_list.append(guess)
attempts += 1
if guess > random_number:
print("Guess is too high, try a smaller number")
elif guess < random_number:
print("Guess is too low, try a higher number")
else:
print("Correct- you win in", tries + 1, "guesses")
attempts = -1
break
if attempts is 10 and attempts is not -1:
print("You failed to guess in time")
print("Attempts : ", my_list)

Python Number Guessing Game Need Help Avoiding Counting Duplicates in "Number of Guesses"

I am brand new to learning Python and am building a very simple number guessing game. The user guesses a number between 1-100, and are given feedback on whether their guess is too low or too high. When they guess the number correctly, the program tells them how many guesses they took. What I need help with: telling the user when they guessed a duplicate number if they have entered it already. I also want to exclude any duplicate guesses from the final guess count. What is the easiest way to do this?
Here is my game so far:
import random
print("Guess a number between 1-100")
the_number = random.randint(1, 100)
guess = int(input(""))
tries = 0
while guess != the_number:
if guess > the_number:
print("Lower")
if guess < the_number:
print("Higher")
guess = int(input("Guess again: "))
tries += 1
if guess == the_number:
print("You win! The number was", the_number)
print("And it only took you", tries, "tries!\n")
Keep track of the numbers guessed, only increasing if the user has not guessed a number already in our guessed set:
import random
print("Guess a number between 1-100")
the_number = random.randint(1, 100)
tries = 0
# store all the user guesses
guessed = set()
while True:
guess = int(input("Guess a number: "))
# if the guess is in our guesses set, the user has guessed before
if guess in guessed:
print("You already guessed that number!")
continue
# will only increment for unique guessed
tries += 1
if guess == the_number:
print("You win! The number was", the_number)
print("And it only took you", tries, "tries!\n")
break
elif guess > the_number:
print("Lower")
# if it's not == or >, it has to be <
else:
print("Higher")
# add guess each time
guessed.add(guess)
You also had some logic in regard to your ordering like taking a guess outside the loop which could have meant you never entered the loop if the user guessed first time.
this is how you should write the code.
import random
debug = True
def number_guessing():
previous_guesses = set()
tries = 0
print("Guess a number between 1-100")
random_number = random.randint(1, 100)
while True:
guess = int(input())
if guess in previous_guesses:
print("You already tried that number")
continue
previous_guesses.add(guess)
tries += 1
if random_number < guess:
print(f"Lower => previous attempts [{previous_guesses}] tries [{tries}]") if debug is True else None
elif random_number > guess:
print(f"Higher => previous attempts [{previous_guesses}] tries [{tries}]") if debug is True else None
elif guess == random_number:
print("You win! The number was", random_number)
print(f"And it only took you {tries} attempt{'s' if tries>1 else ''}!\n")
break
number_guessing()

Guess My number game with limited number of guesses

I'm new to python and I'm trying to make the guess my number game with a limit of only 5 guesses, everything I've tried so far has failed. how can I do it?, I forgot to mention that I wanted the program to display a message when the player uses all their guesses.The code below only prints the "You guessed it" part after the 5 guesses whether they guess it or not.
import random
print ("welcome to the guess my number hardcore edition ")
print ("In this program you only get 5 guesses\n")
print ("good luck")
the_number = random.randint(1, 100)
user = int(input("What's the number?"))
count = 1
while user != the_number:
if user > the_number:
print ("Lower")
elif user < the_number:
print ("Higher")
user = int(input("What's the number?"))
count += 1
if count == 5:
break
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
input ("\nPress enter to exit")
Your edit says you want to differentiate between whether the loop ended because the user guessed right, or because they ran out of guesses. This amounts to detecting whether you exited the while loop because its condition tested false (they guessed the number), or because you hit a break (which you do if they run out of guesses). You can do that using the else: clause on a loop, which triggers after the loop ends if and only if you didn't hit a break. You can print something only in the case you do break by putting the print logic right before the break, in the same conditional. That gives you this:
while user != the_number:
...
if count == 5:
print("You ran out of guesses")
break
else:
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
However, this puts code for different things all over the place. It would be better to group the logic for "guessed right" with the logic for warmer/colder, rather than interleaving them with part of the logic for how many guesses. You can do this by swapping where you test for things - put the 'is it right' logic in the same if as the warmer/colder, and put the number of guesses logic in the loop condition (which is then better expressed as a for loop). So you have:
for count in range(5):
user = int(input("What's the number?"))
if user > the_number:
print("Lower")
elif user < the_number:
print("Higher")
else:
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
break
else:
print("You ran out of guesses")
You have two options: you can either break out of the loop once the counter reaches a certain amount or use or a for loop. The first option is simplest given your code:
count = 0
while user != the_number:
if user > the_number:
print ("Lower")
elif user < the_number:
print ("Higher")
user = int(input("What's the number?"))
count += 1
if count == 5: # change this number to change the number of guesses
break # exit this loop when the above condition is met

Categories

Resources