【问题标题】:Python NameError: global name 'score' is not definedPython NameError:未定义全局名称'score'
【发布时间】:2017-09-05 09:51:49
【问题描述】:

我正在尝试完成一个已设置为返校作业的程序,但我以前从未使用过 Python,所以我很难找出错误所在。任何帮助将不胜感激,最好在星期四之前,因为这是工作到期的时候!

#revision platform
def Spelling():
    global test
    global score
    score = 0
print("Welcome to the Spelling test.")
Q1=raw_input("Which spelling is correct:\nChangeable\nChangeble\n")
if Q1=="Changeable":
    print("Correct")
    score +=  1
else:
    print("Incorrect")
Q2=raw_input("Which spelling is correct:\nThreshhold\nThreshold\n")
if Q2=="Threshold":
    print("Correct")
    score += 1
else:
    print("Incorrect")
Q3=raw_input("Which spelling is correct:\nScent\nSent\nCent\n")
if Q3=="Scent" or Q3=="Sent" or Q3=="Cent":
    print("Trick Question they were all right!")
    score += 1
    print("Your score is:" ,score)
else:
    print("Incorrect")
    print("Your score is:",score)

感谢您的帮助!

【问题讨论】:

  • 您的缩进好像关闭了。
  • 你得到什么错误?你能更具体地说明问题是什么吗?如果您也可以添加回溯,那将很有帮助
  • 问题是缩进。但是为什么要将这些变量声明为全局变量?
  • 在python中你不需要在使用前声明变量。只需删除def Spelling(),这两个global 语句并确保score=0 没有缩进,这应该可以工作。
  • 回溯(最近一次调用最后):文件“python”,第 10 行,在 NameError: global name 'score' is not defined

标签: python


【解决方案1】:
#revision platform
def Spelling():
    score = 0
    print("Welcome to the Spelling test.")
    Q1=raw_input("Which spelling is correct:\nChangeable\nChangeble\n")
    if Q1=="Changeable":
        print("Correct")
        score +=  1
    else:
        print("Incorrect")
    Q2=raw_input("Which spelling is correct:\nThreshhold\nThreshold\n")
    if Q2=="Threshold":
        print("Correct")
        score += 1
    else:
        print("Incorrect")
    Q3=raw_input("Which spelling is correct:\nScent\nSent\nCent\n")
    if Q3=="Scent" or Q3=="Sent" or Q3=="Cent":
        print("Trick Question they were all right!")
        score += 1
        print("Your score is:" ,score)
    else:
        print("Incorrect")
        print("Your score is:",score)

只需调用 Spelling() 函数,您的程序就可以运行了

【讨论】:

    猜你喜欢
    • 2013-08-23
    • 1970-01-01
    • 2013-07-20
    • 2023-03-30
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    相关资源
    最近更新 更多