Beginners Coding Error, While Loop Triggering 2 Messages - python

I am a beginner that just started learning python this Monday and one of the first hurdles I am getting into is while loops. I was trying to code a number guessing game and when I enter the correct answer it will give me "Wrong Guess" and "Correct Guess" as outputs. I have been staring at this problem wondering why this is happening but I can't figure it out. Can someone explain why this is happening? Thanks in advance!
secret_number = 9
guess = ''
i = 0
while guess != 9 and i < 3:
guess = int(input("Guess Number: "))
i += 1
print('Wrong Guess!')
if guess == 9:
print('Your Correct!')
if i == 3:
print('You lost!')

You need to trace your code line by line. Even if your answer was correct, the print('Wrong Guess!') would still execute.
Instead, I would check if the answer is correct inside the loop.
Note: there's a bug in your code - you should be using secret_number variable instead of explicitly writing 9.
You should also only add i for wrong guesses to prevent saying you lost although you did it in 3 tries.
while guess != secret_number and i < 3:
guess = int(input("Guess Number: "))
if guess == secret_number :
print('Your Correct!')
else:
print('Wrong Guess!')
i += 1

You were getting both the messages together when you entered 9 as the input because the input statement and the Wrong Guess statement are both in the same while loop. Meaning once the code asks you to guess a number, it would then increment i and then print Wrong Guess. Only after doing all three it would go back and check for the conditions of the while loop. Because the conditions fail, for guess = 9 the next lines of code are implemented. which give you the Correct Guess output.
To get the desired output do this,
secret_number = 9
guess = ''
i = 0
while True:
if i < 3:
guess = int(input("Guess Number: "))
if guess == secret_number:
print("Correct Guess")
break
else:
print("Wrong Guess")
i += 1
else:
print("You've run out of lives.")
break

This is another way to get what you're looking for:
secret_number = 9
guess = ''
i = 0
while guess!= secret_number and i<3:
guess = int(input("Guess Number:"))
if guess == secret_number:
print("Your Correct!")
break
print("Wrong Guess!")
i+=1
if i == 3:
print('You Lost!')

Related

How to break out of this loop?

Write a Python program to guess a number between 1 to 9. Go to the editor
Note : User is prompted to enter a guess. If the user guesses wrong then the prompt appears again until the guess is correct, on successful guess, user will get a "Well guessed!" message, and the program will exit.
Edit:- i want to print a message everytime a wrong number is input. However i am getting that message even if i write the correct number.
target_num = 3
guess_num = ""
while target_num != guess_num:
guess_num = int(input('Guess a number between 1 and 10 until you get it right : '))
print("wrong guess")
print('Well guessed!')`
You will want to use to break keyword like so:
target_num=3
while True:
guess_num = int(input('Guess a number between 1 and 10 until you get it right : '))
if guess_num == target_num:
break
print("wrong guess")
print('Well guessed!')
Alternatively, if you don't want to use break you could use:
target_num=3
guess_num=""
while guess_num != target_num:
guess_num = int(input('Guess a number between 1 and 10 until you get it right : '))
if guess_num != target_num:
print("wrong guess")
print('Well guessed!')

BEGINNER: Why is my code executing a fourth guess when the limit is set to three max?

Below code runs fine if your guesses are within the "three-guess" limit, but if you guess wrong the third time, the guess-task asks once more for some reason. This is not what I want. And even if you get it right the third time, the program finishes. What to do?
Code:
secret_number = 6 #random.randint(1, 12)
print("We are going to play a guessing game.")
guess_count = 3
guess = int(input('Try figuring out the computers number between 1 and 12: '))
while guess_count > 0:
if int(guess) != int(secret_number):
if int(guess) > int(secret_number):
guess = input('Too high. Try again: ')
guess_count = guess_count - 1
elif int(guess) < int(secret_number):
guess = input('Too low. Try again: ')
guess_count = guess_count - 1
elif int(guess) == int(secret_number):
print("THAT'S CORRECT!")
break
else:
print("Well, you tried.")
Output:
We are going to play a guessing game.
Try figuring out the computers number between 1 and 12: 12
Too high. Try again: 1
Too low. Try again: 4
Too low. Try again: 6
Well, you tried.
Each time the user guesses incorrectly in the loop, guess_count is decreased by 1 and the input function is called asking the user to guess again. So this will be done three times; but the input function is also used before the loop, giving the user one extra guess.
To fix it, you could set guess_count to 2 before the loop, so that the user gets two guesses in the loop, making three in total including the one before the loop. But it is probably better to use the input function only at the start of the loop, not before the loop and not after an incorrect guess; the way you have it at the moment, the user will be asked again after an incorrect guess even if they have no guesses left.
This should work. You are asking for input 3 times inside the while-loop and one time initially, so total 4 times. Also if the last prediction is correct, you are not checking it with the original value as you have used an elif condition. You can do it like this.
secret_number = 6 #random.randint(1, 12)
print("We are going to play a guessing game.")
guess_count = 2
correct_answer = False
guess = int(input('Try figuring out the computers number between 1 and 12: '))
while guess_count > 0:
if int(guess) != int(secret_number):
if int(guess) > int(secret_number):
guess = input('Too high. Try again: ')
guess_count = guess_count - 1
elif int(guess) < int(secret_number):
guess = input('Too low. Try again: ')
guess_count = guess_count - 1
if int(guess) == int(secret_number):
correct_answer = True
print("THAT'S CORRECT!")
break
if correct_answer == False:
print("Well, you tried.")
As others pointed out, you are giving free guess at the top because you are input the first guess. It prints Well, you tried because guess_count is 0 at the last call, satisfying else statement.
For debugging purpose, if you print guess_count in the else statement, you might be able to figure out.
Also You don't have to keep convert variable to int. The following is how I changed the code.
secret_number = 6 #random.randint(1, 12)
print("We are going to play a guessing game.")
guess_count = 3
while guess_count > 0:
guess = int(input('Try figuring out the computers number between 1 and 12: '))
if guess != secret_number:
if guess > secret_number:
print('Too high. Try again: ')
guess_count = guess_count - 1
elif guess < secret_number:
print("Too low. Try again: ")
guess_count = guess_count - 1
elif guess == secret_number:
print("THAT'S CORRECT!")
break
else:
print("Well, you tried.")

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

random number generator, number guess. What is wrong with my code? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have this basic code and what I want it to do is choose a random number, then it would ask the user to input a number from 0 to 100, the would give back results based on the number, such as number is too low or high. I keep switching things around but always get an error, this for 2.7:
import random
randomNumber = random.randrange(0,100)
guess = -1
guess = int(input('Enter a number between 0 and 100: ')
guess != randomNumber:
if guess < randomNumber
print('Your guess is too low.')
elif guess > randomNumber:
print('Your guess is too high.')
print('You win!')
First, you define guess twice. Just define it once. There is no need to make guess be equal to -1 if that won't be the original value anyways. Second, I believe you want to use a while loop to keep checking if the user has guessed the correct number. In this case, add another guess into the while loop to allow the player to continue guessing and to keep proper syntax.
Don't let the player win always with another condition. Use colons after each if/elif statement as well. As you are comparing a string (the input) and an integer, change the input() to int(input()). The final code should be something like:
import random
randomNumber = random.randrange(0, 100)
guess = None # Define guess
while guess != randomNumber: # Create loop
guess = int(input("Enter a number between 0 and 100")) # Change guess
if guess < randomNumber:
print "Your guess is too low."
elif guess > randomNumber:
print "Your guess is too high."
elif guess == randomNumber:
print "You win!" # Win message under correct condition
break # Exit the loop as game is finished
You're missing a colon after your if statement. You're also printing You win! regardless of the outcome. Put that inside an else statement. You don't need this line guess != randomNumber:, and you don't need guess=-1, and finally you're missing a closing paren as mentioned in comments.
import random
randomNumber = random.randrange(0,100)
guess = None
while guess != randomNumber:
guess = int(input('Enter a number between 0 and 100: '))
if guess == randomNumber:
break
elif guess < randomNumber:
print('Your guess is too low.')
elif guess > randomNumber:
print('Your guess is too high.')
print('You win!')
As usual, commenting your code reveals the error instantly
import random
# Pick a number between 0 and 99
randomNumber = random.randrange(0,100)
# initialize guess (hint: why?)
guess = -1
# Ask the user to guess a number (hint: balanced parentheses help)
guess = int(input('Enter a number between 0 and 100: ')
# What is this line supposed to be? Looks like the beginning of a loop here, but what kind?
guess != randomNumber:
# If the guess is less than the number, then tell the user
if guess < randomNumber
print('Your guess is too low.')
# Otherwise if the guess is higher than the number, tell the user
elif guess > randomNumber:
print('Your guess is too high.')
# Regardless, win the game. Wait whuh..?
print('You win!')
Try the following code:
import random
randomNumber = random.randrange(0,100)
guess = int(input("Enter a number between 0 and 100:"))
if guess < randomNumber:
print('Your guess is too low.')
elif guess > randomNumber:
print('Your guess is too high.')
else:
print('You win!')
(EDIT - removed some unecessary lines)
missing some formatting, and there's a few lines (guess != randomNumber:) that don't really do anything (and in that case, the colon would cause a SyntaxError).
import random
randomNumber = random.randrange(0,100)
guess = int(input('Enter a number between 0 and 100: '))
if guess < randomNumber:
print('Your guess is too low.')
elif guess > randomNumber:
print('Your guess is too high.')
else: # assuming you only want to print this if they guessed right
print('You win!')

I'm trying to write a number guessing game in python but my program isn't working

The program is supposed to randomly generate a number between 1 and 10 (inclusive) and ask the user to guess the number. If they get it wrong, they can guess again until they get it right. If they guess right, the program is supposed to congratulate them.
This is what I have and it doesn't work. I enter a number between 1 and 10 and there is no congratulations. When I enter a negative number, nothing happens.
import random
number = random.randint(1,10)
print "The computer will generate a random number between 1 and 10. Try to guess the number!"
guess = int(raw_input("Guess a number: "))
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
guess = int(raw_input("Guess another number: "))
elif guess <= 0 and guess >= 11:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
elif guess == number:
print "Congratulations! You guessed correctly!"
Just move the congratulations message outside the loop. You can then also only have one guess input in the loop. The following should work:
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
else:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
print "Congratulations! You guessed correctly!"
The problem is that in a if/elif chain, it evaluates them from top to bottom.
Move the last condition up.
if guess == number:
..
elif other conditions.
Also you need to change your while loop to allow it to enter in the first time. eg.
while True:
guess = int(raw_input("Guess a number: "))
if guess == number:
..
then break whenever you have a condition to end the game.
The problem is that you exit the while loop if the condition of guessing correctly is true. The way I suggest to fix this is to move the congratulations to outside the while loop
import random
number = random.randint(1,10)
print "The computer will generate a random number between 1 and 10. Try to guess the number!"
guess = int(raw_input("Guess a number: "))
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
guess = int(raw_input("Guess another number: "))
elif guess <= 0 and guess >= 11:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
if guess == number:
print "Congratulations! You guessed correctly!"

Categories