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.

9th Jun 2020, 4:23 PM
Krishna Agrawal
Krishna Agrawal - avatar
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
9th Jun 2020, 4:34 PM
Ayush Kumar
Ayush Kumar - avatar
+ 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)
9th Jun 2020, 5:31 PM
Lothar
Lothar - avatar
+ 2
What programming language are you using?
9th Jun 2020, 4:27 PM
Emanuel Maliaño
Emanuel Maliaño - avatar
+ 1
Python 3.8
9th Jun 2020, 4:28 PM
Krishna Agrawal
Krishna Agrawal - avatar
+ 1
times = 0 def do_it(num): global times for i in range(num): times += 1 return times print(do_it(15)) 15
9th Jun 2020, 4:33 PM
Slick
Slick - avatar
+ 1
Thankyou
9th Jun 2020, 5:36 PM
Krishna Agrawal
Krishna Agrawal - avatar