Foundation of Function

Introduction to Python #3

originally published on August 19th

To reduce redundant lines and write code more efficiently, Python has a function, also known as "subroutine" and "procedure". Using functions, the code will look neat and clean.

However, there are points to be paid attention to. First, only alphabet, numbers, and underscore _ are allowed for function names, and function names always have to begin with alphabets or numbers. Also, functions can be treated as objects in Python, so it is possible to store functions in variables and return functions themselves.

Python function defined with def. Also, literally, anything can go into arguments, so it is needed to be careful to use functions.

def <FUNCTION NAME> (ARG1, ARG2, ARG3, ...):
     <CODE BLOCK>
    return <RETURN VALUE> #(could be omitted)


Function with No Argument

The example code below just simply prints "Hello World!!".

def func ():
    print("Hello World!!")

func()


Function with Arguments.

In Python function, you can put arguments for parameters. Argument order is really important, and if mistakenly put the argument in different orders, then the program behaves as you do not expect. However, by using keyword argument, the argument orders are less important.

def func (person, theory, age):
    print(person + " found " + theory + " at the age of " + age)

func("Albert Einstein" , "Special Relativity Theorem", "26")
func("Universal Gravitation", "22", "Isaac Newton")
# use keyword arguments
func(theory = "Universal Gravitation", age = "22", person = "Isaac Newton")
# output
Albert Einstein found Special Relativity Theorem at the age of 26
# Does not make any sense
Universal Gravitation found 22 at the age of Isaac Newton
# but using keyword argument
Isaac Newton found Universal Gravitation at the age of 22

return statement

With return statement, you can get value when call a function. In the example below, add() is a simple function that returns the sum of two objects. The example below returns the sum of integer, float, and string.

def add(a, b):

    summation = a + b
    return summation

print(add(1, 1)) 
print(add(0.01, 0.01))
print(add([1, 2, 3], [4, 5, 6]))
print(add((1, 2, 3), (4,5,6)))
print(add("Hello ", "World!"))
# output
2
0.02
[1, 2, 3, 4, 5, 6]
(1, 2, 3, 4, 5, 6)
Hello World!

Default parameter

Even though functions have parameters, programmers do not always have to put them on functions. If you set default values for parameters (just put "=" and the value in the arguments), you do not have to put the values in parameters.

def greeting(person, greeting = "Hello"): 
# using greeting is for default parameters.
    print(person + " says \"" + greeting + "\"!");

greeting("Juan", "Ora")
greeting("Doe")
# output
Juan says "Ora"!
Doe says "Hello"!

However, if you want to use default parameters, you always have to put the default parameters on the later side.

def greeting(person = "John Doe", greeting):
    print(person + " says \"" + greeting + "\"!");

greeting("Juan", "Ora")
greeting("Doe")
# output
    def greeting(person = "John Doe", greeting):
                                      ^^^^^^^^
SyntaxError: non-default argument follows default argument

*args

Using *args, programmers will be able to pass unspecific numbers of arguments to a function. The arguments passed with *args are stored in a tuple.

def func(*args):

    print(args) # To see args is stored in tuple

    # printing each element in tuple
    for arg in args:
        print(arg)

func("Spring", "Summer", "Fall", "Winter")
('Spring', 'Summer', 'Fall', 'Winter')
Spring
Summer
Fall
Winter

**kwargs

**kwargs is called Keyword Arguments. With **kwargs, the parameters are going to be dictionary type. The argument must be passed like key=value. Otherwise, it returns errors.

def saying(**keywords):

    for kw in keywords:
        print(kw + " says " + keywords[kw])

saying(kennedy="Those who dare to fail miserably can achieve greatly",
           churchill="Success is not final, failure is not fatal: it is the courage to continue that counts",
           einstein="I have no special talent. I am only passionately curious")
kennedy says Those who dare to fail miserably can achieve greatly
churchill says Success is not final, failure is not fatal: it is the courage to continue that counts
einstein says I have no special talent. I am only passionately curious


Lambdas

Lambdas can be stored in variables. The [EXPRESSION] of lambdas is equivalent to return [VALUE]; of function.

lambda [ARG...]: [EXPRESSION]

Example of Lambdas

def func(a, b, c):
     return a * b * c;

print(func(1, 2, 3)); # 6

# this function is equivalent to the lambdas below.
    var = lambda a, b, c: a * b * c;
print(var(1, 2, 3));  # 6


Documentation Strings

Programmers prefer using """ or ''' rather than #. That is because __doc__ returns the string object which enclosed with """ or '''.

def add(a, b):
    '''
    add() function
    adding two numbers and return summation of them
    '''
    summation = a + b
    return summation

print(add.__doc__)
# output

    add() function
    adding two numbers and return summation of them

Conclusion

In Python, there are multiple ways to pass the argument, but some of them are really similar to the other languages. For instance, Java has a similar way of passing an argument of *args. C++ has default parameters. If the beginner has a foundation in the programming of other languages, it might be easier.

Did you find this article valuable?

Support Kojiro Asano by becoming a sponsor. Any amount is appreciated!