If statement answer keeps looping - python

The aim of this code is to get the computer to generate a random number and let the user try and guess what that number is in however many tries they choose. However, when they fail to guess correctly the program is supposed to print "You have failed in (x) tries" just once. Unfortunately this line keeps looping over and over again. Where have I gone wrong?
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
while guess != random_number:
if tries < limit:
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
else:
print(f"You have failed in {limit} tries")
tries = tries + 1
print (f"You have guessed {random_number} correctly")
guess(10)

It was looping forever because the incrementation of tries was done in the else block and there is no break keyword in else block too.
So, move tries = tries+1 in the if tries <limit: block and put break inside the else block as shown below:
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
while guess != random_number:
if tries < limit:
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
tries = tries + 1 # <--- move here
else:
print(f"You have failed in {limit} tries")
break; # <--- put break
print (f"You have guessed {random_number} correctly")
guess(10)

You need to keep a check of the tries.
You need to print the statement only in the user input is correct:
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
while tries<limit:
if tries < limit:
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
else:
print (f"You have guessed {random_number} correctly")
break
else:
print(f"You have failed in {limit} tries")
tries = tries + 1
guess(10)
You can use a for loop:
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
found=False
for i in range(limit):
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
else:
found=True
break
if found:
print (f"You have guessed {random_number} correctly")
else:
print(f"You have failed in {limit} tries")
guess(10)

There are multiple logical errors in your code,
the condition you are using in the while loop, guess != random_number, is to check if a number has been guessed correctly or not, not to check if the total number of guesses are exhausted.
No matter what happens, when the code will exit the while loop it will show the user that he/she has guessed correctly
Changing your code to take this into consideration will fix your problem. Below is a possible solution:
import random
def guess(x):
random_number = random.randint(1,x)
guess = 0
tries = 0
limit = int(input("How many tries would you like to have? "))
# Flag to check if the user is guessing the right or wrong value
# Default assumption is that user is guessing incorrectly
UserGuess = False
while tries < limit:
guess = int(input(f"Guess a random number between 1 and {x} in {limit} tries: " ))
if guess < random_number:
print("too low")
elif guess > random_number:
print("too high")
else:
# Changing flag and stopping the loop if the user guesses correctly
UserGuess = True
break
tries = tries + 1
if UserGuess:
print (f"You have guessed {random_number} correctly")
else:
print (f"You have failed in {limit} tries")
guess(10)

Related

My guessing game repeatedly prints in console if you guess incorrectly

I am new to python and built this for practice. How come if you guess incorrectly the print function runs repeatedly. Additionally, if you make a correct guess the corresponding print function doesn't run.
import random
print("Welcome to the Guessing Game")
rand = random.randint(1, 9)
count = 0
running = True
guess = int(input("Pick a number from 1 - 9"))
while guess != rand:
count += 1
if guess > rand:
print("Too High")
running = False
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
running = False
elif guess < rand:
print("Too Low")
If the number is incorrect we need to ask the player to guess again. You can use break to avoid having an infinite loop, here after 5 guesses.
The conversion of the input to integer will throw an error if the entry is not a valid number. It would be good to implement error handling.
import random
print("Welcome to the Guessing Game")
rand = random.randint(1, 9)
count = 0
running = True
guess = int(input("Pick a number from 1 - 9"))
while guess != rand:
count += 1
if guess > rand:
print("Too High")
running = False
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
running = False
break
elif guess < rand:
print("Too Low")
if i >= 5:
break
guess = int(input("Try again\nPick a number from 1 - 9"))
in the first while loop, when player guesses the correct number we need to break.
Also for counting the number of rounds that player played we need a new while loop based on count.
When we use count in our code we should ask player every time that he enters the wrong answer to guess again so i used input in the while
import random
print("Welcome to the Guessing Game:")
rand = random.randint(1, 9)
count = 0
while count!=5:
guess = int(input("Pick a number from 1 - 9:"))
count += 1
if guess > rand:
print("Too High")
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
break
elif guess < rand:
print("Too Low")
print('you lost')

Keep a game going until the user types exit, and print out how many guesses the user did?

I need to generate a random number from 1 to 9 and ask the user to guess it. I tell the user if its too high, low, or correct. I can't figure out how to keep the game going until they guess it correctly, and once they get it right they must type in exit to stop the game. I also need to print out how many guesses it took for them in the end. Here's my code so far:
import random
while True:
try:
userGuess = int(input("Guess a number between 1 and 9 (including 1 and 9):"))
randomNumber = random.randint(1,9)
print (randomNumber)
except:
print ("Sorry, that is an invalid answer.")
continue
else:
break
if int(userGuess) > randomNumber:
print ("Wrong, too high.")
elif int(userGuess) < randomNumber:
print ("Wrong, too low.")
elif int(userGuess) == randomNumber:
print ("You got it right!")
import random
x = random.randint(1,9)
print x
while (True):
answer=input("please give a number: ")
if ( answer != x):
print ("this is not the number: ")
else:
print ("You got it right!")
break
Here is the solution for your problem from:
Guessing Game One Solutions
import random
number = random.randint(1,9)
guess = 0
count = 0
while guess != number and guess != "exit":
guess = input("What's your guess?")
if guess == "exit":
break
guess = int(guess)
count += 1
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
else:
print("You got it!")
print("And it only took you",count,"tries!")
from random import randint
while 1:
print("\nRandom number between 1 and 9 created.")
randomNumber = randint(1,9)
while 1:
userGuess = input("Guess a number between 1 and 9 (including 1 and 9). \nDigit 'stop' if you want to close the program: ")
if userGuess == "stop":
quit()
else:
try:
userGuess = int(userGuess)
if userGuess > randomNumber:
print ("Wrong, too high.")
elif userGuess < randomNumber:
print ("Wrong, too low.")
else:
print ("You got it right!")
break
except:
print("Invalid selection! Insert another value.")

How to go about repeating or ending a function by a simple yes or no answer? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I wanted to create a guessing game to get more comfortable programming, The user has up to 100 guesses(yes more than enough). If the number is too high or too low it have them type in a new input, if its correct it will print correct.Now I simply want to have it setup to where I ask them would they like to play again. I think I have an idea of to set it up, by separating them into two functions?
I am aware that is not currently a function but should put this as a fucntion and then put my question as an if statement in its own function?
import random
randNum = random.randrange(1,21)
numguesses = 0
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
Here's a simple way to do as you asked.I made a function and when you get the thing correct it asks if you want to play again and if you enter "yes" then it resets the vars and runs the loop again. If you enter anything but "yes" then it breaks the loop which ends the program.
import random
def main():
randNum = random.randrange(1,21)
numguesses = 0
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
x = input("would you like to play again?")
if x == "yes":
main()
else:
break
main()
Here is another way to do
import random
randNum = random.randrange(1,21)
numguesses = 0
maxGuess = 100
print("Guessing number Game - max attempts: " + str(maxGuess))
while True:
numguesses +=1
userguess = int(input("What is your guess [1 through 20]? "))
if userguess < randNum:
print("Too Low")
elif userguess > randNum:
print("Too High")
else:
print("Correct. You used ",numguesses," number of guesses")
break
if maxGuess==numguesses:
print("Maximum attempts reached. Correct answer: " + str(randNum))
break
import random
randNum = random.randrange(1, 21)
guess = 0
response = ['too low', 'invalid guess', 'too hight', 'correct']
def respond(guess):
do_break = None # is assigned True if user gets correct answer
if guess < randNum:
print(response[0])
elif guess > randNum:
print(response[2])
elif guess < 1:
print(response[1])
elif guess == randNum:
print(response[3])
do_continue = input('do you want to continue? yes or no')
if do_continue == 'yes':
# if player wants to play again start loop again
Guess()
else:
# if player does'nt want to play end game
do_break = True # tells program to break the loop
# same as ''if do_break == True''
if do_break:
#returns instructions for loop to end
return True
def Guess(guess=guess):
# while loops only have accesse to variables of direct parent
# which is why i directly assigned the guess variable to the Fucntion
while guess < 100:
guess -= 1
user_guess = int(input('What is your guess [1 through 20]?'))
# here the respond function is called then checked for a return
# statement (note i don't know wheter this is good practice or not)
if respond(user_guess):
# gets instructions from respond function to end loop then ends it
break
Guess()
Yet another way with two while loops
answer = 'yes'
while answer == 'yes':
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
break #Stop while loop if user guest, hop to the first loop with answer var
answer = raw_input("Would you like to continue? yes or no\n>")

Guessing number game python

So i'm working on a guessing number game and one of the requirements is for the "range" of numbers to be updated so that the user with have an easier time with their guess'. I created a new input for when the number is either too high or too low. However, i'm not very good with loops and I can't figure out why my loop is repeating only once without my pasting the code over and over again. Can anyone help so the elif statements will repeat until the number is correct?
This is my code thus far...
import random
random_number = random.randint(1,100)
tries = 0
while tries < 800:
guess = input("Guess a random number between 1 and 100.")
tries += 1
try:
guess_num = int(guess)
except:
print("That's not a whole number!")
break
if not guess_num > 0 or not guess_num < 101:
print("That number is not between 1 and 100.")
break
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
break
elif guess_num > random_number:
print("Sorry that number is too high.")
guess_high = input("Guess a number between 0 and {} .".format(guess_num))
elif guess_num < random_number:
print("Sorry that number is too low.")
guess_low = input("Guess a number between {} and 100 .".format(guess_num))
else:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
import random
random_number = random.randint(1,100)
tries = 0
guess = input("Guess a random number between 1 and 100.")
while tries < 800:
tries += 1
try:
guess_num = int(guess)
except:
print("That's not a whole number!")
break
if not guess_num > 0 or not guess_num < 101:
print("That number is not between 1 and 100.")
break
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
break
elif guess_num > random_number:
print("Sorry that number is too high.")
guess = input("Guess a number between 0 and {} .".format(guess_num))
elif guess_num < random_number:
print("Sorry that number is too low.")
guess = input("Guess a number between {} and 100 .".format(guess_num))
else:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
Do not use break, as they terminate the while loop. See python language reference.
You should ask only once for guess_num. Remove the two input when the guess is too high or too low (BTW variable name guess was incorrect).
The last condition (out of tries) should be outside the while loop, since it will be executed when the number of tries is over 800.
Hint. A user can play this game with the equivlent of a binary search (start with 50, then guess 25 or 75 depending if higher/lower, etc). You should allow about 8 tries (not 800).
Here is how to update the ranges:
import random
random_number = random.randint(1,100)
tries = 0
low = 0
high = 100
while tries < 800:
if(tries == 0):
guess = input("Guess a random number between {} and {}.".format(low, high))
tries += 1
try:
guess_num = int(guess)
except:
print("That's not a whole number!")
break
if guess_num < low or guess_num > high:
print("That number is not between {} and {}.".format(low, high))
break
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
break
elif guess_num > random_number:
print("Sorry that number is too high.")
high = guess_num
guess = input("Guess a number between {} and {} .".format(low, high))
elif guess_num < random_number:
print("Sorry that number is too low.")
low = guess_num
guess = input("Guess a number between {} and {} .".format(low, high))
else:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
For which case does your loop only repeats once?
The loop would break (since you have a break statement in line 15 under the "if not guess_num > 0 or not guess_num < 101:") if the input guess is less than 0 or greater than 100.
If the user input an incorrect guess between 1 and 100, then the code does loop and hence the user is asked to input another number.
Although it does loop, the loop is not updating the range.
What you can do is set range_min and range_max as variables and change these variables according to if the guess is too low or too high.
See the following code:
import random
random_number = random.randint(1,100)
tries = 0
range_min = 0
range_max = 100
while tries < 800:
guess = input("Guess a random number between " + str(range_min +1) + " and " + str(range_max))
tries += 1
try:
guess_num = int(guess)
except:
print("That's not a whole number!")
break
if not guess_num > range_min or not guess_num < (range_max+1):
print("That number is not between str(range_min +1) + " and " + str(range_max)")
break
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
break
elif guess_num > random_number:
print("Sorry that number is too high.")
guess_high = input("Guess a number between 0 and {} .".format(guess_num))
range_max = guess_num
elif guess_num < random_number:
print("Sorry that number is too low.")
guess_low = input("Guess a number between {} and 100 .".format(guess_num))
range_min = guess_num
else:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
Here is how I would do it. Not sure if it works but the approach would be:
import random
random_number = random.randint(1,100)
max_tries = 100
tries = 0
left = 0
right = 100
found = False
def get_number():
try:
guess = int(input("Guss a random number between {} and {}".format(left, right)))
if guess > right or guess < left:
print("That number is not between {} and {}".format(left, right))
return guess
except:
print("That's not a whole number!")
get_number()
def update_range(guess):
if guess >= left:
left = guess
else:
right = guess
while tries <= max_tries and not found:
guess = get_number()
tries=+1
if guess == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
found = True
else:
update_range(guess)
if not found:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
As you can see I am using helper functions in order to reduce the number of if/else structures.
Also updating the range is necessary. And thanks to parametrized strings I can tell the user what's the range.
I also set a flag to know whether the user found the number or not at the end of the game

Player already guessed the number

I'm having difficulties telling the player that the player already guessed the number.
This is my code:
import random
number = random.randint (1, 100)
guess = int(input("\nCan you guess the number?\n\n"))
guessing = 1
def get_guess(already_guessed):
guess = input()
if guess in already_guessed:
print("You already guessed that number.")
else:
return guess
while guess != number:
if guess < number:
print("Your guess is too low.")
if guess > number:
print("Your guess is too high.")
if guess == number:
break
guess = get_guess(input("Try again.\n\n"))
You never updating your already_guessed variable you could add it to your get_guess function. And also you have too many input. Try that:
import random
number = random.randint (1, 100)
guess = int(input("\nCan you guess the number?\n\n"))
already_guessed = []
def get_guess(already_guessed):
if guess in already_guessed:
print("You already guessed that number.")
else:
already_guessed.append(guess)
return already_guessed
while guess != number:
if guess < number:
print("Your guess is too low.")
if guess > number:
print("Your guess is too high.")
if guess == number:
break
guess = int(input("Try again.\n\n"))
already_guessed = get_guess(already_guessed)
You don't maintain a list of guesses seen, but you try to use it.
You pass input in place of the already_guessed list at the end.
Your input statement flow is not consistent with game play.
Your termination doesn't tell the player that s/he won, and you use a redundant break statement.
import random
number = random.randint (1, 100)
guess = int(input("\nCan you guess the number?\n\n"))
guessing = 1
seen = []
def get_guess(already_guessed):
guess = int(raw_input("Your guess?"))
if guess in already_guessed:
print("You already guessed that number.")
else:
return guess
while guess != number:
seen.append(guess)
if guess < number:
print("Your guess is too low.")
elif guess > number:
print("Your guess is too high.")
guess = get_guess(seen)
print "You win!"

Categories

Resources