Accessing variables inside a function

how do i access variables inside a function. suppose i have two functions function1 and function2 . function1 which has a input statement takes in the input does a couple operations on it and saves it in a variable say var1 in function1 and now i want to use var1 in function2 to do a couple of operations on it. how do i do it?i wrote some simple example code to give you an idea of the problem I’m facing. Basically i want two separate functions where my second function can access the variable in first function.
i know about scope and global variable and local variable btw.

#function1 adds stuff def function1(): input1 = input("enter number") input2 = input("enter a number") var1 = int(input1)+int(input2) #function2 prints stuff def function2(): print(var1) function1() function2()

Because of scoping, variables in one function are not accessible in any other scope, parent, or sibling.

To make a variable accessible in both functions it will need to be global and needs a global binding within the function that mutates it.

Methods in a class can access instance and class variables, which may fit with what you are attempting?

var = None
def foo():
  global var
  a, b = 6, 7
  var = a + b
def bar():
  print (var)
>>> bar()
>>> foo()
>>> bar()

thank you this solves my question. All i need to do now is first define the variable i want to access outside the function with none then inside the function i have to type global with the variable do my operations on it and then it will be saved to the global variable which i can access from anywhere.

var = None #function1 adds stuff def function1(): global var input1 = input("enter number") input2 = input("enter a number") var = int(input1) + int(input2) #function2 prints stuff def function2(): print(var) function1() function2()
1 Like

You’re welcome. Be sure to follow up with extra reading on pros and cons of global variables.

Happy coding!