3

I'm a newbie programmer trying to make a program, using Python 3.3.2, that has a main() function which calls function1(), then loops function2() and function3().

My code generally looks like this:

def function1():
    print("hello")

def function2():
    name = input("Enter name: ")

def function3():
    print(name)

def main():
    function1()
    while True:
        funtion2()
        function3()
        if name == "":
            break

main()

Currently, I get the following error when I run the program and enter a name:

NameError: global name 'name' is not defined

I understand that this is because name is only defined within function2(). How do I make it so that name is defined as a 'global name', or somehow be able to use it within function3() and main().

Thanks in advance.

4

2 回答 2

4

不要尝试将其定义为全局变量,而是将其返回:

def function2():
    name = input("Enter name: ")
    return name

def function3():
    print(function2())

如果你想使用在函数中定义的变量在所有函数中都可用,那么使用一个类:

class A(object):

   def function1(self):
       print("hello")

   def function2(self):
       self.name = input("Enter name: ")

   def function3():
       print(self.name)

   def main(self):  
       self.function1()
       while True:
          funtion2()
          function3()
          if not self.name:
              break

A().main()
于 2013-11-13T06:00:41.530 回答
2

在函数外部定义变量,然后首先在内部使用global关键字将其声明为全局变量。虽然,这几乎总是一个坏主意,因为您最终会使用全局状态创建所有可怕的错误。

于 2013-11-13T06:01:13.060 回答