'Beginners Coding Error, While Loop Triggering 2 Messages
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!')
Solution 1:[1]
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
Solution 2:[2]
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
Solution 3:[3]
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!')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | jloh |
Solution 2 | Zero |
Solution 3 | Jake Korman |