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?

2
  • 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. Commented Oct 22, 2015 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. Commented Oct 22, 2015 at 15:55

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.