Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python while loop unexpected behavior

I'm relatively new to Python, and I don't understand the following code produces the subsequently unexpected output:

x = input("6 divided by 2 is")
while x != 3:
    print("Incorrect. Please try again.")
    x = input("6 divided by 2 is")
    print(x)

the output of which is:

6 divided by 2 is 3
Incorrect. Please try again.
6 divided by 2 is 3
3
Incorrect. Please try again.
6 divided by 2 is 

Why is the while loop still being executed even though x is equal to 3?

like image 805
anatta Avatar asked Aug 05 '26 10:08

anatta


1 Answers

input() returns a string, which you are comparing to an integer. This will always return false. You'll have to wrap input() in a call to int() for a valid comparison.

x = int(input("6 divided by 2 is"))
while x != 3:
    print("Incorrect. Please try again.")
    x = int(input("6 divided by 2 is"))
    print(x)

Read more on int() here.

like image 155
Emile Pels Avatar answered Aug 07 '26 22:08

Emile Pels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!