Reputation: 3
I'm new to working in terminal (Mac, bash) and starting a tutorial, but I don't get the results that are expected. Here's my code in atom.
print('Hello, python')
name = input('What is your name? ')
print name
And here's what I get after entering Tim (or after entering anything other than and integer)
Hello, python
What is your name? Tim
Traceback (most recent call last):
File "max2.py", line 2, in <module>
name = input('What is your name? ')
File "<string>", line 1, in <module>
NameError: name 'Tim' is not defined
If I enter an integer it works fine.
Hello, python
What is your name? 4
4
My understanding is that input takes the user input and puts it in a string. Any help would be appreciated.
Upvotes: 0
Views: 36
Reputation: 16247
Your code is correct, but you are running it through the wrong version of Python. The input()
function is different between Python 2 and Python 3.
Function | Python 2 | Python 3 |
---|---|---|
input() |
Reads and evaluates a Python expression | Reads a string |
raw_input() |
Reads a string | Doesn't exist, use input() |
Since Python 2 is practically obsolete, you should make sure that your script is being invoked through python3
and not through just "python" (which is different from OS to OS but usually means Python 2).
For example, if your script has a #!
line (and you're running it via ./myscript.py
) then change that line to specify "python3".
(However, I'm actually not sure whether macOS even comes with Python 3. You may need to install it through Homebrew or whatever else they use on macOS.)
Also note that the print
syntax is also very different between the two. You're using the correct syntax for Python 3, but it is only by coincidence that print(x)
with one parameter works the same way in both versions.
Upvotes: 1