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
10 Respostas
+ 3
Logics Suker no, "return" stops the function and outputs the value to be assigned to the variable, as shown in the first example.âșïž
+ 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 ...
+ 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))
+ 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?
+ 1
JOKER I do want to print variable a that is returned by the function
+ 1
def haha(x):
print(x*x)
haha(5)
0
def haha(x):
a = x
return a*a
print(haha(9))
#this
- 1
def haha(x):
print(x*x)
return x*x
haha(9)
print(haha)
- 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.