Functions in Python


I've got a couple of questions about functions in Python:

First question: Let's say we have this function def test(*arg)

Can we choose the parameter we want when defining a function? Because I see that *arg seems a little different than n, and what does *arg exactly do?

Second question: We have this code

    def fun_one(n):
          return n * 5

    def fun_two(m):
          return fun_one(m) + 7

Why does the fun_one(n) change into fun_one(m)?

A parameter acts like a variable for arguments, is that why we have to mention only fun_one and not its parameter? So, every time we want to add two functions, we only have to mention the function we want do add, in this case fun_one and the parameter's second function? Thanks

Thanks in advance.


*arg is useful, if you don't know how many arguments are going to be supplied into the function:

def test(*arg):
    for i in arg:

see? Now it prints all arguments. quit useful, you can read about it here

If you know the amount of arguments the function is going to get, you can name it anything you like (n for example), although i would choice logic names

because inside fun_two you call fun_with with argument n (the function parameter of fun_two)

think about what this code will produce as output:

def fun_one(n):
    return n * 5
def fun_two(m):
    return fun_one(m) + 7
print fun_two(3)

what do you think the output of the function is? Think about it for a second before reading further.

So, i call fun_two and as argument i supply 3, so m is now 3. then inside fun_two, i call fun_one, as argument i provide m (which is 3), so know fun_one gets executed. so now n is 3. 3 * 5 = 15, so fun_one return 15. so then we have:

return 15 + 7

so the outcome is 22, make sense?

I am a bit confused by the last part of your question. You can have function with parameters, which means they take no argument. The confusing bit here, is that you have a function calling another function, doesn't always have to be the case


Thanks for answering! And by the last part I meant that in the previous example provided with fun_one(n) and fun_two(m) if we want to have a function calling a function, do we always need to provide the fun_two's (m) and use it on fun_one?

I'm not sure by what you mean with


No, you don't have to. You can also call fun_one without m, but it depends on what your function is suppose to do

I meant you don't always have function calling other functions, not important


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.