运行以下内容
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
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发布于 2013-11-17 03:42:25
在Python2.7中,input尝试将输入计算为Python表达式,而raw_input则将其计算为字符串。显然,j不是一个有效的表达式。在某些情况下,使用input实际上是危险的--您不希望用户能够在应用程序中执行任意代码!
因此,您要寻找的是raw_input。
Python3没有raw_input,旧的raw_input被重命名为input。所以,如果您在Python 3中尝试了您的代码,它就会工作。
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")测试:
>>> 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'发布于 2013-11-17 03:40:29
您可能希望使用raw_input而不是input
Name = raw_input("What is the player's name?: ")
Score = raw_input("What is the player's score?: ")https://stackoverflow.com/questions/20026910
复制相似问题