Python: Passing variable between functions
In any language, we use variable to save some values , it could be anything int, float , list , dict etc , but if in python we like to use variable a function that was declared in another function.
While programming we do required functions results in another functions, which we use to work in another ways. We will take it in this post, where we will provide example in which one variable of a functions is used in another functions to work on another bigger objective.
Return in Functions
We can do this thing, with few ways. like an example if we return some variable in end of func1 and call that func1 for assignment variable in func2, will save variable of func1 to save in variable in func2.
Let’s see an example:-
import math def one(): radius = int(input(" please provide your radius to calculate area of circle: ")) return radius def area(): radius = one() print("Area of circle :", math.pi*(radius*radius)) if __name__ == "__main__": area()
When we run this program we return one variable from function “one” will save in another function “area” variable “radius”. It will run like this
please provide your radius to calculate area of circle: 10 Area of circle : 314.1592653589793
With above example, we can see it work like it need. So with return statement we do this task easily. We can even support multiple variable in one function.
Multiple return statements
def one(): name = input(" What's your name : ") age = input(" How old you are ..? : ") return name, age def introduction(): name, age = one() print(name, "is", age, "years old") if __name__ == "__main__": introduction()
When we run this code , we will able to call two variables from previous function to use in current function to use in some of its work like below
What's your name : Sang How old you are ..? : 33 Sang is 33 years old
With above two examples , now we know we could call variables from one functions towards another.