Python function basic learning


Function definition and call:

**def function name (parameter 1, parameter 2): **

'''Function comment'''

print('function body')

return return value

Definition: def keyword switch, followed by a space followed by the function name and parentheses, and finally a colon at the end

def is fixed and immutable

Function name: The function name contains any combination of letters, numbers, and underscores (cannot start with a number)

Function call: return value = function name (parameter 1, parameter 2)

Function return value:

1- The role of return: end the execution of a function

2- First, the return value can be any data type

3- The function can have a return value: if there is a return value, it must be accepted by a variable to have an effect

There can also be no return value:

  1. When return is not written, the function return value is None
  2. When only one return is written, the function return value is None
  3. When return Nonede, the function return value is None (almost useless)

4- return returns a value (a variable)

5- return returns multiple values (multiple variables): multiple values are separated by commas and returned in the form of a tuple

Accept: You can use one variable to receive, or you can use multiple variables to receive (return only a few variables to use)

The parameters of the function:

1- Actual and formal parameters:

Formal parameters: are the parameters defined when the function is defined

Actual parameters: the parameters passed in when the function is called

2- Pass multiple parameters:

Multiple parameters can be passed, separated by commas.

From the perspective of passing parameters, there are two ways to call a function by passing parameters:

  1. Pass parameters according to location
  2. Pass parameters by keyword

Usage: 1-Positional parameters must be before the keyword parameters

2- Can only be assigned once for a parameter

3- Default parameters:

Usage: Why use default parameters? Set the small change value as the default parameter

Definition: The default parameter can not be passed. When it is not passed, the default value is used. If passed, the default value will be overwritten.

The default value is determined when the function is defined

3- Dynamic parameters:

The redundant parameters passed by position will be received uniformly by args and saved in the form of a tuple

Receive multiple keyword parameters by value by keyword, received by kwargs, and saved in the form of a dict

summary:

  1. Definition: The def keyword starts with the function name and parentheses () after the space.

  2. Parameters: Parentheses are used to receive parameters. If multiple parameters are passed in, separate the parameters with commas.

Multiple parameters can be defined or not defined.

There are many kinds of parameters. If multiple parameter definitions are involved, they should always be defined in the order of positional parameters, *args, default parameters, and **kwargs.

For example, a certain parameter type defaults in the above definition process, and other parameters still follow the above order

  1. Comment: The first statement of the function should be commented.

  2. Function body: The function content starts with a colon and is indented.

  3. Return value: return [expression] End the function. Return without expression is equivalent to returning None

def function name (parameter 1, parameter 2, *args, default parameter, **kwargs):

""" Note: Function and parameter description """

Function body

……

return return value


Advanced learning of python functions

Ternary operator

Result + if + condition + else + result

One, namespace and scope

The essence of the namespace: stores the name and worthy binding relationship

There are three types of namespaces:

Global namespace

Local namespace

Built-in namespace

The order of loading and value selection among the three: (namespace and scope are inseparable)

Loading sequence: built-in namespace (load before running) ->

Global namespace (running: loading from top to bottom) ->

Local namespace (run: load only when called)<

Value:

Called locally: local namespace -> global namespace -> built-in namespace

Call in the global: global namespace -> built-in namespace

Scope:

Why is there a concept of scope:

In order that the variables in the function will not affect the global

The scope is the scope, according to the effective scope can be divided into global scope and local scope

Global scope: Contains built-in name space, global name space, can be referenced anywhere in the entire file, globally effective

Local scope: local namespace, which can only take effect in the local scope

Look at the big picture: use names:

If the global is useful, the global: if the global is not used, the built-in

Two, function nesting and scope chain

Nested function calls:

1 # Nested function call
 23 def max2(x,y):45 m = x if x>y else y
 67 return m
 891011 def max4(a,b,c,d):1213 res1 =max2(a,b)1415 res2 =max2(res1,c)1617 res3 =max2(res2,d)1819return res3
20212223... max4(23,-7,31,11)...

Nested definition: functions defined inside cannot be directly called globally

In order to protect internal functions, make sure that internal functions can only be called in external functions

 def animal():

 def tiger():print(‘ bark ’)print(‘ eat ’)tiger()animal()

The scope chain of the function:

Third, the essence of the function name (——memory address)

1- Can be quoted

2- Can be used as a container type element

3- Can be used as function parameters and return values (can be used as ordinary variables)

Four, closure

Internal functions contain references to externally-scoped rather than global-acting names. (Function reference to the upper domain name)

 def func():

 name = ‘eva’

 def inner():print(name)

Decorator

The essence of decorator: a closure function

The function of the decorator: extend the function of the original function without modifying the original function and its calling method

**Syntactic sugar: **

1 import time
 23 def timer(func):45 def inner():67 start = time.time()89func()1011print(time.time()- start)1213return inner
1415 @ timer# ==> func1 =timer(func1)===>Syntactic sugar
1617 def func1():1819print(‘in func1’)2021func1()

·Open and closed principle: open to expansion and closed to modification

1- Open to expansion

Why should it be open to extensions?

We said that for any program, it is impossible to have all the functions in mind at the beginning of the design and do not make any updates or modifications in the future. So we must allow code expansion and add new features.

2- Closed for modification

Why should it be closed to modification?

As we just mentioned, because a function we wrote is likely to have been delivered to others to use, if we modify it at this time, it is likely to affect other users who are already using the function.

The decorator perfectly follows this open and closed principle.

The main function and fixed format of the decorator: add some functions before and after the function without changing the way the function is called.

Fixed format: (fixed universal format)

1 def timer(func):2345 def inner(*args,**kwargs):6789...What to do before executing the function...10111213 re =func(*args,**kwargs)14151617...What to do after executing the function...18192021return re
22232425 return inner

Decorator with parameters:

def outer(flag):

def timer(func):

def inner(*args,**kwargs):if flag:print(&quot;What to do before executing the function&quot;)
re =func(*args,**kwargs)if flag:print(&quot;What to do after executing the function&quot;)return re

return inner

return timer

@ outer(False)

def func():print(111)func()

Multiple decorators decorate the same function:

def wrapper1(func):

def inner():print(‘wrapper1,before func’)func()print(‘wrapper1,after func’)return inner

def wrapper2(func):

def inner():print(‘wrapper2,before func’)func()print(‘wrapper2,after func’)return inner

@ wrapper1

@ wrapper2

def f():print(‘in f’)f()

Recursion and bisection algorithm

Recursion: call the function itself in a function

1 import sys
23 print(sys.setrecursionlimit(100000))

Recursively implement a three-level menu:

1 menu ={2&#39;Beijing&#39;:{3&#39;Haidian&#39;:{4&#39;Wudaokou&#39;:{5             ‘soho’:{},6&#39;NetEase&#39;:{},7               ‘google’:{},8},9&#39;Zhongguancun&#39;:{10&#39;iqiyi&#39;:{},11&#39;Car House&#39;:{},12                 ‘youku’:{},13},
14 &#39;Shangdi&#39;:{15&#39;Baidu&#39;:{},16},17&#39;Changping&#39;:{18&#39;Shahe&#39;:{19&#39;Old Boy&#39;:{},20&#39;Beihang&#39;:{},21},
22 &#39;Tiantongyuan&#39;:{},23&#39;Huilongguan&#39;:{},24},25&#39;Chaoyang&#39;:{},26&#39;East City&#39;:{},27},
28 &#39;Shanghai&#39;:{29&#39;Minhang&#39;:{30&#39;People&#39;s Square&#39;:{31&#39;Fried Chicken Shop&#39;:{}32},33},34&#39;Pudong&#39;:{},35},36&#39;Shandong&#39;:{},37}3839 def three(dic):40for key in dic :41print(key)42 k =input(“>>>>>>>>”)43if k in dic:44three(dic[k])45three(dic)

Binary search algorithm:

1 l =[2,3,5,10,15,16,18,22,26]23 def find( l,aim,start,end ):45 mid =( end+start )// 267if(l[mid]> aim):89 end = mid
1011 returnfind(l,aim,start,end)1213elif(l[mid]< aim):1415 start = mid
1617 returnfind(l,aim,start,end)1819else:2021return mid
2223 print(find( l,15,start=0,end=len(1)-1))

Recommended Posts

Python function basic learning
python_ crawler basic learning
Python magic function eval () learning
Learning Python third day one-line function
python learning route
Python3 basic syntax
Python basic summary
python list learning
Python enumerate() function
Python basic operators
Python function buffer
Python entry learning materials
Python basic syntax generator
Python custom function basics
Python basic drawing tutorial (1)
Join function in Python
Python3 entry learning four.md
Python built-in function -compile()
Python data analysis-apply function
Python3 built-in function table.md
Python basic data types
Basic syntax of Python
Basic knowledge of Python (1)
python_ regular expression learning
Python3 entry learning three.md
Python3 entry learning one.md
Python basic data types
Python Print print timer function
Python3 entry learning two.md
Python basic syntax iteration
Python defines a function method
Python high-order function usage summary!
Python realizes online translation function
Python regular expression quick learning
Python basic syntax list production
Python programming Pycharm fast learning
Getting started python learning steps
Python tornado upload file function
Python basic drawing tutorial (two)
How Python implements FTP function
Python implements image stitching function
Python high-order function usage summary!
Python telnet login function implementation code
Python| function using recursion to solve
Python regular expression learning small example
Python introductory notes [basic grammar (on)]
How Python implements the mail function
Why doesn&#39;t Python support function overloading?
Is there function overloading in python
Python file operation basic process analysis
Python function definition and parameter explanation
Python crawler basic knowledge points finishing
Python ATM function implementation code example
Real zero basic Python development web
Python implements AI face change function
Python realizes image recognition car function
Python implements ftp file transfer function
Python realizes udp transmission picture function
How Python implements the timer function
Learning path of python crawler development
Python basic syntax and number types