首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python nameERROR错误

python nameERROR错误
EN

Stack Overflow用户
提问于 2013-11-17 03:38:18
回答 2查看 1K关注 0票数 4

运行以下内容

代码语言:javascript
复制
golfFile = open("golf.dat","a")
another = "Y"
while another=="Y":
    Name = input("What is the player's name?: ")
    Score = input("What is the player's score?: ")
    golfFile.write(Name+"\n")
    golfFile.write(Score+"\n")
    another = input("Do you wish to enter another player? (Y for yes): ")
    print()
golfFile.close()
print("Data saved to golf.dat")

得到以下错误--玩家的名字是什么?:J

代码语言:javascript
复制
Traceback (most recent call last):
  File "C:\Users\Nancy\Desktop\Calhoun\CIS\Chapter10#6A.py", line 4, in <module>
    Name = input("What is the player's name?: ")
  File "<string>", line 1, in <module>
NameError: name 'j' is not defined
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-17 03:42:25

在Python2.7中,input尝试将输入计算为Python表达式,而raw_input则将其计算为字符串。显然,j不是一个有效的表达式。在某些情况下,使用input实际上是危险的--您不希望用户能够在应用程序中执行任意代码!

因此,您要寻找的是raw_input

Python3没有raw_input,旧的raw_input被重命名为input。所以,如果您在Python 3中尝试了您的代码,它就会工作。

代码语言:javascript
复制
golfFile = open("golf.dat","a")
another = "Y"
while another=="Y":
    Name = raw_input("What is the player's name?: ")
    Score = raw_input("What is the player's score?: ")
    golfFile.write(Name+"\n")
    golfFile.write(Score+"\n")
    another = raw_input("Do you wish to enter another player? (Y for yes): ")
    print()
golfFile.close()
print("Data saved to golf.dat")

测试:

代码语言:javascript
复制
>>> Name = input("What is the player's name?: ")
What is the player's name?: j
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'j' is not defined
>>> Name = raw_input("What is the player's name?: ")
What is the player's name?: j
>>> Name
'j'
票数 2
EN

Stack Overflow用户

发布于 2013-11-17 03:40:29

您可能希望使用raw_input而不是input

代码语言:javascript
复制
Name = raw_input("What is the player's name?: ")
Score = raw_input("What is the player's score?: ")
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20026910

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档