Python: How to use named variables from one function in other functions

前端 未结 2 565
北恋
北恋 2021-01-21 08:56

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()

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-21 09:24

    Don't try to define it a global variable, return it instead:

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

    If you want to use variables defined in function to be available across all functions then use a class:

    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()
    

提交回复
热议问题