Yes, I\'ve read tons of examples on this but I still don\'t get it.
I\'m learning Python and I made this script in order to help me understand how to \'return\':
you need to set a variable named "random"
so your calc_pay_rise function should look like:
def calc_pay_rise():
payrise = 5
random = random_number()
payrise = payrise + random
print payrise
your variable "random" in def calc_pay_rise() was never assigned. Try:
def calc_pay_rise():
payrise = 5
random = random_number()
payrise = payrise + random
print payrise
I'm not a python programmers, but this looks like a problem of scope. You did define the variable "random" but it's scope-- the section of the code where it is visible and usable-- is limited to the function where you define it. In this case, inside the random_number() function.
It is not visible inside the calc_pay_rise() function.
What is visible is the other function, random_number() itself.
That is what you need to use in your addition.
That is the basic point of returning values.
Try this:
payrise = payrise + random_number()
When you call a function that returns a value (a random number in this case), you're supposed to do something with the returned value.
Also notice that the variable random
that was defined locally inside random_number()
can not be "seen" from other functions - unless you declare a new variable locally, but it can have any name you want. Another way to say the same would be:
random = random_number() # can be any name, I'm using `random` again
payrise = payrise + random
In calc_pay_rise
, you are throwing away the value returned by the random_number()
call; instead, do randmom = random_number()
. What you've misunderstood is how variables work—local variables in one function (e.g. def random_number
) are not visible in other functions (e.g. def calc_pay_rise
).
def random_number():
random = 0 # not sure what's the point of this
return (random + 5) * 10
def calc_pay_rise():
return 5 + random_number()
calc_pay_rise()
I've also reduced the code by eliminated all the stuff that does nothing.
P.S. if the code is really reduced to the absolute minimum, you're left with nothing, because in its current form, the code does absolutely nothing:
def random_number():
random = 0 # not sure what's the point of this
return (random + 5) * 10
# is the same as
def random_number():
return 50
and
def calc_pay_rise():
return 5 + random_number()
# is the same as
def calc_pay_rise():
return 5 + 50 # because random_number always returns 50
and
calc_pay_rise()
# is really just the same as writing
5 + 50
# so you're not doing anything at all with that value, so you might as well eliminate the call, because it has no side effects either.