Python during unexpected loop behavior

I'm relatively new to Python, and I don't understand that the following code produces the following 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)

whose output 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 running even though x is 3?

+4
source share
5 answers

input()returns the string you are comparing with an integer. This always returns false. You will need to wrap input()on call int()for proper 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 about int() here .

+4
source

You get this error because you are not parsing the input like this:

x = int(input("6 divided by 2 is"))

If you replace your operator’s instructions, this will work.

+1

. , int :

x = int(input("6 divided by 2 is"))
+1

Guesses = 0
while(Guesses < 101):
    try:
        x = int(input("6 divided by 2 is: "))
        if(x == 3):
            print("Correct! 6 divide by 2 is", x)
            break
        else:
            print("Incorrect. try again")
            Guesses += 1
    except ValueError:
        print("That is not a number. Try again.")
        Guesses += 1
else:
    print("Out of guesses.")

, , input a number, while\else loop, try\except loop. try\except , , inputs , ValueError, , inputted was not a number. while\else loop , , Guesses 100. , guesses the answer, 3, they got the answer right and the loop will end; -, 3 (), answer will be incorrect will be prompted the question again; user guesses a string ValueError, , their answer wasn't a number and that the user has to try again.

, , , , , , , . :)

+1

python 2.6 int int. , :

x = input("6 divided by 2 is")
print "Your input is %s, %s" % (x, type(x))

:

6 divided by 2 is 2
Your input is 2, <type 'int'>

, ? , , ( OS X)? , , , int().

0

Source: https://habr.com/ru/post/1626791/


All Articles