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
Related
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!")
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")
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!")
I'm taking my first-ever Python class and, like most Python classes, the last assignment is to create a guessing game from 1-100 that tracks the number of VALID tries. The element that I just cannot get (or find here on stackoverflow) is how to reject invalid user input. The user input must be whole, positive digits between 1 and 100. I can get the system to reject everything except 0 and <+ 101.
The only things I can think to do end up telling me that you can't have operators comparing strings and integers. I keep wanting to use something like guess > 0 and/or guess < 101. I've also tried to create some sort of function, but can't get it to work right.
# Generate random number
import random
x = random.randint(1,100)
# Prompt user for input
print("I'm thinking of a number from 1 to 100")
counter = 0
while True:
guess = input("Try to guess my number: ")
# Check if input is a positive integer and is not 0 or >=101
# this line doesn't actually stop it from being a valid guess and
# counting against the number of tries.
if guess == "0":
print(guess, "is not a valid guess")
if guess.isdigit() == False:
print(guess, "is not a valid guess")
else:
counter += 1
guess = int(guess)
# Begin playing
if guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
print(guess, "is correct! You guessed my number in", counter, "tries!")
import random
x = random.randint(1,100)
# Prompt user for input
print("I'm thinking of a number from 1 to 100")
counter = 0
while True:
guess = input("Try to guess my number: ")
try:
guess = int(guess)
if(100 > guess > 0):
counter += 1
guess = int(guess)
# Begin playing
if guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
print(guess, "is correct! You guessed my number in", counter, "tries!")
break
else:
print("Number not in range between 0 to 100")
except:
print("Invalid input")
# Generate random number
import random
x = random.randint(1,100)
# Prompt user for input
print("I'm thinking of a number from 1 to 100")
counter = 1
while True:
try:
guess = int(input("Try to guess my number: "))
if guess > 0 and guess < 101:
print("That's not an option!")
# Begin playing
elif guess == x:
print(guess, "is correct! You guessed my number in", counter, "tries!")
break
elif guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
counter += 1
except:
print("That's not a valid option!")
My instructor helped me out. (I posted to keep from needing that from the guy who's giving me the grade.) Here is what we came up with. I'm posting it to help out any future Python learner that may have this particular rejecting user input problem.
Thank you guys for posting SO FAST! Even though I needed the instructor's help, I would've looked even more incompetent without your insights. Now I can actually enjoy my holiday weekend. Have a great Memorial Day weekend!!!
import random
x = random.randint(1,100)
print("I'm thinking of a number from 1 to 100.")
counter = 0
while True:
try:
guess = input("Try to guess my number: ")
guess = int(guess)
if guess < 1 or guess > 100:
raise ValueError()
counter += 1
if guess > x:
print(guess, "is too high.")
elif guess < x:
print(guess, "is too low.")
else:
print(guess, "is correct! You guessed my number in", counter, "tries!")
break
except ValueError:
print(guess, "is not a valid guess")
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")