Traceback NameError in python tutorial

2020-05-03 11:50发布

I'm reading an online python tutorial book from here. The code is listed below. When I execute the code, I can type words into it but then it gave me the error below. What is the wrong with the code?

On a related note, if you have a better resource for leaning python, please let me know. I'm looking for one that is online and updated often (ex: railstutorial.org). The resource I am using have plenty of errors even this early in the book. Thanks.

Enter something : programmig is fun
Traceback (most recent call last):
  File "break.py", line 5, in <module>
    s = input('Enter something : ')
  File "<string>", line 1, in <module>
NameError: name 'programmig' is not defined

#!/usr/bin/python
# Filename: break.py

while True:
    s = input('Enter something : ')
    if s == 'quit':
        break
    print('Length of the string is', len(s))
print('Done')

标签: python
2条回答
劫难
2楼-- · 2020-05-03 12:29

input() doesn't get a string, so it thinks that programmig is a variable. You can type the input you want in quotes to solve this.
A better way however, is to use raw_input, which returns a string.
So either do Enter something : 'programmig is fun', not recommended, or do s = raw_input('Enter something : ') recommended way

The cause of the confusion is that the book is probably for python 3, which has a different input, and also a different print, while you are using python 2.x.

查看更多
甜甜的少女心
3楼-- · 2020-05-03 12:36

This is python 3 code. It seems like you're running it with python 2.

Run python --version to check which version of python you are using.

查看更多
登录 后发表回答