运行以下
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
答案 0 :(得分:2)
在Python 2.7中,input
尝试将输入作为Python表达式进行评估,而raw_input
将其作为字符串进行评估。显然,j
不是有效的表达式。在某些情况下使用input
实际上是危险的 - 您不希望用户能够在您的应用程序中执行任意代码!
因此,您正在寻找的是raw_input
。
Python 3没有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'
答案 1 :(得分:1)
您可能希望使用raw_input
代替input
:
Name = raw_input("What is the player's name?: ")
Score = raw_input("What is the player's score?: ")