1

I've noticed a very curious phenomenon here. I've instantiated a global variable (usrPIN), and I'm comparing it to a local variable (c). When I input a value (in this case, four zeros), the value is chopped off, creating a string that is one character long. Why?

usrPIN
...
def login():
    global usrPIN
    ...
    c = str(input("Enter PIN"))
    print usrPIN
    print str(c)
    if usrPIN == c:
        mainMenu()
    else:
        print "Incorrect PIN"
        login()

enter image description here

What on earth is going on?

Community
  • 1
  • 1
Wolfish
  • 960
  • 2
  • 8
  • 34
  • 5
    Use `raw_input(...)` rather than `str(input(...))` - `str(eval(raw_input('0000')))` is effectively `str(int('0000'))`, which is `'0'`. Also, while you're here: don't use globals. – jonrsharpe Oct 22 '15 at 15:24
  • @jonrsharpe You were correct. Additionally, whilst I've read about globals being somewhat dangerous, I have multiple functions that I'm passing these variables to. Using globals is the most logical solution I've found so far - I've only been learning Python for two days. – Wolfish Oct 22 '15 at 15:55

1 Answers1

3

In Python 2.x input() does automatic evaluation. What this means is when I do:

input(0.2757)

Python evaluates that to be a float. Similarly, in your case 0000 is evaluated as an integer and since four zeros is the same as one zero, it chops those away. In Python 2.x it's generally always recommended to use raw_input() for safety.

Note: raw_input() in Python 2.x always returns a string.

Dylan Lawrence
  • 1,503
  • 10
  • 32
  • This was the one - OOI, why does this occur even if I specify `str()`? Is it because the implicit conversion happens *before* the specification? – Wolfish Oct 22 '15 at 15:53
  • @Wolfish Internally `input()` looks kind of like `eval(raw_input())` so when you say `str(input())` you're actually saying `str(eval(raw_input()))` so the evaluation has already occurred before you ask for a string conversion. – Dylan Lawrence Oct 22 '15 at 16:22