Python multiple choice game that doesn't end after one choice [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
import random
from random import randint
number = randint(1, 500)
guess = input("The computer has chosen a random number. Guess the number: ")
guess = int(guess)
while guess == number:
print("Congrats, you have won")
break
if guess > number:
print("Lower")
if guess < number:
print("Higher")
This code only allows the user to input one guess and then the program ends. Can someone help me fix this

You should think about your loop condition.
When do you want to repeat? This is the loop condition
When the guess is not correct. guess != number
What do you want to repeat? Put these inside the loop
Asking for a guess guess = int(input("Your guess: "))
Printing if it's higher or lower if guess > or < number: ...
What don't you want to repeat?
You need this before the loop
Deciding the correct number.
Setting the initial guess so the loop is entered once
You need this after the loop
Printing the "correct!" message, because you only exit the loop once the guess is correct
So we have:
number = random.randint(1, 100)
guess = 0
while guess != number:
guess = int(input("Your guess: "))
if guess > number:
print("Lower")
elif guess < number:
print("Higher")
print("Correct!")

Right now, your while loop is useless as once you are in it you break immediately. The rest of the code is not in a loop.
You should rather have an infinite loop with all your code, and break when there is a match:
from random import randint
number = randint(1, 500)
while True: # infinite loop
guess = input("The computer has chosen a random number. Guess the number: ")
guess = int(guess) # warning, this will raise an error if
# the user inputs something else that digits
if guess == number: # condition is met, we're done
print("Congrats, you have won")
break
elif guess > number: # test if number is lower
print("Lower")
else: # no need to test again, is is necessarily higher
print("Higher")

You must take input in the loop, because the value for each step has to be updated .
from random import randint
number = randint(1, 500)
while True:
guess = input("The computer has chosen a random number. Guess the number: ")
guess = int(guess)
if guess == number:
print("Congrats, you have won")
break
if guess > number:
print("Lower")
if guess < number:
print("Higher")

Related

How to use a loop to make something repeat until conditions are met? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 months ago.
I'm trying to make a simple number guessing game. I wanted to try to see if I could do this myself without looking up any answers but I'm very confused on how to keep the game going if the guess is not correct. Here is what I have so far:
import random
#ask user to guess a number:
guess = int(input("Guess a number from 0 to 100: \n"))
#create random number:
computer_number = random.randint(0, 100)
#How can i make this block of code loop to keep on giving the user tries??
if guess == computer_number:
print("You won")
elif guess > computer_number:
print("Try a lower number!")
else:
print("Try a higher number!")
import random
#ask user to guess a number:
#create random number:
computer_number = random.randint(0, 100)
#How can i make this block of code loop to keep on giving the user tries??
while True:
guess = int(input("Guess a number from 0 to 100: \n"))
if guess == computer_number:
print("You won")
break
elif guess > computer_number:
print("Try a lower number!")
else:
print("Try a higher number!")
You could use a while loop to loop the game until a condition is met.
For example:
#create random number:
computer_number = random.randint(0, 100)
while True:
#ask user to guess a number:
guess = int(input("Guess a number from 0 to 100: \n"))
#How can i make this block of code loop to keep on giving the user tries??
if guess == computer_number:
print("You won")
break
elif guess > computer_number:
print("Try a lower number!")
else:
print("Try a higher number!")
it's very easy you just need an while loop:
while condition:
#while condition True run what stands here
So the answer to your question is:
import random
#create random number:
computer_number = random.randint(0, 100)
guess = -1
#we need to firs declare the variables so we can use them in the condition
while guess != computer_number:
#ask user to guess a number:
guess = int(input("Guess a number from 0 to 100: \n"))
if guess == computer_number:
print("You won!")
elif guess > computer_number:
print("Try a lower number!")
else:
print("Try a higher number!")

Python random number guessing game

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. "))

I need help on a python guessing game

I need help changing the range and showing the user what the range is so they know if they are closer or not. I have given the description I have been given. On what I need to do . I have given the code that I have come up wit so far. Let me know if you need anything else from me.
Step 6 – Guiding the user with the range of values to select between
Add functionality so that when displaying the guess prompt it will display the current range
to guess between based on the user’s guesses accounting for values that are too high and too
low. It will start out by stating What is your guess between 1 and 100, inclusive?, but as
the user guesses the range will become smaller and smaller based on the value being higher
or lower than what the user guessed, e.g., What is your guess between 15 and 32,
inclusive? The example output below should help clarify.
EXAMPLE
----------------
What is your guess between 1 and 44 inclusive? 2
Your guess was too low. Guess again.
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
play()
#Part 1
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.")
print("\n")
def play():
''' Plays a guessing game'''
number = int(random.randrange(1,10))
guess = int(input("What is your guess between 1 and 10 inclusive ?: "))
number_of_guess = 0
while guess != number :
(number)
#Quit
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
#Guessing
if guess < number:
if guess < number:
guess = int(input("Your guess was too low. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
if guess > number:
if guess > number:
guess = int(input("Your guess was too high. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
#Winner
if guess == number :
number_of_guess += 1
print("Congratulations you won in " + str(number_of_guess) + " tries!")
again()
def again():
''' Prompts users if they want to go again'''
redo = input("Do you want to play again (Y or N)?: ")
if redo.upper() == "Y":
print("OK. Let’s play again.")
play()
elif redo.upper() == "N":
print("OK. Have a good day.")
sys.exit(0)
else:
print("I’m sorry, I do not understand that answer.")
again()
main()
What you'll need is a place to hold the user's lowest and highest guess. Then you'd use those for the range checks, instead of the hardcoded 1 and 11. With each guess, if it's a valid one, you then would compare it to the lowest and highest values, and if it's lower than the lowest then it sets the lowest value to the guess, and if it's higher than the highest it'll set the highest value to the guess. Lastly you'll need to update the input() string to display the lowest and highest guesses instead of a hardcoded '1' and '10'.
You need to simplify a lot your code. Like there is about 6 different places where you ask a new value, there sould be only one, also don't call method recursivly (call again() in again()) and such call between again>play>again.
Use an outer while loop to run games, and inside it an inner while loop for the game, and most important keep track of lower_bound and upper_bound
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
redo = "Y"
while redo.upper() == "Y":
print("Let’s play")
play()
redo = input("Do you want to play again (Y or N)?: ")
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.\n")
def play():
lower_bound, upper_bound = 0, 100
number = int(random.randrange(lower_bound, upper_bound))
print(number)
guess = -1
number_of_guess = 0
while guess != number:
guess = int(input(f"What is your guess between {lower_bound} and {upper_bound - 1} inclusive ?: "))
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
elif guess not in list(range(lower_bound, upper_bound)):
print("You're outside the range")
continue
number_of_guess += 1
if guess < number:
print("Your guess was too low")
lower_bound = guess
elif guess > number:
print("Your guess was too high")
upper_bound = guess
print("Congratulations you won in", number_of_guess, "tries!")

Python while loop number guessing game with limited guesses

For a class assignment, I'm trying to make a number guessing game in which the user decides the answer and the number of guesses and then guesses the number within those limited number of turns. I'm supposed to use a while loop with an and operator, and can't use break. However, my issue is that I'm not sure how to format the program so that when the maximum number of turns is reached the program doesn't print hints (higher/lower), but rather only tells you you've lost/what the answer was. It doesn't work specifically if I choose to make the max number of guesses 1. Instead of just printing " You lose; the number was __", it also prints a hint as well. This is my best attempt that comes close to doing everything that this program is supposed to do. What am I doing wrong?
answer = int(input("What should the answer be? "))
guesses = int(input("How many guesses? "))
guess_count = 0
guess = int(input("Guess a number: "))
guess_count += 1
if answer < guess:
print("The number is lower than that.")
elif answer > guess:
print("The number is higher than that")
while guess != answer and guess_count < guesses:
guess = int(input("Guess a number: "))
guess_count += 1
if answer < guess:
print("The number is lower than that.")
elif answer > guess:
print("The number is higher than that")
if guess_count >= guesses and guess != answer:
print("You lose; the number was " + str(answer) + ".")
if guess == answer:
print("You win!")
What about something like this?
answer = int(input("What should the answer be? "))
guesses = int(input("How many guesses? "))
guess_count = 1
guess_correct = False
while guess_correct is False:
if guess_count < guesses:
guess = int(input("Guess a number: "))
if answer < guess:
print("The number is lower than that.")
elif answer > guess:
print("The number is higher than that")
else: # answer == guess
print("You win!")
break
guess_count += 1
elif guess_count == guesses:
guess = int(input("Guess a number: "))
if guess != answer:
print("You lose; the number was " + str(answer) + ".")
if guess == answer:
print("You win!")
break
It's very similar to your program, but has a couple break statements in there. This tells Python to immediately stop execution of that loop and go to the next block of code (nothing in this case). In this way you don't have to wait for the program to evaluate the conditions you specify for your while loop before starting the next loop. If this helped solve your problem, it'd be great of you to click the checkmark by my post

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.

Categories