It will be difficult to explain this in the comments section so I am going to try and answer it in the answer section:
Code initialization:
guess = 0
answer = 5
attempts = 0
Iteration 1: Then code goes into while loop for the first time:
while answer != guess:
attempts += 1
attempts value is 1
as answer != guess
i.e., 5 != 0
by initialization.
However, user input = 0
Then you check if attempts is 3 or more. Here it checks 1 >= 3
which is False
if attempts >= 3:
break
assume guess = 8
Iteration 2: while statement checked for the first time with user input value
while answer != guess:
attempts += 1
Now attempts value is 2
as answer != guess
i.e., 5 != 8
user input. However, user input = 1
Then you check if attempts is 3 or more. Here it checks 2 >= 3
which is False
if attempts >= 3:
break
assume guess = 9
Iteration 3: while statement checked for the second time with user input value
while answer != guess:
attempts += 1
Now attempts value is 3
as answer != guess
i.e., 5 != 9
user input. However, user Input = 2
Then you check if attempts is 3 or more. Here it checks 3 >= 3
which is True
if attempts >= 3:
break
You break out of the loop as attempts
is 3
while user has input only twice. Also, the user input value (even if it is 5
) does not matter anymore. You are exiting the loop before you check it again.
Since you broke out of the loop, it also does not go into the else
clause. That's why you are unable to get the code to go to else
clause. The way this program is designed, the code will go into else
clause if you actually guessed the correct answer. The else clause gets triggered when the while
condition fails. When you guess correctly, the while condition fails. Your print statement contradicts with what's actually happening.
Hope this helps you debug your code.
Here's how to fix the code:
answer = 5
attempts = 0
while guess := int(input("Guess: ")) !=answer:
attempts += 1
if attempts >= 3:
print("You Failed")
break
else:
print ("Congrats on guessing the correct number")
Note: I am using the walrus operator. If you are not familiar with it, read more details about walrus
operator here.
Tweaking your code, you can fix it like this:
answer = 5
attempts = 0
while attempts < 3:
guess = int(input("Guess: "))
if guess ==answer:
print ("Congrats on guessing the correct number")
break
attempts +=1
else:
print ('You Failed')