Not sure what I'm doing wrong, Python number-guessing game [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
import random
print("Hey there, player! Welcome to Emily's number-guessing game! ")
name=input("What's your name, player? ")
random_integer=random.randint(1,25)
tries=0
tries_remaining=10
while tries < 10:
guess = input("Try to guess what random integer I'm thinking of, {}! ".format(name))
tries += 1
tries_remaining -= 1
# The next two small blocks of code are the problem.
try:
guess_num = int(guess)
except:
print("That's not a whole number! ")
tries-=1
tries_remaining+=1
if not guess_num > 0 or not guess_num < 26:
print("Sorry, try again! That is not an integer between 1 and 25! ")
break
elif guess_num == random_integer:
print("Nice job, you guessed the right number in {} tries! ".format(tries))
break
elif guess_num < random_integer:
if tries_remaining > 0:
print("Sorry, try again! The integer you chose is a litte too low! You have {} tries remaining. ".format(int(tries_remaining)))
continue
else:
print("Sorry, but the integer I was thinking of was {}! ".format(random_integer))
print("Oh no, looks like you've run out of tries! ")
elif guess_num > random_integer:
if tries_remaining > 0:
print("Sorry, try again! The integer you chose is a little too high. You have {} tries remaining. ".format(int(tries_remaining)))
continue
else:
print("Sorry, but the integer I was thinking of was {}! ".format(random_integer))
print("Oh no, looks like you've run out of tries! ")
I'll try to explain this as well as I can... I'm trying to make the problem area allow input for guesses again after the user inputs anything other than an integer between 1 and 25, but I can't figure out how to. And how can I make it so that the user can choose to restart the program after they've won or loss?
Edit: Please not that I have no else statements in the problems, as there is no opposite output.

Use a function.Put everything in a function and call the function again if the user wants to try again!
This will restart the complete process again!This could also be done if the user wants to restart.
Calling the method again is a good plan.Enclose the complete thing in a method/function.

This will solve the wrong interval
if not guess_num > 0 or not guess_num < 26:
print("Sorry, try again! That is not an integer between 1 and 25! ")
continue
For the rest, you can do something like this
create a method and stick in your game data
def game():
...
return True if the user wants to play again (you have to ask him)
return False otherwise
play = True
while play:
play = game()

Related

Where should I put an if function for my Guessing game?

Right now, I am working on Chapter 3 of the book Python for the absolute beginner.
One of the challenges at the end of chapter 3 is to "Modify the Guess My Number game so that the player has a limited number of guesses" and that if the player fails to get the correct amount of guesses, a message should be displayed.
The code looks like this:
# Guess My Number
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money
import random
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")
# set the initial values
the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1
# guessing loop
while guess != the_number:
if guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = int(input("Take a guess: "))
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.")
From what I can see so far, I need to add a variable that counts how many lives a player has, which is set to an amount at the beginning, like 10 and an if command should be used to make sure that, when the player uses all their lives, the message is displayed.
However, I am unsure where to place the if command in the existing code.
Well, If I were you I would make a game loop instead of the guessing loop. And then I would just break the game loop when I reach the guessing limit. However if you wanna keep your code you can use this.
while guess != the_number:
if tries == 3: # Replace 3 with the limit you'd like to use
print("You lost :(")
exit()
else:
if guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
Also in your case don't use break, it will still cause to print in the end the winning msg
(the spacing might be a little bit off so u may need to fix it)
After you say tries+=1, put an if statement. Your code should look like this:
if tries>3:
print("Game Over")
break()
import random
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")
# set the initial values
the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1
while tries < 8:
if guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
break
elif guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
if tries == 8:
print("You failed to guess my number")
input("\n\nPress the enter key to exit.")
You can also do it this way

Is it possible to change a variable’s value while it is in the `while` loop?

I was trying to write code to solve a question:
Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. Keep track of how many guesses the user has taken, and when the game ends, print this out.
The code that I wrote was:
import sys
import random
x=random.randint(1,9)
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
for i in range (10):
z=input()
if int(z)<x:
print('Too low. Please try again.')
elif int(z)>x:
print('Too high. Please try again.')
elif int(z)==x:
print('You guessed it right!')
if i==0:
print('It took you a single turn! Nice')
else:
print('it took you ' + str(i+1)+' turns.')
print('Do you want to play again? Yes or No?')
j=input()
if j.lower()=='yes':
print('Okay, Please enter a number between 1 and 9 including the extremes.')
pass
else:
sys.exit()
Here’s what it looks like when run:
Hello there! Please enter a number between 1 and 9 including the extremes.
4
Too high. Please try again.
3
Too high. Please try again.
2
You guessed it right!
it took you 3 turns.
Do you want to play again? Yes or No?
yes
Okay, Please enter a number between 1 and 9 including the extremes.
6
Too high. Please try again.
4
Too high. Please try again.
2
You guessed it right!
it took you 6 turns.
Do you want to play again? Yes or No?
See, the code gives perfect results when the for loop is first executed. It gives weird results when we try to run this “game” for the second time by saying yes when it asks us the question: Do you want to play again? Yes or No?.
Is it possible to put i=0 when python reaches the 4th last line and the for loop starts again from i=0 so that I do not get weird results?
Or is there some other easier method remove this bug?
You can use while loop for the task. And you should add exception handling method for getting an input.
import random
cond = True
while cond:
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
x=random.randint(1,9)
for i in range (10):
z=int(input())
if int(z)<x:
print('Too low. Please try again.')
elif int(z)>x:
print('Too high. Please try again.')
elif int(z)==x:
print('You guessed it right!')
import sys
if i==0:
print('It took you a single turn! Nice')
else:
print('it took you ' + str(i+1)+' turns.')
print('Do you want to play again? Yes or No?')
j=input()
if j.lower()=='yes':
break
else:
cond = False
sys.exit()
First of all, you pick the random number only once, so it's always going to be the same.
Secondly, your game should be in while loop instead of for loop (if you want to allow player to restart after they guessed).
turns = 0
while True:
secret_number = random.randint(1,9)
print('Please enter a number between 1 and 9 including the extremes.')
guess = input()
turns += 1
if int(guess) < secret_number:
print("Too low")
elif int(guess) > secret_number:
print("Too high")
else:
print("You guessed in {} turn(s)".format(turns))
You continue the loop, and assign turns = 0 if user wants to keep playing, or you break if he doesn't.
All imports should go at the top of the file. Then, put a while loop so the player can restart after every game; this way, the variable x is also reset after every game. Also, the first print should be put outside the while and for loop, so it's printed only one time (the last if will print a new prompt at the beginning of a new game).
Your code at this point should look like this:
import random
import sys
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
while True:
x=random.randint(1,9)
for i in range (10):
z=input()
if int(z)<x:
print('Too low. Please try again.')
elif int(z)>x:
print('Too high. Please try again.')
elif int(z)==x:
print('You guessed it right!')
if i==0:
print('It took you a single turn! Nice')
else:
print('it took you ' + str(i+1)+' turns.')
print('Do you want to play again? Yes or No?')
j=input()
if j.lower()=='yes':
print('Okay, Please enter a number between 1 and 9 including the extremes.')
else:
sys.exit()
I'd write it like this, probably.
from itertools import count
from random import randint
def run_game():
random_value = randint(1, 9)
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
for i in count():
guess_string = input()
try:
guess = int(guess_string)
except ValueError:
print("Invalid value given for guess: {}".format(guess_string))
if guess < random_value:
print("Too low! Please try again.")
elif guess > random_value:
print("Too high! Please try again.")
else:
print('You guessed it right!')
if not i:
print('It took you a single turn! Nice')
else:
print('it took you {} turns.'.format(i + 1))
print('Do you want to play again? Yes or No?')
response_string = input()
return response_string.lower() == 'yes'
if __name__ == "__main__":
while run_game():
pass
But, for simplicity in understanding:
from itertools import count
from random import randint
if __name__ == "__main__":
playing = True
while playing:
random_value = randint(1, 9)
print('Hello there! Please enter a number between 1 and 9 including the extremes.')
for i in count():
guess_string = input()
try:
guess = int(guess_string)
except ValueError:
print("Invalid value given for guess: {}".format(guess_string))
if guess < random_value:
print("Too low! Please try again.")
elif guess > random_value:
print("Too high! Please try again.")
else:
print('You guessed it right!')
if not i:
print('It took you a single turn! Nice')
else:
print('it took you {} turns.'.format(i + 1))
print('Do you want to play again? Yes or No?')
response_string = input()
if response_string.lower() != 'yes':
playing = False
break
The whole of your code is embedded within the for loop and the counter is never reset. If you want to reset i within the for loop, you have to define it outside the for loop so that it has a global scope.

How Do I Make This Python Guessing Game Start Again?

I want to add some code to the end of this guessing game which will ask the user if they want to play again. If they say yes, the program will, I suppose, just run again from the beginning. I've tried multiple ideas, but none have worked. The closest was another if loop at the end. Thank you! x
print("Welcome to this guessing game!")
import random
x = random.randrange(50)
guess = int(input("I've picked an integer between 1 to 99. Guess what it is: "))
while x != "guess":
print
if guess < x:
print("Your guess is too low!")
guess = int(input("Guess again:"))
elif guess > x:
print("Your guess is too high!")
guess = int(input("Guess again:"))
else:
print ("You guessed the right number!")
Something like:
while True:
your code
if input("Continue? Y/N: ").lower() not in {"y", "yes"}:
break
At the end of every play, this gets input from the user, converts it to lower case, and sees if it's "y" or "yes". If it's not, the game breaks out of the loop, i.e. quits. Otherwise it keeps looping.
You could wrap your game in a function. And then on user say "yes", you invoke the function. And at the end of you game, reask the samequestion.
This is what function is made for.
Pseudo code:
function askUser(){
'Do you want to play'=>yes: launchGame, no:print("ok bye bye")
}
function myGame(){
//your game
askUser()
}
for example
import random
something="yes"
while(something == "yes"):
#your code...
#....
#from your code
else:
print ("You guessed the right number!")
something=input("Do you want to play again? (yes/no)")#input return str? I use raw_input all the time in p2.7
and this:
while x != "guess":
why to guess use " "?
x = random.randrange(50) so x never being a string "guess" its like while True: or while 1:
print("Welcome to this guessing game!")
import random
x = random.randrange(50)
guess = int(input("I've picked an integer between 1 to 99. Guess what it is: "))
while True:
if guess < x:
print("Your guess is too low!")
guess = int(input("Guess again:"))
elif guess > x:
print("Your guess is too high!")
guess = int(input("Guess again:"))
else:
print ("You guessed the right number!")
break
You are learning about the basics of python too little advice to read more books
x is the type of int and guess you use "" included "guess" he is not a variable name and become a string

How do i repeat the game on a loop? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
import random
computer=random.randint(1, 100)
guess=int(input("guess the number"))
if guess > 100:
print("your guess is too high")
elif guess < 1:
print("your guess is too low")
elif guess==computer:
print("well done!")
else:
print("you\'re wrong, guess again")
This is my current code. it's game where the computer randomly chooses a number and the player has to guess it. i have tried but i don't know how to ask the player if they want to play again and if they say yes how to restart it.
Wrap the game code to function and use while True to call it again and again
import random
def play():
computer=random.randint(1, 100)
guess=int(input("guess the number"))
if guess > 100:
print("your guess is too high")
elif guess < 1:
print("your guess is too low")
elif guess==computer:
print("well done!")
else:
print("you\'re wrong, guess again")
while True:
answer = input("do you want to play?")
if answer == 'yes':
play()
elif answer == 'no':
break
else:
print("dont understand")
Put all the if-else statements within one big while loop that keeps looping until the user guesses the number correctly. Then, after each losing outcome, give the user another chance to guess the number so that the loop has a chance to reevaluate the guess with the next iteration. In my modification below I decided to leave the last if-else statement outside of the loop because when the user guesses correctly, the code will break out of the loop to check if the guess is correct. Of course in this scenario it has to be correct so the user is told that he or she is right and the program terminates.
import random
computer=random.randint(1, 100)
guess=int(input("guess the number\n"))
while(guess != computer):
if guess > 100:
print("your guess is too high\n")
guess=int(input("guess the number again\n"))
elif guess < 1:
print("your guess is too low\n")
guess=int(input("guess the number again\n"))
if guess==computer:
print("well done!\n")
Just an overview of how you can do it.
initialize a variable play_again = "yes"
Place a while check on play_again:
while play_again == "yes":
Enclose all if statements and guess input in the while loop
Read the user input in a variable within but at the end of the loop:
play_again = raw_input("\n\nWant to play again?: ")
You can use a while loop for multiple iterations
import random
computer=random.randint(1, 100)
guess=int(input("guess the number"))
play_again = 'y'
while play_again == 'y':
if guess > 100:
print("your guess is too high")
elif guess < 1:
print("your guess is too low")
elif guess==computer:
print("well done!")
else:
print("you\'re wrong, guess again")
play_again = input("Want to play again(y/n): ")
You should put your code in while loop. Then after game ask user if they want to continue with input() function. If they say 'no' you can break the loop or set argument of while to False.

Beginner 'Guess my number' program. while loop not breaking when correct number guessed or when out of guesses

So I'm learning python and I'm trying to code a simple guess my number game where you only have 5 guesses or the game ends. Im really having trouble with the while loop not recognising that the number has been guessed or the guess limit has been reached. Is there a better way of formatting my functions also. Thanks for any and all help, first time using this site.
# Guess my number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money
import random
GUESS_LIMIT = 5
# functions
def display_instruct():
"""Display game instructions."""
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.")
print("\nHARDCORE mode - You have 5 tries to guess the number!\n")
def ask_number(question, low, high, step = 1):
"""Ask for a number within a range."""
response = None
while response not in range(low, high, step):
response = int(input(question))
return response
def guessing_loop():
the_number = random.randint(1, 100)
guess = ask_number("\nTake a guess:", 1, 100)
tries = 1
while guess != the_number or tries != GUESS_LIMIT:
if guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = ask_number("Take a guess:", 1, 100)
tries += 1
if tries == GUESS_LIMIT:
print("\nOh no! You have run out of tries!")
print("Better luck next time!")
else:
print("\nYou guessed it! The number was", the_number)
print("And it only took you", tries, "tries!")
def main():
display_instruct()
guessing_loop()
# start the program
main()
input("\n\nPress the enter key to exit")
Your while condition will be true as long as you haven't hit the guess limit.
while guess != the_number or tries != GUESS_LIMIT:
You should join those conditions with and, not or. The way you have it now, the entire condition will be true because tries != GUESS_LIMIT is true, even if guess != the_number is false.
Or you can break your cycle explicitly with break statement. But previous answer is more correct in a sense you should really understand conditions you're setting for the loop.

Categories