0

Why I am getting an error? What is the purpose of return here?

return is supposed to return a value from the function that can be used in the whole program right? Why is it not working? https://code.sololearn.com/cbts65Vuvq1j/?ref=app

23rd Jul 2022, 10:36 AM
Logics Suker
Logics Suker - avatar
10 Answers
+ 3
Logics Suker no, "return" stops the function and outputs the value to be assigned to the variable, as shown in the first example.â˜ș
23rd Jul 2022, 11:06 AM
Solo
Solo - avatar
+ 6
Logics Suker , this may claryfy the use of return and the output from outside the function: (we don't need to use *global* variable when the code is done properly) def haha(x): # a = x # we don't need this #print(x*x) # option: print this expression from inside the function return x * x # e.g. return this expression res = haha(9) # we can accept the returned value from the function by storing it in variable like *res*. # it can be used for any purpose in main part of the program print(res) # last step is to output, or do with it whatever is needed ...
23rd Jul 2022, 11:15 AM
Lothar
Lothar - avatar
+ 3
"a" is a local variable, that is, it is defined inside the function and cannot be used outside of it. So you are trying to print another variable "а" that you haven't defined yet. #1: def haha(x): a = x print(x*x) return a a = haha(9) print(a) #2: a = 5 def haha(x): global a a = x print(x*x) haha(9) print(a) 👇👍 😉 def squaring(x): return x*x print(squaring(9))
23rd Jul 2022, 10:54 AM
Solo
Solo - avatar
+ 2
Solo what is the purpose of return statement then. Doesn't it returns anything that can be used in the whole program at any time?
23rd Jul 2022, 10:56 AM
Logics Suker
Logics Suker - avatar
+ 1
JOKER I do want to print variable a that is returned by the function
23rd Jul 2022, 10:45 AM
Logics Suker
Logics Suker - avatar
+ 1
def haha(x): print(x*x) haha(5)
24th Jul 2022, 10:14 AM
CodeStory
CodeStory - avatar
0
def haha(x): a = x return a*a print(haha(9)) #this
24th Jul 2022, 2:41 PM
emma
emma - avatar
- 1
def haha(x): print(x*x) return x*x haha(9) print(haha)
24th Jul 2022, 6:22 PM
Irshad Ahmad
Irshad Ahmad - avatar
- 1
Hello, your 'a' variable is inside the function scope and you re calling it on the global scope which will return an error since it is unknown to a global scope while declaring the 'a' to local/function scope.
25th Jul 2022, 8:41 AM
Christopher Sanchez
Christopher Sanchez - avatar
24th Jul 2022, 12:28 AM
athaleyah weise