【问题标题】:Error on python nameERROR [duplicate]python名称错误错误[重复]
【发布时间】:2013-11-17 03:38:18
【问题描述】:

运行以下

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

【问题讨论】:

    标签: python


    【解决方案1】:

    在 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'
    

    【讨论】:

      【解决方案2】:

      您可能想要使用raw_input 而不是input

      Name = raw_input("What is the player's name?: ")
      Score = raw_input("What is the player's score?: ")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-14
        • 2016-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多