当一个变量已经在另一个 def 中声明时,我是否必须声明它两次?

do i have to declare a variable twice when it is already declared in another def?

我正在 python 做一个算术测验。在测验开始时,它询问用户 class 他们想要输入什么结果,这在 def classname() 中。稍后当测验完成时,如果用户不想像这样重复测验,程序会将分数写入文本文件:

def classname():
    class_name = input("Which class do you wish to input results for?")
    #  the rest of my code for my introduction 
    #
    #
    #
    #
def askquestion():
    # all of my code to ask the user the arithmetic question
    #
    #
    #
    # code to ask the user if they want to repeat the quiz
    #if they dont want to repeat the quiz then this code is run
    else:
        filename = class_name + ".txt"
        # code that will write the scores to a text file

当我 运行 这个代码时,我得到这个错误:

   filename = class_name + ".txt"
 NameError: name 'class_name' is not defined

我必须在 askquestion() 中再次声明变量 "classname" 还是有什么方法 python 可以识别我已经声明了变量?

除非您将变量定义为全局变量,否则您将不得不重新定义它,或者将代码中的值作为参数传递给后续函数。

您可以将参数传递给 askquestion,就目前而言,变量 class_name 超出了函数的范围。

因此,您的函数定义更改为

def askquestion(class_name):
    ...
    ...

现在,当您调用 askquestion 函数时,您必须将 class_name 传递给它。


一个工作示例如下所示:

def classname():
    class_name = input("Which class do you wish to input results for?")
    ...
    ...
    return class_name

def askquestion(class_name):
    ...
    else:
        filename = class_name + ".txt"
        # code that will write the scores to a text file

if __name__ == `__main__`:
    class_name = classname()
    askquestion(class_name)

您的代码在 class_name() 函数内声明了变量 class_name,因此外部无法访问它。如果您在 class_name() 函数之外声明变量 class_name,则 askquestion() 函数可以访问它。

函数内声明的变量是该函数的局部变量,需要传递或return编辑到其他方法或移出函数使其成为全局变量,这需要在使用时显式声明它在一个函数中:

所以你可以 return 来自 classname() 的 class_name 并在 askquestion() 中使用 classname():

def classname():
    class_name = input("Which class do you wish to input results for?")
    return class_name

def askquestion():
    ...
    else:
        filename = classname() + ".txt"
        # code that will write the scores to a text file