Junior — Middle
Kas Pythonis on võimalik kasutada ühe funktsiooni sees deklareeritud muutuja väärtust teises funktsioonis?
sobes.tech AI
Vastus AI-lt
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 as an argument to the second.
- Use global variables (not recommended due to bad 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)
This way, the variable's value is explicitly passed between functions.