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.
Related
I decided to make a small project to test my skills as I continue to learn Python in my free time.
The game consists of the user guessing the right number that is randomly generated within a certain amount of tries. The user first enters the range of numbers they want to guess from. Then they get their first try at guessing the right number (I have the randomly generated number displayed on purpose to test my code as I continue). I cannot figure out why when I enter the same number as the randomly generated number, I get the error that would pop up when you guess the wrong number. But if I enter that same number after I am prompted to guess for the randomly generated number again, I get a success note prompted to me. I've been trying different variations all day.
import random
print("Guessing Game")
rangeAmount = int(input("From 1 to what number do you want to guess from (Maximum amount is 50)? "))
correctNum = random.randint(1, rangeAmount)
wrongCount = 0
userScore = 0
print("-" * 50)
while rangeAmount:
if 1 < rangeAmount < 10:
guesses = 3
print("Guesses allowed: 3")
break
if 1 < rangeAmount < 20:
guesses = 4
break
if 1 < rangeAmount < 30:
guesses = 5
break
if 1 < rangeAmount < 40:
guesses = 6
break
if 1 < rangeAmount < 50:
guesses = 7
break
print("Correct number: " + str(correctNum))
print("Guess amount: " + str(guesses))
print("-" * 50)
userGuess = input("Make a guessing attempt for the correct number: ")
while userScore != 3:
if wrongCount != guesses:
if userGuess is correctNum:
userScore += 1
print("You got the right answer")
break
else:
wrongCount += 1
print("Current guess count: {}".format(wrongCount))
userGuess = int(input("Wrong answer, try again: "))
if wrongCount == guesses:
print("Out of guesses, score is : {}".format(userScore))
userScore -= 1
break
if userScore == 3:
print("You won the game!")
Output:
Guessing Game
From 1 to what number do you want to guess from (Maximum amount is 50)? 23
--------------------------------------------------
Correct number: 5
Guess amount: 5
--------------------------------------------------
Make a guessing attempt for the correct number: 5
Current guess count: 1
Wrong answer, try again: 5
You got the right answer
Process finished with exit code 0
First, your maximum range is 50, but it is not included in your first while loop (ends at 49), change the last line to <= 50. You can remove the while loop, and change the if statements to if/elifs. Second, your indentation is off in the while userScore != 3: loop, but that could just be a copy/paste error.
And now for the most likely cause of the error,
userGuess = input("Make a guessing attempt for the correct number: ")
is a string, don't forget to make it an int before you compare it to another int.
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 created a while loop so I would keep on asking the user questions until they got the number right. But when a do a random number, for example, it either prints "Pick a higher number" or "pick a lower number" infinitely. Can someone help me out here.
from random import randint
answer = randint(1, 100)
print("Guess a number between 1 and 3.")
guess = int(input())
count = 0
while guess != answer:
if guess < answer:
print("Pick a higher number.")
count += 1
elif guess > answer:
print("Pick a lower number.")
count += 1
elif guess == answer:
print("You got it!")
print("It took you " + str(count) + " tries.")
Try this.
while True:
guess = int(input("Guess a number between 1 and 3."))
if guess < answer:
print("Pick a higher number.")
count += 1
elif guess > answer:
print("Pick a lower number.")
count += 1
elif guess == answer:
print("You got it!")
break
Let me phrase it this way: When do you obtain the input from the user? What happens on a second loop run? Is guess at any time updated?
The answers to these (suggestive) questions will lead you to the right path:
You have to request input from the user in every loop run.
This will lead you to the point about how to start the loop.
from random import randint
answer = randint(1, 100)
count = 0
keep_loop = True
prompt = "Guess a number between 1 and 3."
while keep_loop:
print(prompt)
guess = int(input())
if guess < answer:
prompt = "Pick a higher number."
count += 1
elif guess > answer:
prompt = "Pick a lower number."
count += 1
elif guess == answer:
print("You got it!")
keep_loop = False
print("It took you " + str(count) + " tries.")
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
I have a question about How to delete a space in my guessing game.
Here is my source code:
import random
print ("I’m thinking of an integer, you have three guesses.")
def tovi_is_awesome():
random_integer = random.randint (1, 10)
chances = 3
for i in [1,2,3]:
print ("Guess", i, ": ", end=" ")
guess = eval(input("Please enter an integer between 1 and 10: "))
if guess < random_integer:
print ("Your guess is too small.")
elif guess > random_integer:
print ("Your guess is too big.")
else:
print ("You got it!")
break
if guess != random_integer:
print ("Too bad. The number is: ", random_integer)
tovi_is_awesome ()
When I run it, I got this:
I’m thinking of an integer, you have three guesses.
Guess 1 : Please enter an integer between 1 and 10:
How can I delete that space after "Guess 1"?
Or are there any better ways to avoid that space?
Thank you!
This is my first question in SOF lol
print ("Guess", i, ": ", end=" ")
You could write it like;
print ("Guess {}: ".format(i), end=" ")
So you can avoid from that space. You could check this one for examples.
Here is a simple guess game, check it carefully please. It may improve your game. You dont' have to use eval().
random_integer = random.randint (1, 10)
chances = 3
gs=1
while 0<chances:
print ("Guess {}".format(gs))
guess = int(input("Please enter an integer between 1 and 10: "))
if guess<random_integer:
print ("Your guess is too small.")
chances -= 1 #lost 1 chance
gs += 1 #increase guess number
elif guess > random_integer:
print ("Your guess is too big.")
chances -= 1
gs +=1
else:
print ("You got it!")
break
It's really simple, just showing you some basic logic. You may consider in the future catching errors with try/except etc.
print ("Guess %d:" % (i) )
Writing this way will delete the space.