Personal understanding of python functions (no parameters, formal and actual parameters, parameter types)

Posted by zack45668 on Thu, 03 Feb 2022 19:51:19 +0100

When writing automation use-case code, I always write a lot of functions and have a confusing understanding of their parameters. Here's a simple summary and summary of how functions are used

Function Definition

def Function name(Formal parameter 1,Formal parameter 2,...):
    #If it is necessary to return a result to the caller, it is necessary to add a return return value instead of a return value.
    return Return value

function call

Function name(Argument 1, Argument 2,...)

None of the following examples has a return value

Functions are divided into parameterized and parameterized functions according to whether they have parameters or not.

1. parameterless functions

Some arguments (variables, constants, expressions, functions, etc.) are not manipulated, and parameterless functions have no parameters and arguments.

Example 1: Define a function, function function: print hello. Call this function.

#Define Functions
def print_hello():
    print ('hello')
#Call function

Example 2: Define a function, open the traceless mode of chrome browser, and visit Baidu. Call this function.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from selenium import webdriver
#Define Functions
def open_baidu():
    options = webdriver.ChromeOptions()
    # incognito mode
    # Start chrome browser traceless mode
    driver = webdriver.Chrome(chrome_options=options)
    # Open Baidu
#Call function

From the two chestnuts above, you can see that if you do not need to operate on any parameters (variables, constants, expressions, functions, etc.), you do not need to add formal parameters when defining functions.

2. Functions with parameters

When you need to do something with some arguments (which can be variables, constants, expressions, functions, etc.), you need to define the parameters for the function and pass in the corresponding arguments when calling it.

Argument types include: positional argument, keyword argument

Parameter types include: default parameters, variable parameters, keyword parameters

2.1 Argument Type

2.1.1 Positional arguments: Require that the order of arguments be the same as that of parameters

Note: The position parameter position and number must correspond (as many parameters as arguments).

Raise a chestnut: Print name and results

def print_info(name,score):
    print name
    print score


ps: Sometimes I get confused at work, can arguments and parameters have the same name in python?

Then I try this: assign an argument to a variable, and the variable name is the same as the parameter name, and it runs as above.


def print_info(name,score):
    print name
    print score


The results run as follows:


2.1.2 Keyword arguments: Keyword arguments are name-value pairs passed to a function. Names and values are directly associated in arguments, so passing arguments to a function is not confusing.

What it does: It lets you ignore the order of arguments in a function call and clearly indicates the purpose of each value in a function call, so you don't need to consider the order when passing in.

Take a chestnut: (In this example, the argument position does not correspond to the parameter position)

def print_info(name,score):
    print name
    print score
#There is no corresponding parameter position here

The results are working correctly


2.2 Parameter Type

2.2.1. Default parameters

Take a chestnut: Calculate the n-th power of X, where in most cases n is 2 when calling a function and in rare cases n is another value when calling a function.

#Calculates the n-th power of x and returns the printed result
def power(x, n=2):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return print(s)




As can be seen from the example above:

When the default parameter is set, the argument does not need to pass in the same value as the default parameter (that is, it does not need to pass in argument 2 when calculating the square of 2,3,4, and it needs to be modified when calculating the third power of 5)

Note: The required parameters are first, and the default parameters are second (for example, x is first, n is last). (Otherwise, Python's interpreter will fail). When a function has more than one parameter, put the parameter with large change ahead and the parameter with small change behind. A parameter with a small change can be used as the default parameter.

2.2.2 Variable parameters

As the name implies, a variable parameter means that the number of parameters passed in is variable, either one, two, or any, or zero.

When the number of parameters passed in is uncertain, variable parameters need to be preceded by *

Example: Calculate the sum of the actual parameters of the input

#Calculate the sum of arguments
def Plus(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n
#The incoming parameter can be 0

Run result:


ps: Inside the function, the parameter numbers receives a tuple

If you already have a list or tuple, what about calling a variable parameter? You can do this:

def Plus(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n
#There is already a list
#Add before arguments*

*nums means that all elements of the list nums are passed in as variable parameters.

Run result:


2.2.3 Keyword Parameters

Keyword parameters allow you to pass in zero or any parameters with parameter names that are automatically assembled into a dict within a function. The keyword argument above is passed without regard to order, whereas the keyword argument here is any number of keyword arguments that can be passed in. Callers of functions can pass in any unrestricted keyword parameter (the key and value of the parameter are defined by themselves).

What is the difference between keyword arguments here and above? This keyword parameter is a hash of the parameter operation.

When the parameter passed in is a variable keyword parameter, the variable parameter needs to be preceded by **

Lift a chestnut:

#name and age are required parameters, **kw is optional
def person(name, age, **kw):
    print('name:', name, 'age:', age, 'other:', kw)
#You can add any number of arguments after name and age


name: jack age: 20 other: {'city': 'chengdu', 'hobby': 'draw'}

Similar to a variable parameter, you can assemble a dict and then convert it into a keyword parameter to pass in:

def person(name, age, **kw):
    print('name:', name, 'age:', age, 'other:', kw)
others_info= {'city': 'chengdu', 'hobby': 'draw'}

The result is the same:

name: jack age: 20 other: {'city': 'chengdu', 'hobby': 'draw'}

About Return Values

As the name implies, the value returned by a function is called a return value. (Listen to one of your words, such as one of your words)

When to use it?

If it is necessary to return a result to the caller, it is necessary to add a return return value instead of a return value.

In general, when calling a function with a return value, you need to provide a variable to store the returned value.

Raise a chestnut

def print_info(name,score):
    return print(name,'Achievements were',score)

jack 100

Topics: Python Functional Programming