Im learning python and having a go at the guessing game. my game works but my win condition prints both "you win" and "you loss", I think my "if" statements are incorrect but i could be wrong.
Also, there's an issue with my printing of the win loss, I can only get it to print the loss..
Thanks in advance!
import random
print("Number guessing game")
name = input("Hello, please input your name: ")
win = 0
loss = 0
diceRoll = random.randint(1, 6)
if diceRoll == 1:
print("You have 1 guess.")
if diceRoll == 2:
print("You have 2 guesses.")
if diceRoll == 3:
print("You have 3 guesses.")
if diceRoll == 4:
print("You have 4 guesses.")
if diceRoll == 5:
print("You have 5 guesses.")
if diceRoll == 6:
print("You have 6 guesses.")
number = random.randint(1, 5)
chances = 0
print("Guess a number between 1 and 5:")
while chances < diceRoll:
guess = int(input())
if guess == number:
print("Congratulation YOU WON!!!")
break
win += 1
elif guess < number:
print("Your guess was too low")
else:
print("Your guess was too high")
chances += 1
if not chances == 0:
print("YOU LOSE!!! The number is", number)
loss += 1
print(name)
print("win: "+str(win))
print("loss: "+str(loss))
Try changing your loop. Since you're breaking if it's correct, you can use a while: else. Otherwise you can win on your last chance and still get the lose message.
while chances < diceRoll:
guess = int(input())
if guess == number:
print("Congratulation YOU WON!!!")
break
win += 1
elif guess < number:
print("Your guess was too low")
else:
print("Your guess was too high")
chances += 1
else:
print("YOU LOSE!!! The number is", number)
loss += 1
In your while loop the if statement should be...
if guess == number:
print("Something)
win += 1
break
and the last if statement should be...
if win != 0:
print("You lose")
else:
print("You win")
The problem lies within the final if statement. The player loses if their chances are greater than the diceRoll, whereas the if condition is true if the player's chances are not 0 i.e. the player failed once.
The code for the final if statement should look something like this:
if chances >= diceRoll:
print("YOU LOSE!!! The number is", number)
loss += 1
As for the problems printing the win, the problem here is in the first if statement inside the while loop. If the player wins the break statement is encountered first, so the code breaks out of the while loop without incrementing the win counter.
Just swap the break statement with the win += 1 and it'll work wonders:
if guess == number:
print("Congratulation YOU WON!!!")
win += 1
break
To start look at
the position of your break
the loss condition
Related
I'm having issues with this random number guessing game. There are 2 issues: The first issue has to do with the counting of how many tries you have left. it should give you 3 changes but after the 2nd one it goes into my replay_input section where I am asking the user if they want to play again.
import random
# guess the # game
guess = input("Enter in your numerical guess. ")
random_number = random.randint(0, 10)
print(random_number) # used to display the # drawn to check if code works
number_of_guess_left = 3
# this is the main loop where the user gets 3 chances to guess the correct number
while number_of_guess_left > 0:
if guess != random_number:
number_of_guess_left -= 1
print(f"The number {guess} was an incorrect guess. and you have {number_of_guess_left} guesses left ")
guess = input("Enter in your numerical guess. ")
elif number_of_guess_left == 0:
print("You lose! You have no more chances left.")
else:
print("You Win! ")
break
The second part has to do with the replay input, I can't seem to get it to loop back to the beginning to restart the game.
replay_input = input("Yes or No ").lower()
if replay_input == "yes":
guess = input("Enter in your numerical guess. ")
The break statement exits a while loop. The code in the loop executes once, hits break at the end, and moves on to execute the code after the loop.
You can have the player replay the game by wrapping it in a function which I've called play_game below. The while True loop at the end (which is outside of play_game) will loop until it encounters a break statement. The player plays a game once every loop. The looping stops when they enter anything other than "yes" at the replay prompt which will make it hit the break statement.
import random
def play_game():
# guess the # game
guess = input("Enter in your numerical guess. ")
random_number = random.randint(0, 10)
print(random_number) # used to display the # drawn to check if code works
number_of_guess_left = 3
# this is the main loop where the user gets 3 chances to guess the correct number
while number_of_guess_left > 0:
if guess != random_number:
number_of_guess_left -= 1
print(f"The number {guess} was an incorrect guess. and you have {number_of_guess_left} guesses left ")
guess = input("Enter in your numerical guess. ")
elif number_of_guess_left == 0:
print("You lose! You have no more chances left.")
else:
print("You Win! ")
while True:
play_game()
replay_input = input("Yes or No ").lower()
if replay_input != "yes":
break
Please focus on the basics first before posting the questions here. Try to debug with tools like https://thonny.org/. However, I updated your code, just check.
import random
# guess the # game
random_number = random.randint(0, 10)
print(random_number)
# don't forget to convert to int
guess = int(input("Enter in your numerical guess. "))
number_of_guess_left = 3
# this is the main loop where the user gets 3 chances to guess the correct number
while number_of_guess_left > 0:
number_of_guess_left -= 1
if guess == random_number:
print("You Win! ")
break
else:
if number_of_guess_left == 0:
print("You lose! You have no more chances left.")
break
else:
print(f"The number {guess} was an incorrect guess. and you have {number_of_guess_left} guesses left ")
guess = int(input("Enter in your numerical guess. "))
So I have a game where you have to guess a number the code picks at random (I was looking at project ideas), before taking a look at the answer I want to know if there is a more efficient to store the if's? I do think there might be a way to merge them into one single block and delete the others.
def guess(x): # this is a number generator
ran_num = random.randint(1, x)
guess = int(input('type number guess from 1 to {} '.format(x)))
attempt_num = 4
if attempt_num < 1:
print('game over')
exit()
elif guess < ran_num:
(print('your guess was a bit low'))
elif guess > ran_num:
print('your guess was all too high')
while guess != ran_num:
guess = int(input('oh no, your number is incorrect, please type that again, you gots {} attempts left '.format(attempt_num)))
attempt_num -= 1
if attempt_num < 1:
print('game over')
exit()
elif guess < ran_num:
(print('your guess was a bit low'))
elif guess > ran_num:
print('your guess was all too high')
if guess == ran_num:
print("success")
guess(5)
Just ask for the guess inside the loop. You can use a for loop to iterate 4 times.
def guess(x): # this is a number generator
ran_num = random.randint(1, x)
for attempt_num in range(4, 0, -1):
guess = int(input('type number guess from 1 to {}, you gots {} attempts left '.format(x, attempt_num)))
elif guess < ran_num:
(print('your guess was a bit low'))
elif guess > ran_num:
print('your guess was all too high')
else:
print("success")
break
else:
print('game over')
guess(5)
You have some repeated code, so it would be a good idea to just put the if-else blocks into a function, this will simplify your code.
I added a check_guess function, and made ATTEMPT_NUM global so we can reference it and update it in both functions.
import random
ATTEMPT_NUM = 4
def guess(x): # this is a number generator
global ATTEMPT_NUM
ran_num = random.randint(1, x)
guess = int(input('type number guess from 1 to {} '.format(x)))
check_guess(ran_num, guess)
while guess != ran_num:
guess = int(input('oh no, your number is incorrect, please type that again, you gots {} attempts left '.format(ATTEMPT_NUM)))
ATTEMPT_NUM -= 1
check_guess(ran_num, guess)
if guess == ran_num:
print("success")
def check_guess(ran_num, guess):
global ATTEMPT_NUM
if ATTEMPT_NUM < 1:
print('game over')
exit()
elif guess < ran_num:
(print('your guess was a bit low'))
elif guess > ran_num:
print('your guess was all too high')
guess(5)
I made this attempt. x was the max random number you could get, right? Combine everything in an infinite loop that only breaks after you win or you put wrong all the numbers.
def guess(x):
attempt_num = 5
ran_num = random.randint(1, x)
while True:
guess = int(input('type number guess from 1 to {} '.format(x)))
if guess == ran_num:
print ("congrats")
break
elif guess < ran_num:
(print('your guess was a bit low'))
attempt_num = attempt_num -1
elif guess > ran_num:
print('your guess was all too high')
attempt_num = attempt_num -1
print (attempt_num)
if attempt_num == 0:
print ("game over")
break
It wouldn't hurt if you do a small check in the input to avoid the user putting anything else than a number, though.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I recently made a number guessing game and whenever I guess or lower than the randomnum it will acuratley say if it is higher or lower but if you try to keep guessing it keeps spitting out the same answer even if you get it right. I even made the code print the answer troughout the code just to make sure the value doesnt change.
import random
randomnum = random.randint(1, 100)
print(randomnum)
number = 0
wttg = input("welcome to the guesing game! \ntype y to start!")
if wttg == ("y"):
playinp = input("Guess a number between 1 and 100! \nGet it right and you win!\nwould you like to play on easy mode? (10 guesses)\nor hard mode? (3 guesses) E/H")
else:
print("oops! Thats not a correct input! Restart the code to try again! :\\")
if playinp == ("e"):
guessnum = int(input("OK, easy mode selected \nGuess..."))
while number < 10:
if guessnum == (randomnum):
print("Congratulations! You are the winner! Restart code to play again!")
break
else:
if guessnum > randomnum:
guessnum == int(input("Guess Lower"))
number = (number + 1)
if guessnum < randomnum:
guessnum == int(input("Guess Higher"))
number = (number + 1)
if number == 10:
print("You lost boohoo. what are you guna cry?")
elif playinp == ("h"):
guessnum = int(input("OK, hard mode selected \nGuess..."))
while number < 2:
if guessnum == (randomnum):
print("Congratulations! You are the winner! Restart code to play again!")
break
else:
if guessnum > randomnum:
guessnum == int(input("Guess Lower"))
number = (number + 1)
if guessnum < randomnum:
guessnum == int(input("Guess Higher"))
number = (number + 1)
print(randomnum)
if number == 2:
print("You lost boohoo. what are you guna cry?")
else:
print("oops! Thats not a correct input! Restart the code to try again!:\\")
I created a working version of your code and I will summarize the changes that I made so you can replicate this on your own.
The reason why your code doesn't update the guessnum variable is because you're doing
guessnum == int(input("Guess Lower"))
The double equal sign, ==, is a comparison operator so you are only checking if guessnum is equivalent to the input. Instead, use a single equal sign = which assigns the value of the input to the guessnum variable.
First off, from a code cleanliness perspective, you don't need parenthesis around comparisons. So instead of if wttg == ("y"):, you can just do if wttg == "y":.
You had the right idea for using a while loop but you didn't finish that code. In the future, if you want to test your code without it breaking, you can use a python pass statement. I added a condition that checks if guessnum does not equal randomnum so that we can avoid using a break statement.
Instead of doing number = (number + 1), you can use the += operator which does the same thing but is a shorthand notation. More info here.
Last thing is I did playinp.lower() == "e" and playinp.lower() == "h". This makes sure that users can type in both capital letters and lowercase letters which makes your game more user-friendly.
I updated the range of random.randint() to (1, 101) because Python ranges are non-inclusive of the last number. For example, if you print (list(range(1,10)) you will get [1, 2, 3, 4, 5, 6, 7, 8, 9].
I made quite a few more changes so feel free to ask me any more questions. :D
import random
randomnum = random.randint(1, 101)
print(randomnum)
number = 0
wttg = input("welcome to the guesing game! \ntype y to start!")
if wttg == "y":
playinp = input("Guess a number between 1 and 100! \nGet it right and you win!\nwould you like to play on easy mode? (10 guesses)\nor hard mode? (3 guesses) [E/H]")
else:
print("oops! Thats not a correct input! Restart the code to try again! :\\")
if playinp.lower() == "e":
print("OK, easy mode selected")
guessnum = int(input("Guess..."))
number += 1
while number < 10 and guessnum != randomnum:
if guessnum > randomnum:
guessnum = int(input("Guess Lower"))
else: # guessnum < randomnum
guessnum = int(input("Guess Higher"))
number += 1
if guessnum == (randomnum):
print("Congratulations! You are the winner! Restart code to play again!")
elif number == 10:
print("You lost boohoo. what are you guna cry?")
elif playinp.lower() == "h":
print("OK, hard mode selected")
guessnum = int(input("Guess..."))
number += 1
while number < 3 and guessnum != randomnum:
if guessnum > randomnum:
guessnum = int(input("Guess Lower"))
else: # guessnum < randomnum
guessnum = int(input("Guess Higher"))
number += 1
if guessnum == (randomnum):
print("Congratulations! You are the winner! Restart code to play again!")
elif number == 3:
print("You lost boohoo. what are you guna cry?")
else:
print("oops! Thats not a correct input! Restart the code to try again!:\\")
Above, I replicated your code structure but if you want to make the code cleaner, you can use the following code
import random
randomnum = random.randint(1, 101)
print(randomnum)
number = 0
wttg = input("welcome to the guesing game! \ntype y to start!")
if wttg.lower() == "y":
playinp = input("Guess a number between 1 and 100! \nGet it right and you win!\nwould you like to play on easy mode? (10 guesses)\nor hard mode? (3 guesses) [E/H]")
else:
print("oops! Thats not a correct input! Restart the code to try again! :\\")
if playinp.lower() == "e" or playinp.lower() == "h":
print("OK, easy mode selected" if playinp.lower() == "e" else "OK, hard mode selected")
max = 10 if playinp.lower() == "e" else 3
guessnum = int(input("Guess..."))
number += 1
while number < max and guessnum != randomnum:
if guessnum > randomnum:
guessnum = int(input("Guess Lower"))
else: # guessnum < randomnum
guessnum = int(input("Guess Higher"))
number += 1
if guessnum == (randomnum):
print("Congratulations! You are the winner! Restart code to play again!")
elif number == max:
print("You lost boohoo. what are you guna cry?")
else:
print("oops! Thats not a correct input! Restart the code to try again!:\\")
Inside of the if statements where you check if guessnum is lower or higher than randomnum, you aren't updating the value of guesnum. For example, if the guess is too high, you're doing guessnum == int(input("Guess Lower")) which just checks if guessnum is equal to the input or not. You want guessnum = int(input("Guess Lower")) which actually sets the value.
My son has this project he has to do in python and is stuck.
He needs to make a number guessing game. The code must generate a random secret number between 0 and 10, then give the user 5 attempts to guess that number, each guess if not correct must indicate if it is higher or lower than the secret random number. After each guess the code needs to display text stating what has happened. The code also needs to store all guesses and display them at the end. Needs to be made using loop, if, elif, else and an array or list code.
The attempt so far is below
print("Hi there, lets play a little guessing game. Guess the number between 0 and 10")
from random import randint
x = [randint(0,10)]
counter = 0
guess = input("Enter guess:")
while counter < 5:
print("You have " + str(counter) + " guesses left")
counter = counter +1
if guess == x:
print("Congrats you got it")
break
elif guess > x:
print("Too high")
elif guess < x:
print("Too low")
else:
print("You lost")
break
Any help to correct my sons code would be appreciated as this project is due soon and he cannot access his tutor
This should do it. What the code does is explained in comments below.
You need to do x=randint(0,10) which will assign the random number to a variable, i.e x=4 rather than `x = [randint(0,10)], which assigns the random number to a list ,x=[4]```
Also you need to ask for a guess in the loop, instead of doing it only one before the loop started.
Also you would need to convert the string to an int for comparison i.e. guess = int(input("Enter guess:"))
print("Hi there, lets play a little guessing game. Guess the number between 0 and 10")
#Create a random number
from random import randint
x = randint(0, 10)
counter = 0
won = False
#Run 5 attempts in a loop
while counter<5:
#Get the guess from the user
guess = int(input("Enter guess:"))
counter = counter+1
#Check if the guess is the same, low or high as the random number
if guess == x:
print("Congrats you got it")
won = True
break
elif guess > x:
print("Too high")
elif guess < x:
print("Too low")
print("You have " + str(5 - counter) + " guesses left")
#If you didn't won, you lost
if not won:
print("The number was ", x)
print("You Lost")
So here are the corrections. So x has been initialized as array rather than an integer. So none of the comparisons with guess will be working. Also the counter logic is wrong. Rather than starting from zero, start from 5 which is the maximum number of chances and go from the reverse rather. Then at each if/elif loop append all the guesses and print it in the end.
Here is the corrected code
from random import randint
x = randint(0,10)
print(x)
counter = 5
guesses=[] #initalize an empty list to store all guesses
while counter != 0:
guess = input("Enter guess:")
if guess == x:
print("Congrats you got it")
guesses.append(guess)
break
elif guess > x:
print("Too high")
guesses.append(guess)
elif guess < x:
print("Too low")
guesses.append(guess)
else:
print("You lost")
break
counter = counter-1
print("You have " + str(counter) + " guesses left")
print(guesses)
Edit:
x = [randint(0,10)] wouldn't work as you are creating a list here instead of single guess
print("You have " + str(counter) + " guesses left") is also incorrect. You might instead set counter to 5 and check for counter > 0 and do counter -= 1, that way message can be fixed
Lastly to store all guesses you would need a variable
from random import randint
if __name__ == "__main__":
number_to_guess = randint(0,10)
guesses = []
for c in range(5,0,-1):
guessed = input("Enter guess:")
guessed = guessed.strip()
assert guessed.isnumeric()
guessed = int(guessed)
guesses.append(guessed)
if guessed == number_to_guess:
print("yes")
break
elif guessed > number_to_guess:
print("more")
else:
print("less")
c -= 1
print("pending guesses", c)
print("Expected - ", number_to_guess)
print("All guesses - ", guesses)
Implement the GuessNumber game. In this game, the computer
- Think of a random number in the range 0-50. (Hint: use the random module.)
- Repeatedly prompt the user to guess the mystery number.
- If the guess is correct, congratulate the user for winning. If the guess is incorrect, let the user know if the guess is too high or too low.
- After 5 incorrect guesses, tell the user the right answer.
The following is an example of correct input and output.
I’m thinking of a number in the range 0-50. You have five tries to
guess it.
Guess 1? 32
32 is too high
Guess 2? 18
18 is too low
Guess 3? 24
You are right! I was thinking of 24!
This is what I got so far:
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
while guessed == False:
userInput = int(input("Guess 1?"))
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + randomNumber + "!")
elif userInput>randomNumber:
print(randomNumber + "is too high.")
elif userInput < randomNumber:
print(randomNumber + "is too low.")
elif userInput > 5:
print("Your guess is incorrect. The right answer is" + randomNumber)
print("End of program")
I've been getting a syntax error and I don't know how to make the guess increase by one when the user inputs the wrong answer like, Guess 1?, Guess 2?, Guess 3?, Guess 4?, Guess 5?, etc...
Since you know how many times you're going through the loop, and want to count them, use a for loop to control that part.
for guess_num in range(1, 6):
userInput = int(input(f"Guess {guess_num} ? "))
if userInput == randomNumber:
# insert "winner" logic here
break
# insert "still didn't guess it" logic here
Do you see how that works?
You forgot to indent the code that belongs in your while loop. Also, you want to keep track of how many times you guessed, with a variable or a loop as suggested. Also, when giving a hint you probably want to print the number guessed by the player, not the actual one. E.g.,
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
count = 0
while guessed is False and count < 5:
userInput = int(input("Guess 1?"))
count += 1
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + randomNumber + "!")
elif userInput > randomNumber:
print(str(userInput) + " is too high.")
elif userInput < randomNumber:
print(str(userInput) + " is too low.")
if count == 5:
print("Your guess is incorrect. The right answer is" + str(randomNumber))
print("End of program")
You are facing the syntax error because you are attempting to add an integer to a string. This is not possible. To do what you want you need to convert randomNumber in each print statement.
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
while guessed == False:
userInput = int(input("Guess 1?"))
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + str(randomNumber) + "!")
elif userInput>randomNumber:
print(str(randomNumber) + "is too high.")
elif userInput < randomNumber:
print(str(randomNumber) + "is too low.")
elif userInput > 5:
print("Your guess is incorrect. The right answer is" + randomNumber)
print("End of program")
import random
arr=[]
for i in range(50):
arr.append(i)
answer=random.choice(arr)
for trial in range(5):
guess=int(input("Please enter your guess number between 0-50. You have 5
trials to guess the number."))
if answer is guess:
print("Congratulations....You have guessed right number")
break
elif guess < answer-5:
print("You guessed too low....Try again")
elif guess > answer+5:
print("You guessed too high..Try again")
else:
print("Incorrect guess...Try again please")
print("the answer was: "+str(answer))
Just a three things to add:
The "abstract syntax tree" has a method called literal_eval that is going to do a better job of parsing numbers than int will. It's the safer way to evaluate code than using eval too. Just adopt that method, it's pythonic.
I'm liberally using format strings here, and you may choose to use them. They're fairly new to python; the reason to use them is that python strings are immutable, so doing the "This " + str(some_number) + " way" is not pythonic... I believe that it creates 4 strings in memory, but I'm not 100% on this. At least look into str.format().
The last extra treat in this is conditional assignment. The result = "low" if userInput < randomNumber else "high" line assigns "low" of the condition is met and "high" otherwise. This is only here to show off the power of the format string, but also to help contain conditional branch complexity (win and loss paths are now obvious). Probably not a concern for where you are now. But, another arrow for your quiver.
import random
from ast import literal_eval
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
win = False
for guess_count in range(1,6):
userInput = literal_eval(input(f"Guess {guess_count}: "))
if userInput == randomNumber:
print(f"You are right! I was thinking of {randomNumber}!")
win = True
break
else:
result = "low" if userInput < randomNumber else "high"
print(f"{userInput} is too {result}")
if win:
print ("YOU WIN!")
else:
print("Better luck next time")
print("End of program")