For more cases, please pay attention to my blog: home.cnblogs.com/u/Python1234

Welcome to join thousands of people and share resources: 125240963

There is nothing to say

If the function does not return a value, you can return to None

Used for occupying

Three. Built in data structure

list

set

dict

tuple

list(List)

# 1, Create an empty list L1 =

[]

# 2. Create a list of values L2 = [100

]

# 3. Create a list with multiple values L3 = [2, 3, 1, 4, 6, 4, 6

]

# 4. Using list () L4 = list ()

# Using list a to create a list B B code, the following code means that for all elements in a, add the new list B one by one, B = [i * 10 for I in

a]

# You can also filter the content disease in the original list into a new list, such as the original list a, to generate a new list of B a = [x for X in range (1, 35)) to generate a list from 1 to 34.Generate all the even numbers in a to a new list B B = [m for m in a if M% 2 = =

0]

# The list generation can be nested by two lists of a, B a = [i for I in range (1, 4)] list generates a list = B, a (100, 400)F I% 100 = = = =

0]

# List generation is nested, which is equal to two for loops nested C = [M + n for m in a for N in

b]

# The above code is equivalent to the following code for m in

a:

for n in

b:

print (m + n, end = ” “

)

# Nested list cities can also use conditional expression C = [M + n for m in a for N in B N + + 250;]

On the common functions of lists

copy: Copy, this function is a shallow copy

b = a.copy()

count:Find the number of specified values or elements in the list

a_len = a.count( 8 )

extend:Expand the list, two lists, and splice one directly into the next one.

a = [ 1 , 2 , 3 , 4 , 5

]

b

= [ 6 , 7 , 8 , 9 , 10

]

a.extend(b)

remove:Deletes the element of the specified value in the list (if the deleted value is not in list, it is wrong).

clear:empty

reverse:Flip the content of the list and turn it in

a = [ 1 , 2 , 3 , 4 , 5

]

a.reverse()

del delete

pop，Take an element from the counterpoint, that is, take the last element out.

last_ele = a.pop()

insert: Enact position insertion

# insert(index, data), The insertion position is a.insert (3, 666) in front of index.

append Insert a content, add to the end

a = [ i for i in range( 1 , 5

)]

a.append(

100 )

min

list：Convert data from other formats into list

# Convert the content generated by range to list print (list (range (12, 19))).

max:Find the maximum in the list

b = [ ‘ man ‘ , ‘ film ‘ , ‘ python ‘

]

print (max(b))

len:List length

a = [x for x in range( 1 , 100

)]

print (len(a))

tuple(Tuple)

# Create the empty tuple t =

()

# Create a tuple with only one value t = (1

,)

t

= 1

,

# Create a tuple of tuples t = (1, 2, 3, 4, 5).

)

t

= 1 , 2 , 3 , 4 , 5 # Use other structures to create L = [1, 2, 3, 4, 5

]

t

= tuple(l)

The characteristics of the tuple

Sequence table, order

The value of the tuple data can be accessed and can not be modified

The tuple data can be any type

listAll features except for modifiable tuples are available.

Function of a tuple

len: Get the length of a tuple

max, min:Maximum minimum

count: Calculate the number of times the data appears

index:Find the index position of elements in the tuple

set(Set)

# The definition of the set s =

set()

# At this time, brackets must have values, otherwise it is defined as a dict s = {1, 2, 3, 4, 5, 6, 7.

}

# If it is only defined with braces, it is defined as a dict type D = {}.

The features of a set

Data in the collection is out of order, that is, index and fragmentation can not be used.

The collection of internal data elements is unique and can be used to exclude duplicate data.

Data in the collection, STR, int, float, tuple, frozen set, etc., that is, only hash data can be placed inside.

Set sequence operation

Member detection (in, not in)

ergodic

# for Cyclic s = {{4, 5, ‘I’

}

for i in

s:

print (i, end = ” “

)

# Sets with tuples are traversed by S = {(1, 2, 3), (“just”, “for”, “fun”), (4, 5, 6).

)}

for k,m,n in

s:

print (k, ” — ” , m, ” — “

, n)

for k in

s:

print (k)

Connotations of set

# The following sets are automatically filtered out after initialization. S = {23, 223, 545, 3, 1, 2, 3, 4, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,

}

# Common set connotation SS = {i for I in

s}

# Conditional set connotations SSS = {i for I in s if I% 2 = =

0}

# The connotations of the set of multiple cycles S1 = {{{1, 2, 3, 4

}

s2

= { ” just ” , ” for ” , ” fun “

}

s

= {m * n for m in s2 for n in

s1}

s

= {m * n for m in s2 for n in s1 if n == 2 }

Set function

len, max, min

set:Generating a set

add：Adding elements to the set

clear

copy

remove:Remove the set value and change the original value directly. If the value to be deleted does not exist, it is wrong.

discard:Removing the specified value in the collection is the same as remove, but if you want to delete it, you will not report it wrong.

pop Random removal of an element

function

intersection: intersection

difference:Difference set

union: Union

issubset: Check whether a set is another subset

issuperset: Check whether one set is another superset

# Create s = frozenset ()

dict(Dictionary)

There is no sequential combination of data, and data appears in key value pairs.

# Create an empty dictionary 1 d =

{}

# Create an empty dictionary 2 D =

dict()

# Create a value dictionary. Each set of data is separated by colon. Each pair of key values is separated by commas. D = {“one”: 1, “two”: 2, “three”: 3).

}

# Using dict to create a content Dictionary 1 d = dict ({“one”: 1, “two”: 2, “three”: 3)

})

# Using dict to create a content dictionary 2, using keyword parameter d = dict (one = 1, two = 2, three = 3

)

# d = dict( [( ” one ” , 1 ), ( ” two ” , 2 ), ( ” three ” , 3 )])

The characteristics of the dictionary

A dictionary is a sequence type, but it is an unordered sequence, so there is no fragmentation and index.

Every data in the dictionary has a pair of key pairs, that is, kV pairs.

key: Must be the value of a hash, such as int, string, float, tuple, but list, set, dict are not.

value: Any value

Dictionary common operation

# Access data d = {“one”: 1, “two”: 2, “three”: 3

}

# Note that the parentheses in the access format are key values print (d[“one”).

])

d[

” one ” ] = ” eins ” # Delete an operation using del to operate del d[“one”.

]

# Member detection, in, not in in detection detected key content d = {“one”: 1, “two”: 2, “three”: 3).

}

if 2 in

d:

print ( ” value “

)

if ” two ” in

d:

print ( ” key “

)

if ( ” two ” , 2 ) in

d:

print ( ” kv “

)

# Use key to use for loop d = {“one”: 1, “two”: 2, “three”: 3).

}

# Using the for loop, for K in is accessed directly by the key value

d:

(k, d[k])

# The above code can be rewritten as for K in

d.keys():

(k, d[k])

# Only access to the value of the dictionary for V in

d.values():

(v)

# Pay attention to the following special usage: for K, V in

d.items():

print (k, ‘ — ‘ ,v)

Dictionary generation

d = { ” one ” : 1 , ” two ” : 2 , ” three ” : 3

}

# Conventional dictionary generation DD = {k:v for K, V in

d.items()}

# Lexicon generation with restricted conditions DD = {k:v for K, V in d.items () if v% 2 = = 0}

Dictionary related functions

len, max, min, dict

str(Dictionary: return the string format of the dictionary

clear: Empty dictionary

items: Return the key value of the dictionary to the composition of the tuple format

keys:A structure that returns the keys of a dictionary

values: In the same way, an Iterable structure

get: Return the corresponding value based on the set key

d = { ” one ” : 1 , ” two ” : 2 , ” three ” : 3

}

print (d.get( ” on333 “

))

# getThe default value is None, and you can set print (d.get (“one”, 100)).

fromkeys: Using a specified sequence as a key, using a value as the value of all keys in the dictionary.

l = [ ” eins ” , ” zwei ” , ” drei “

]

# Note the type of fromkeys two parameters. Note that the calling body of fromkeys is d = dict.fromkeys (L, “oops”).

Four. Expression

operator

Arithmetic operator

Comparison or relation operator

Assignment Operators

Logical operator

Bit operation

Member operation

Identity operator

Arithmetic operator

Plus +

Minus –

By *

Except /

Remainder%

The dealer (floor) / / /

Power operation * *

:warning:Python No self incrementing operator

Comparison operator

==

!=

>=

<=

The result of comparison is the Boolean value (True/False)

Assignment Operators

+= （-=， ×=， /=, //=, %=, **=）

Logical operator

and Logic and

or Logic or

not Logic non

As a result, if 0 is False, or True

short circuit

Python There is no other or operation in it

Member operation symbol

Used to detect whether a variable is a member of another variable.

in

not in

Identity operation

is: It is used to detect whether two variables are the same variable

is not: Two variables are not the same variable

Operator precedence

Parentheses have the highest priority

** Index (highest priority)

~ + – Bit by bit flipping

,

The one plus plus and minus sign (the last two methods are called + / and].

* / % // Multiplying, removing, drawing and removing

+ – addition and subtraction

\>> << Right shift, left shift operator

& Bit’AND’

^ | Bitwise Operators

<

= < > > =

Comparison operator

<>

== ! =

equal operator

= % = / = // = – = + = * = ** =

Assignment Operators

is is not Identity operator

in not in member operator

not or and Logical operator

Five. Program structure

order

branch

Basic grammar

# The colon behind the expression can not be small. Indent is used to represent the same block if.

Conditional expression:

Statement 1

Statement 2

Statement 3

..

Bi-directional branch

# if And else a hierarchy, the rest of the statement is a level if.

Conditional expression:

Statement 1

Statement 2

else

:

Statement 1

Statement 2

switch

if

Conditional expression:

Statement 1

.

elif

Conditional expression:

Statement 1

elif

Conditional expression:

Statement 1

..

else

:

Statement 1

.

Python No switch-case statement

loop

for loop

for Variable in

Sequence:

Statement 1

Statement 2

range

Generating a digital sequence

Scope: [m, n)

# Print 1~10 for I in range (1, 11)

):

print (i)

for-else

When the for loop ends, the else statement is executed

elseStatement selectable

while loop

while

Conditional expression:

Statement block

# Another expression while

Conditional expression:

Statement block 1

else

：

Statement block 2

Cyclic break, continue, pass

break： Unconditionally end the whole cycle, short of sudden death

continue：Unconditionally terminate this cycle, from the new to the next cycle.

pass：Indicates skipping, usually used for standing, without skipping function.

Six. Function

defKeyword

Code indentation

# Define def

func():

print ( ” This is a function “

)

# Call func ()

Parameter and return value of a function

Parameter: responsible for transferring necessary data or information to function.

Formal parameter (formal parameter): the parameter used in function definition is not a specific value, it is just a symbol of occupation, and becomes a parameter.

Argument (real parameter): the value entered when calling the function.

Return value: the result of the function

Using the return keyword

If there is no return, the default returns a None

Once the function executes the return statement, it returns unconditionally, that is, the execution of the ending function.

# returnThe basic use of the sentence is to return a sentence def after the greeting function.

hello(person):

print ( ” {0}, Are you swollen? “

.format(person))

print ( ” Sir, If you ignore the amount, you go. “

)

return ” I’ve greeted {0}, and {1} doesn’t look at me. “

.format(person, person)

p

= ” “Ming moon” RST =

hello(p)

print (rst)

# Define a function to print a 99 multiplication table def

printLine(row):

for col in range( 1 , row + 1

):

# printThe default function of the function is printed after completing the line print (row * col, end = “”).

)

print ( “”

)

# 99 multiplication tables, version 2 for row in range (1, 10)

):

printLine(row)

Parameter detailed solution

Parameter classification

Common parameters

Default parameters

Keyword parameters

Collection of parameters

Common parameters

See the above example

Defining a variable name directly at the time of definition

When you call, put the variable or value directly in the specified location.

def Function name (parameter 1, parameter 2,

.):

Function body

# Call the function name (value1, Value2,

.)

Default parameters

The parameter has the default value

If you do not assign values to the corresponding parameters when invoking, use default values.

def func_name(p1 = v1, p2 = v2

.):

func_block

# Call 1

func_name()

# Call 2 value1 = 100 Value2 = 200 func_name (value1, Value2)

Keyword parameters

def func(p1 = v1, p2 = v2

..):

func_body

# Call function: func (P1 = value1, P2 = Value2)

.)

Collection of parameters

Place a parameter that has no location and cannot correspond to the parameter position of the definition, and place it in a specific data structure.

def func( *

args):

func_body

# Access to args according to the way list is used to get incoming parameters: func (P1, P2, P3).

..)

The sequential problem of collecting parameter mixed calls

Collection parameters, keyword parameters, general parameters can be mixed.

The rule of use is that common parameters and keyword parameters are preferred.

When it is defined, it usually looks for common parameters, keyword parameters, collection parameters tuple, and collection of parameters Dict

Return value

The difference between function and process

Whether there is a return value

You need to display the content with return,

If you do not return, return to None by default

Recursive function

pythonThere is a limit to the depth of recursion, exceeding the limit of the error

# F (1) = 1, f (2) = 1, f (n) = f (n-1), and f (n) = f (n-1).+ F (n-2), for example: 1,1, 2, 3,5,8,13……. N indicates the value of the Fibonacci sequence of the N number def.

fib(n):

if n == 1

:

return 1 if n == 2

:

return 1 return fib(n – 1 ) + fib(n – 2

)

print (fib( 3

))

print (fib( 10 ))

Hanoa problem

Rules:

Method：

n=1： Directly move a plate on A to C, A-> C

n=2:

n=3:

n = n：

Put small plates from A to B, A-> B

Put the big plate from A to C, A-> C

Put small plates from B to C, B-> C

Move the two plates on the A to the B through C, and invoke the recursive implementation.

Move the remaining largest plate on A to C, A-> C

The two plates on the B are moved to C by means of A, calling recursion.

N-1 plates on A are moved to B through C, calling recursion.

The largest plate on A is also the only one moving to C, A-> C

N-1 plates on B are moved to C through A, calling recursion.

Move one plate at a time

At any time, the big plate is underneath, and the small plate is on it.

def

hano(n, a, b, c):

”’

Recursive implementation of Hanoi Tower

n：Represent a few plates

a：The first tower, the beginning of the tower

b：A tower representing second towers.

c：Representing third towers, target towers

”’ if n == 1

:

print (a, ” –> “

, c)

return

None

”’

if n == 2:

print(a, “–>”, b)

print(a, “–>”, c)

print(b, “–>”, c)

return None

”’ # N-1 plates, from the a tower to the B tower with the help of C tower, are added to Hano (n – 1).

, a, c, b)

print (a, ” –> “

, c)

# N-1 plates from the B tower, with the help of a tower, moved to the C tower to Hano (n – 1, B, a, c).

a = ” A ” b = ” B ” c = ” C ” n = 1

hano(n, a, b, c)

n

= 2

hano(n, a, b, c)

n

= 3 hano(n, a, b, c)

Lookup function help document

Using help function

help( print )

Using __doc__

def

stu(name, age):

”’

This is the text content of the document

:param name: Express the name of the student

:param age: Indicate the age of the student

:return: This function has no return value

”’ pass print

(help(stu))

print ( ” * ” * 20

)

print (stu. __doc__ )

Seven, variable scope

Classification: according to the scope of action

Global (global): external definition of function

Local (local): definition within a function

LEGBPrinciple

L（Local）Local scope

E（Enclosing function locale）Outer nested function scope

G（Global module）Function definition in the module scope

B（Buildin）： pythonBuilt-in magic area

Lifting local variables as global variables (using global)

def

fun():

global

b1

b1

= 100 print

(b1)

print ( ” I am in fun “

)

# b2The scope of action is fun B2 = 99 print

(b2)

fun()

print (b1)

globals, localsfunction

Local variables and global variables can be displayed through globals and locals.

# globals Locals and globals and locals are called built-in functions a = 1 b = 2 def.

fun(c,d):

e

= 111 print ( ” Locals={0} “

.format(locals()))

print ( ” Globals={0} “

.format(globals()))

fun(

100 , 200 )

eval()function

Executes a string as an expression and returns the result after the expression is executed.

eval(string_code, globals = None, locals = None)

exec()function

Similar to the eval function, but do not return the result

exec (string_code, globals = None, locals = None)