Junior — Middle
In Python, is it possible to use the value of a variable declared inside one function in another function?
sobes.tech AI
Answer from AI
In Python, variables declared inside a function have local scope and are not directly accessible in other functions. To use a value from one function in another, you can:
- Return the value from the first function and pass it to the second as an argument.
- Use global variables (not recommended due to poor practice).
- Use objects and class attributes to store state.
Example with returning a value:
def func1():
x = 10
return x
def func2(value):
print(f"Value from func1: {value}")
val = func1()
func2(val)
Thus, the variable's value is explicitly passed between functions.