1
votes

I want to insert a number and if I put any number other than 4 it will tell me it's wrong, but if it's false it will tell me "gg you win, noob.". However when I insert 4, it tells me it's incorrect.

x = input("Insert a numer: ")

while x != 4:
   print("incorrect")
    x =input("Insert another number: ")

if x == 4:
    print("gg you win, noob")
5
Python 2 or Python 3 ? - Tony Suffolk 66
Fair assumption he's talking about 3, since this works in 2. - brianpck
@brianpck It is a fair assumption, but I would not say it exactly "works" in 2. The code is wrong either way, but with a different problem. - zvone
@brianpck yes. It's python 3 - Carlitos

5 Answers

3
votes

In Python 3+, input returns a string, and 4 does not equal '4'. You will have to amend to:

while x != '4':

or alternatively use int, being careful to check for a ValueError if the input is not an int.

2
votes

The result from input() will be a string, which you'll need to convert to an integer before comparing it:

x = int(input("Insert another number: ")

This will raise a ValueError if your input is not a number.

0
votes

Here, if x == 4 is not necessary. Because until x is equal to 4 the while loop won't be passed. You can try like this:

x = int(input("Insert a numer: "))
while x != 4:
    print("incorrect")
    x = int(input("Insert another number: "))

print("gg you win, noob")
0
votes

Python 2 and 3 differ in the function input().

  • In Python 2, input() is equivalent to eval(raw_input()).
  • In Python 3, there is no raw_input(), but input() works like Python 2'sraw_input().

In your case:

  • In Python 2, input() gives you 4 with type int, so your program works.
  • In Python 3, input() gives you '4' with type str, so your program is buggy.

In Python 3, one way to fix this is to use eval(input()). But using eval on an untrusted string is very dangerous (yes your program works dangerously in Python 2). So you should validate the input first.

0
votes

Try this:

    z = 0
while z != "gg you win, noob":
    try:
       x = int(input("Insert a numer: "))
       while x != 4:
           print("incorrect")
           x =int(input("Insert another number: "))

       if x == 4:
            z = "gg you win, noob"
            print(z)

    except:
        print('Only input numbers')

This will convert all your input values into integers. If you do not input an integer, the except statement will prompt you to only input numbers, and the while True loop will repeat your script from the beginning instead of raising an error.