preloader

Python101: 17. Functions and Arguments

post thumb
Python
by Admin/ on 15 Jul 2021

Python101: 17. Functions and Arguments


Defining a function is very simple, but how to define a function, what parameters are needed, and how to call it is a question we need to think about.

Like most languages (e.g., Java), Python provides a variety of parameters (e.g., default value parameters, keyword parameters, formal parameters, etc.). The code defined using these parameters allows us to adapt to different open scenarios and also simplifies our code development work.


Default Value Parameters


After we create a function that defines one or more of its parameters with default values, we can call this function with fewer parameters than allowed, as an example (Note: the following code uses python version 3.7).

def def_param_fun(prompt, retries=4, reminder='Please try again!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)


        
# We can call it as follows
def_param_fun('Do you really want to quit?')

def_param_fun('Do you really want to quit?', 2)

def_param_fun('Do you really want to quit?', 2, 'Please, yes or no!')

As shown above, we can use one or more parameters to call this function, we actually produce, in many cases will give the function parameters default value of the situation, so the reasonable use of such parameters can simplify our workload a lot.

Important: When using default value arguments, we may call functions with results that do not match our expectations if our default value is a mutable object. As follows.

def f(a, l=[]):
    l.append(a)
    return l

# At this point, call the function
print(f(1))
print(f(2))
print(f(3))

# Return value
# [1]
# [1, 2]
# [1, 2, 3]

This is due to the fact that the default value is only executed once when the function is initialized, so where the default value is a mutable object (lists, dictionaries, and most class instances), we can do the following.

def f(a, l=None):
    if l is None:
        l = []
    l.append(a)
    return l

# Call the function again
print(f(1))
print(f(2))
print(f(3))

# Return value
# [1]
# [2]
# [3]

Variable parameters

Variable parameters means that the parameters defined in the function can be one or more variable, where *args means that a list or tuple can be passed in, and *args means that a dict can be passed in.

def variable_fun(kind, *arguments, **keywords):
    print("friend : ", kind, ";")
    print("-" * 40)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    for kw in keywords:
        print(kw, ":", keywords[kw])


# function calls
variable_fun("xiaoming",
             "hello xiaoming", "nice to meet you!",
            mother="xiaoma",
            father="xiaoba",
            son="see you")


            
# Output results
# first arg: xiaoming ...
# ----------------------------------------
# hello
# nice to meet you!
# ----------------------------------------
# mother : xiaoma
# father : xiaoba
# son : see you

We can also make a call using the following to get the same result as above.

list01 = ["hello xiaoming", "nice to meet you!"]
dict01 = {'mother': 'xiaoma', 'father': 'xiaoba', 'son': 'see you'}
variable_fun("xiaoming", *list01, **dict01)

The above is actually a python unpacking operation, similar to java.

Keyword Parameters


Keyword arguments allow you to call a function with zero or any number of arguments with parameter names, which gives us the flexibility to make parameter calls. As an example.

# Borrowed example from official website
def key_fun(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This key_fun wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")

# function calls
key_fun(1000) # 1 positional argument
key_fun(voltage=1000) # 1 keyword argument
key_fun(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
key_fun(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
key_fun('a million', 'bereft of life', 'jump') # 3 positional arguments
key_fun('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword

Note that you cannot pass the value repeatedly, otherwise the following error will be reported:

# TypeError: key_fun() got multiple values for argument 'voltage'
key_fun(100, voltage=1000) # error

Summary


This section briefly introduced the use of function arguments in python. The settings can be used in conjunction with each other, but don’t over-design them, otherwise they will cause the readability of the function to become poor.


Reference

https://github.com/JustDoPython/python-100-day/tree/master/day-017

comments powered by Disqus