[英]Traceback NameError in python tutorial
I'm reading an online python tutorial book from here . 我正在从这里阅读在线python教程书。 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. 在相关说明中,如果您有更好的Python学习资源,请告诉我。 I'm looking for one that is online and updated often (ex: railstutorial.org). 我正在寻找一个在线且经常更新的网站(例如: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')
This is python 3 code. 这是python 3代码。 It seems like you're running it with python 2. 似乎您正在使用python 2运行它。
Run python --version
to check which version of python you are using. 运行python --version
来检查您正在使用的python版本。
input()
doesn't get a string, so it thinks that programmig
is a variable. input()
没有获得字符串,因此它认为programmig
是变量。 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. 但是,更好的方法是使用raw_input
,它返回一个字符串。
So either do Enter something : 'programmig is fun'
, not recommended, or do s = raw_input('Enter something : ')
recommended way 因此,无论你Enter something : 'programmig is fun'
,不推荐,还是s = raw_input('Enter something : ')
推荐的方法
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. 造成混淆的原因是,这本书可能是针对python 3的,使用python 2.x时,它的input
不同, print
也不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.