Basic functional usage of Python3

  • 2020-04-02 13:54:56
  • OfStack

In general, a function is an organized, reusable, functional piece of code. Functions improve application modularity and code reuse. Python already provides many built-in functions, such as print(), and Python also allows users to customize functions.

This paper summarizes the usage of Python3 function with an example, as follows:

A, definitions,

Define a function using the keyword def, followed by the function name and a list of optional arguments placed in parentheses (), and the function contents begin with a colon and are indented. The general format is as follows:


def  The function name ( The list of parameters ): 
  """ docstring """ 
   The body of the function  
  return [expression] 

Note: parameter list optional, document string optional, return statement optional.

Example:


def fib(n): 
  """Print a Fibonacci series""" 
  a, b = 0, 1 
  while b < n: 
    print(b, end=' ') 
    a, b = b, a+b 
  print() 
 
fib(2000) # call 
f = fib  # assignment 
f(2000) 

The value of a function name is a user-defined function type. The value of the function name can be given another name so that it can also be used as a function.

Function variable scope

Variables defined inside functions have a local scope, and variables defined outside functions have a global scope. Note: global variables can be referenced within functions, but cannot be assigned (unless declared with global).


a = 5     #  The global variable a 
 
def func1(): 
  print('func1() print a =', a) 
 
def func2(): 
  a = 21  #  A local variable a 
  print('func2() print a =', a)  
 
def func3(): 
  global a 
  a = 10  #  Modify global variables a 
  print('func3() print a =', a) 
 
func1() 
func2() 
func3() 
print('the global a =', a) 

Third, function call

1. Normal call

As with function calls in other languages, Python calls a function with the same number of arguments as the formal arguments and corresponds to each other sequentially.


def fun(name, age, gender): 
  print('Name:',name,'Age:',age,'Gender:',gender,end=' ') 
  print() 
 
fun('Jack', 20, 'man') # call 


2. Call functions with keyword parameters

Functions can also be called with keyword arguments in the form keyword=value, because we specify the correspondence, so the order of the arguments doesn't matter.


def fun(name, age, gender): 
  print('Name:',name,'Age:',age,'Gender:',gender,end=' ') 
  print() 
 
fun(gender='man', name='Jack', age=20) # using keyword arguments 

3. Call functions with default arguments

Functions in Python can also specify default values for one or more arguments, which can be optionally omitted when called:


def fun(a, b, c=5): 
  print(a+b+c) 
 
fun(1,2) 
fun(1,2,3) 

Note: the default value is usually evaluated only once, but it is different if the default value is a mutable object, such as a list, dictionary, or object for most classes. For example, the following function accumulates parameter values in subsequent calls:


def fun(a, L=[]): 
  L.append(a) 
  print(L) 
 
fun(1) #  The output [1] 
fun(2) #  The output [1, 2] 
fun(3) #  The output [1, 2, 3] 

4. Call variable parameter function

Specify that a function can receive any number of arguments by adding an asterisk (*) or two asterisks (**) to the parameter.


def fun(*args): 
  print(type(args)) 
  print(args) 
 
fun(1,2,3,4,5,6) 
 
#  Output:  
# <class 'tuple'> 
# (1, 2, 3, 4, 5, 6) 

def fun(**args): 
  print(type(args)) 
  print(args) 
 
fun(a=1,b=2,c=3,d=4,e=5) 
 
#  Output:  
# <class 'dict'> 
# {'d': 4, 'e': 5, 'b': 2, 'c': 3, 'a': 1} 

From the output of the two examples, we can see that when the parameter is shaped like *args, any real participants passed to the function are packed into a tuple in position. When the parameter is shaped like **args, any keys =value passed to the function will be wrapped into a dictionary (dict).

5. Call functions by unpacking parameters

The last point was that when you pass any number of arguments you pack them into a tuple or dictionary, and of course if you pack them you unpack them. Unpack List, Tuple and Dictionary by single asterisk and double star:


def fun(a=1, b=2, c=3): 
  print(a+b+c) 
 
fun()  #  Normal call  
list1 = [11, 22, 33] 
dict1 = {'a':40, 'b':50, 'c':60} 
fun(*list1)  #  Unpack the list  
fun(**dict1) #  Unpack the dictionary  
 
#  Output:  
# 6 
# 66 
# 150 

Note: * for unpacking Sequence, ** for unpacking dictionary. Unpacking the dictionary gives you a list of keys =value, so you essentially call the function with keyword arguments.

Lambda expressions

Lambda keywords can create small anonymous functions. Lambda functions can accept any number of arguments but can only return the value of one expression. The general form is as follows:


lambda [arg1 [,arg2,.....argn]] : expression 

Lambda expressions can be used wherever function objects are needed, and they are syntactically limited to a single expression:


f = lambda x, y: x+y 
print(f(10, 20)) 

def make_fun(n): 
  return lambda x: x+n 
 
f = make_fun(15) 
print(f(5)) 

Document strings

The first statement of the body can be a string enclosed in three quotes, which is the function's docstring, or docstring. We can output the document using print(function.


def fun(): 
  """Some information of this function. 
  This is documentation string.""" 
  return 
 
print(fun.__doc__) 

Docstrings are used primarily to describe information about functions, allowing users to interactively browse and output . It is recommended that you get into the habit of adding documentation strings to your code.


Related articles: