0
How can I use a variable made inside a function outside.
For example I want to make a module which takes square of input and adds them and print it. I took a challenge and try to define a function which take an input and squares it. I stored the result in a variable. But I am not able to use it outside. I want to know if it is possible or not. If possible I would like to know how to it. Thank you.
6 Answers
+ 5
Ok you need to just return the value. For ex
def function_variable(parameter):
Your code will go here
return result
By using above syntex whenever you will call function and pass parameter to it then after execution the result returned use variable to get its value
or else declare your variable as global so that you can use its value outside the function bit it is not recommended.
you can use global for this purpose
+ 6
It's not a secret that i don't like global variables, and we have had very controversal discussions on this item here in the forum. Here is a solution that works without global varibales.
def do_it(num):
times = 0
for i in range(num):
times += 1
return times
my_times = do_it(15)
print(my_times)
my_times = do_it(20)
print(my_times)
+ 2
What programming language are you using?
+ 1
Python 3.8
+ 1
times = 0
def do_it(num):
global times
for i in range(num):
times += 1
return times
print(do_it(15))
15
+ 1
Thankyou