-2

I've finally decided to start learning python as my first language and so far i love it. I;m using python3 along with IDLE3. When writing a simple password prompt im running into a problem :/ script is as follows.

import sys

password = input("Enter your password: ")
if password != "pword" :
    sys.exit()
print("Password correct")

Now when i run the script and enter pass as the password i get the following error:

root@kali:~/Desktop# python password1.py
Enter your password: pword
Traceback (most recent call last):
File "password1.py", line 2, in <module>
password = input("Enter your password: ")
File "<string>", line 1, in <module>
NameError: name 'pword' is not defined

Thanks in advance for your help guys, it's appreciated.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
Adam59600
  • 11
  • 3

1 Answers1

1

One of two things is happening. Either

A) your copy is wrong, and your script actually reads

...
if password != pword:  # note the lack of quotes
...

or B) you're using Python 2

import sys
print(sys.version)
# should show 3.x.y per your question, but if it's showing 2.x.y, that'd be why

The reason Python2 vs Python3 matters is that the input builtin works differently between the two. In Python2, input tries to resolve user input within the namespace, e.g.

# Python2
>>> foo = "bar"
>>> spam = input("enter something: ")
enter something: foo
>>> print(spam)
bar

While Python3 just returns the input as a string

# Python3
>>> foo = "bar"
>>> spam = input("enter something: ")
enter something: foo
>>> print(spam)
foo
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • "_Should I answer it? No, not if you think it's a duplicate._" [source](https://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled) – Xiobiq Sep 02 '16 at 23:48
  • @Polikdir right, but at the time I answered this, it wasn't clear that it was a duplicate. That only came out over the course of the comments with OP. Note that there are two possibilities for what's causing the issue in my answer! :) – Adam Smith Sep 02 '16 at 23:58
  • password = raw_input("Enter your password: ") worked! Thank you guys – Adam59600 Sep 03 '16 at 00:02
  • @adam59600 note that that solution is just writing py2 code. MUCH better to keep the code you had and run python 3 instead! – Adam Smith Sep 03 '16 at 00:03
  • im not sure why my system deafualts to py2.. ive installed py3 did ./configure then make then make install and everything installed successfully... is this a file association issue as previously stated? – Adam59600 Sep 03 '16 at 00:05
  • @adam59600 no that's normal on nix. `python` always points at py2. Read my comments on your question – Adam Smith Sep 03 '16 at 00:12
  • @Polikdir excuse my ignorance for not using the search function first. i didn't realize this is a duplicate. – Adam59600 Sep 03 '16 at 00:41