Functional usage of Python3 Foundation _python

Source: Internet
Author: User
Tags unpack in python

In general, a function is a well organized, reusable, functional piece of code. Functions can improve the modularity of applications and the reuse of code, and in Python there are many built-in functions such as print (), while Python allows users to customize functions.

This article on the example to summarize the function of Python3, the specific contents are as follows:

I. Definition

The definition function uses keyword Def, followed by a function name and an optional list of arguments in parentheses (), starting with a colon and indenting the contents. The general format is as follows:

def function name (argument list): "" Document String "" " 
  function body return 
  [expression] 

Note: The argument list is optional, the document string is optional, and the return statement is 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 # call 
f = fib  # assignment 
F (2000) 

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

Ii. Scope of function variables

Variables defined inside a function have a local scope that has a global scope defined outside the function. Note: A global variable can be referenced inside a function, but it cannot be assigned a value (unless declared with global).

A = 5     # global variable a 
 
def func1 (): 
  print (' Func1 () print a = ', a) 
 
def func2 (): 
  a =  # local variable a 
  print (' Fu NC2 () Print a = ', a '  
 
def func3 (): 
  global a 
  a =  # to modify the globally variable a 
  print (' func3 () print a = ', a) 
 
func 1 () 
Func2 () 
func3 () 
print (' The Global a = ', a) 

Third, function call

1. Normal call

As with function calls in other languages, when calling a function in Python, you need to give an argument with the same number of parameters and correspond in order one by one.

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


2. Call functions using keyword parameters

Functions can also be called by keyword=value keyword arguments, because we explicitly point to the corresponding relationship, so the order of the parameters is irrelevant.

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, calling a function with the default argument

A function in Python can also specify a default value for one or more parameters, so that the argument can be omitted selectively when invoked:

def fun (A, B, c=5): 
  print (A+b+c) 
 
fun (1,2) 
Fun (1,2,3) 

Note: Normally the default value is computed only once, but it will be different if the default is a Mutable object, such as a list, a dictionary, or an object of most classes. For example, the following function accumulates a parameter value in a subsequent call :

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

4. Call variable parameter function

Specifies that a function can receive any number of arguments by adding an asterisk (*) or a two asterisk (* *) before the formal 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, you can see that: When a parameter is shaped like a *args, any actual participants that are passed to the function are packaged into a tuple (tuple) by position, and when the parameter is like **args, any Key=value participants passed to the function are packaged into a dictionary (dict).

5, call the function by the solution package parameter

The point is that when you pass any number of arguments, they are packaged into a tuple or dictionary, and, of course, there are packages (unpacking). Unpack the list, tuple, and dictionary with single and double stars:

def fun (A=1, b=2, c=3): 
  print (A+b+c) 
 
fun ()  # normal call 
List1 = [one, 50] 
Dict1 = {' A ':, ' B ':, ' C ': 
Fun (*list1)  # Unpack List 
Fun (**dict1) # Unpack Dictionary 
 
# Output: 
# 6 # 
150 

Note: * Used to unpack the sequence,** for the package dictionary. The Che Bao Dictionary will get a series of key=value, so it is essentially calling the function with the keyword parameter.

Four, lambda expression

Lambda keywords can create small anonymous functions. A lambda function can receive any number of arguments but can only return the value of an expression, and its general form is as follows:

Lambda [arg1 [, Arg2,..... argn]]: expression 

Lambda expressions can be used wherever a function object is needed, and they are syntactically restricted to a single expression:

f = lambda x, y:x+y 
print (f (a)) 

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

V. Document STRINGS

The first statement of a function body can be a string enclosed in three quotes, which is the document string of the functions, or docstring. We can use print (function.__doc__) to output the document:

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

document strings are used primarily to describe information about functions that allow users to interactively browse and output . It is recommended that you develop a good habit of adding document strings to your code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: [email protected] and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.