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
Related
I need to show "Determinate loop" and "Indeterminate Loops" on this code. (nested)
This is a simple code, pick a random number, and gives you 2 opportunities to guess the number, if you can't, it will let you know what the magic number was and start the game again.
questions:
is there any other way to make the game start over? like a while or nested loop.
can I get an opinion if it is enough?
the problem with the code is, every time you make a guess, it prints
"Can you guess the magic number?"
how can it print that only at the beginning of the code and then only prints:
"try a lower number"
"try a higher number"
I feel like the code is not nested enough, anyway I can make it more professional?
repeat_the_game = True
def start():
import random
magic_number = random.randint(1, 10)
trying = 0
limit = 2
while trying < limit:
guess = int(input("can you guess the magic number?"))
trying += 1
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
elif guess == magic_number:
print("wow, you are right")
break
else:
print("sorry, the magic number was", magic_number)
while repeat_the_game:
start()
Move the text out of the loop to a print statement. Then you can still keep fetching the input inside the loop:
repeat_the_game = True
def start():
import random
magic_number = random.randint(1, 10)
trying = 0
limit = 2
print("can you guess the magic number?")
while trying < limit:
trying += 1
guess = int(input())
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
elif guess == magic_number:
print("wow, you are right")
break
else:
print("sorry, the magic number was", magic_number)
while repeat_the_game:
start()
However, if the second guess is still wrong you probably don't want to print "try a lower/higher number". If you guess it right the second time you do want to print "wow, you're right". I'd put the "try a lower/higher number" after an additional check of whether all tries have been used up already. You can move the "wow, you're right" part before that check:
while trying < limit:
guess = int(input())
trying += 1
if guess == magic_number:
print("wow, you are right")
break
if trying == limit:
continue
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
else:
print("sorry, the magic number was", magic_number)
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.
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()
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()
After making functions for how to check if guesses are right or not, I am having difficulty with getting it to say what I want.
ntries = 0
while ntries < 10:
ntries +=1
if test_guess(code,guess)==True:
print 'You win! You guessed the code in',ntries,'tries.'
elif test_guess(code,guess)==False:
guess = str(raw_input('Your guess: '))
print 'You lose!'
The problem is that when the player successfully guesses the code in, say, 8 tries, the result being printed is:
> You win! You guessed the code in 8 tries.
> You win! You guessed the code in 9 tries.
> You win! You guessed the code in 10 tries.
> You lose!
I realize it's because the while loop indicates that the loop keeps running when ntries is still less than 10. How do I have it so that it will only print the number of tries when won and stops there?
Break out of your loop with the break keyword inside of your if statement.
As an aside: your if-elif block is overly verbose. Since test_guess is returning something to be truthy, you could rewrite it as such. This also moves the ntries variable inside of the else condition, since it only makes sense to increment it if you actually guessed, but failed.
if test_guess(code, guess):
print 'You win! You guess the code in', ntries, 'tries.'
break
else:
ntries += 1
guess = str(raw_input('Your guess: '))
just use break
ntries = 0
while ntries < 10:
ntries +=1
if test_guess(code,guess)==True:
print 'You win! You guessed the code in',ntries,'tries.'
break
elif test_guess(code,guess)==False:
guess = str(raw_input('Your guess: '))
print 'You lose!'