1

The use of the command "return" has always been bothering me since I started learning Python about a month ago(completely no programming background)
The function "double()" seems working fine without me have to reassign the value of the list used as an argument for the function and the value of the elements processed by the function would double as planned. Without the need to assign it outside the function.

However, the function "only_upper()" would require me to assign the list passed as argument through the function in order to see the effect of the function. I have to specify t=only_upper(t) outside of the function to see the effect.

So my question is this: Why are these two seemingly same function produces different result from the use of return?

Please explain in terms as plain as possible due to my inadequate programming skill. Thank you for your input.

def double(x):
    for i in range(len(x)):
        x[i] = int(x[i])*2
    return x

x = [1, 2, 3]
print double(x)

def only_upper(t):
    res = [] 
    for s in t: 
        if s.isupper(): 
            res.append(s) 
    t = res  
    return t 

t = ['a', 'B', 'C']
t = only_upper(t)
print t
MorboRe'
  • 151
  • 10
  • 3
    possible duplicate of [In Python, why can a function modify some arguments as perceived by the caller, but not others?](http://stackoverflow.com/questions/575196/in-python-why-can-a-function-modify-some-arguments-as-perceived-by-the-caller) – ecatmur May 26 '15 at 09:08
  • I find the original poster's code quite difficult to understand. I will try again later on tonight hoping to see what's the OP meant.... thanks for the input nonetheless :) – MorboRe' May 26 '15 at 21:23

1 Answers1

0

i am assuming that this is your first programming language hence the problem with understanding the return statement found in the functions.

The return in our functions is a means for us to literally return the values we want from that given 'formula' AKA function. For example,

def calculate(x,y):
    multiply = x * y
    return multiply

print calculate(5,5)

the function calculate defines the steps to be executed in a chunk. Then you ask yourself what values do you want to get from that chunk of steps. In my example, my function is to calculate the multiplied value from 2 values, hence returning the multiplied value. This can be shorten to the following

def calculate(x,y):
    return x * y
print calculate(5,5)
Kode.Error404
  • 573
  • 5
  • 24