Skip to content Skip to sidebar Skip to footer

Python: How To Use Named Variables From One Function In Other Functions

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

Solution 1:

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

deffunction2():
    name = input("Enter name: ")
    return name

deffunction3():
    print(function2())

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

classA(object):

   deffunction1(self):
       print("hello")

   deffunction2(self):
       self.name = input("Enter name: ")

   deffunction3():
       print(self.name)

   defmain(self):  
       self.function1()
       whileTrue:
          funtion2()
          function3()
          ifnot self.name:
              break

A().main()

Solution 2:

Define the variable outside of your functions, and then declare it first as global inside with the global keyword. Although, this is almost always a bad idea because of all of the horrendous bugs you'll end up creating with global state.

Post a Comment for "Python: How To Use Named Variables From One Function In Other Functions"