More cases please follow my blog: home.cnblogs.com/u/python1234
Welcome to join thousands of people Exchange resource sharing group: 125240963
It means there's nothing.
If the function does not return a value, you can return none
Used to occupy a position
Third, built-in data structure
List (lists)
# 1, create empty list L1 =
[]
# 2. Create a list with values L2 = [100
]
# 3. Create a list with multiple values L3 = [2, 3, 1, 4, 6, 4, 6
]
# 4. Use list () L4 = List ()
# Create a list B with List A # The meaning of the following code is that for all elements in a, put in the new list B = [I * Ten for I in
A
# can also filter the contents of the original list of the disease into a new listing # such as the original list A, you need to have all the even number of a new list B a = [x for x in range (1, 35)] # Generate a list from 1 to 34 # to generate a new list of all even numbers in a (b b) = [M for m in a if m% 2 = =
0]
# list generation can be nested # by two List A, a = [I for I in range (1, 4)] # Generate List A b = [I for I in range] if I% 100 = =
0]
# list generation is nested, at this time equal to two for loop nesting c = [M + N for M in a for n
b
# The above code is equivalent to the following code for the M in
A:
For N in
B:
Print (M + N, end = ""
)
# Nested lists the city can also be used with conditional expressions C = [M + N for M in a for n in b if M + N < 250]
Tuple (tuple)
# Create an empty tuple t =
()
# Create a tuple with only one value T = (1
,)
T
= 1
,
# Create multiple values for tuple 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)
Properties of tuples
is a sequence table, ordered
Tuple data values can be accessed and cannot be modified
The tuple data can be any type
List all features, in addition to modifiable, tuples have
Functions of tuples
Len: Gets the length of the tuple
Max, min: Maximum minimum value
Count: Calculate the number of occurrences of the development data
Index: Find the indexed position of the element in the tuple
Set (SET)
# Definition of the collection s =
Set ()
# at this point, be sure to have a value in the curly braces, otherwise define a dict s = {1, 2, 3, 4, 5, 6, 7
}
# If you just define with braces, you define a dict type D = {}
Characteristics of the collection
Data is unordered within the collection, i.e. indexes and shards cannot be used
Collection internal data elements are unique and can be used to exclude duplicate data
Data within the collection, str, int, float, tuple, frozen set, etc., where only hashed data can be placed inside
Collection sequence Operations
# for loop s = {4, 5, "I"
}
For I in
S
Print (I, end = "")
)
# with tuples set traversal 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)
The connotation of the collection
# Common Set Connotation # The following collection automatically filters out duplicate elements after initialization s = {23, 223, 545, 3, 1, 2, 3, 4, 3, 2, 3, 1, 2, 4, 3
}
# Normal Set Connotation SS = {I for I in
S
# conditional Set Connotation SSS = {I for I in S if i% 2 = =
0}
# multi-loop Set connotation S1 = {1, 2, 3, 4
}
S2
= {"Just", "for", "fun"
}
S
= {m * n for m in S2-N in
S1}
S
= {m * n for m in S2-N in s1 if n = = 2}
Aggregate functions
Len, Max, Min
Set: Generate a Collection
Add: Adding elements to the collection
Clear
Copy
Remove: Remove the established value, directly change the original value, if the value to be deleted does not exist, an error
Discard: Removes the specified value from the collection, as with remove, but does not give an error if the stake is to be deleted
Pop randomly removes an element
Function
Intersection: Intersection
Difference: Difference Set
Union: and set
Issubset: Checks if a collection is another subset
Issuperset: Checks if a collection is another superset
Dict (dictionary)
No sequential combination of data, data appearing as key-value pairs
# Creation of Dictionary # Create empty dictionary 1 d =
{}
# Create an empty dictionary 2 d =
Dict ()
# Create a dictionary with values, each set of data separated by a colon, each pair of key-value pairs separated by commas d = {"One": 1, "one": 2, "three": 3
}
# Create a content dictionary with dict 1 d = dict ({"One": 1, "": 2, "three": 3
})
# Create a content dictionary with dict 2 # using the keyword parameter d = dict (one = 1, 2, three = 3
)
# d = dict (["One", 1), ("One", 2), ("Three", 3)])
The characteristics of a dictionary
A dictionary is a sequence type, but an unordered sequence, so there are no shards and indexes
Each of the data in the dictionary consists of a key-value pair, which is the KV pair
Key: Must be a hash value, such as Int,string,float,tuple, but list,set,dict not
Value: Any value
Common dictionary Operations
# Access Data D = {"One": 1, "one": 2, "three": 3
}
# Note Access format # inside the brackets is the key value print (d["one"
])
d[
"One"] = "eins" # Delete an action # using the Del operation del d[
]
# member detection, in, no in # member detection detected is key content d = {"One": 1, "one": 2, "three": 3
}
If 2 in
D:
Print ("Value"
)
If "both" in
D:
Print ("Key"
)
if ("both", 2) in
D:
Print ("KV"
)
# Press Key to use for loop D = {"One": 1, "one": 2, "three": 3
}
# Use a For loop to access the for-K in directly by the key value
D:
Print
(k, D[k])
# The above code can be rewritten as follows for the K in
D.keys ():
Print
(k, D[k])
# access only the value of the dictionary for the V in
D.values ():
Print
(v)
# Note the following special usages for the k,v in
D.items ():
Print (k, '--', V)
Dictionary-generated
D = {"One": 1, "one": 2, "three": 3
}
# General Dictionary-generated DD = {k:v for k,v in
D.items ()}
# conditional Dictionary Generation DD = {k:v for k,v in D.items () if v% 2 = = 0}
Dictionary-related functions
Len, Max, Min, dict
STR (dictionary): Returns the string format of a dictionary
Clear: Empty the dictionary
Items: Returns the tuple format of the dictionary's key-value pairs
Keys: Returns a structure that consists of a dictionary key
Values: In the same vein, an iterative structure
Get: Returns the corresponding value according to the key set
D = {"One": 1, "one": 2, "three": 3
}
Print (D.get ("on333"
))
# get default value is None, can set print (D.get ("one", 100))
Fromkeys: Uses the specified sequence as the key, using a value as the value of all keys of the dictionary
L = ["Eins", "Zwei", "Drei"
]
# note Fromkeys two parameters of type # Note Fromkeys's call body D = Dict.fromkeys (L, "oops")
Iv. expressions
Operator
Arithmetic operators
Comparison operators
Assignment operators
+ = (-=,x=,/=,//=,%=, **=)
logical operators
Member Operation symbols
Identity operations
Precedence of Operators
Parentheses have the highest precedence
* * Index (highest priority)
~ +-Rollover by bit
,
Unary Plus and minus (the last two methods are called [email protected] and [email protected])
*/%//multiply, divide, modulo and divide
+-Addition Subtraction
\>> << Right SHIFT, left shift operator
& Bit ' and '
^ | Bitwise operators
<
= < > > =
Comparison operators
<>
== ! =
equals operator
= % = / = // = - = + = * = ** =
Assignment operators
Is isn't identity operator
In no in member operator
Not OR and logical operators
V. Structure of the procedure
Order
Branch
Multi-Channel Branch
If
Conditional expression:
Statement 1
.
Elif
Conditional expression:
Statement 1
Elif
Conditional expression:
Statement 1
..
Else
:
Statement 1
.
Cycle
For loop
For variable in
Sequence:
Statement 1
Statement 2
Range
For-else
While loop
While
Conditional expression:
Statement block
# Another way of expression while
Conditional expression:
Statement Block 1
Else
:
Statement Block 2
Break,continue,pass of the Cycle
Break: Unconditionally end the entire cycle, referred to as circular death
Continue: Unconditional end of this cycle, new into the next round cycle
Pass: Indicates skip, usually used for positioning, no skip function
Vi. functions
Parameters and return values for functions
# define a function to print a row of 99 multiplication table def
PrintLine (ROW):
For Col in range (1, row + 1
):
# Print function The default task prints and wraps the print (row * col, end = ""
)
Print (""
)
# 99 Multiplication Table # version 2.0 for row in range (1, 10
):
PrintLine (Row)
Detailed parameters
Parameter classification
General parameters
Default parameters
Keyword parameters
Collect parameters
General parameters
See the example above
Define the variable name directly at the time of definition
Put a variable or value directly into the specified position when calling
def function name (parameter 1, parameter 2,
.):
function body
# Call the function name (value1, value2,
.)
Default parameters
Formal parameters with default values
When called, the default value is used if no value is assigned to the corresponding parameter
def func_name (p1 = v1, p2 = v2
.):
Func_block
# call 1
Func_name ()
# call 2 value1 = value2 = Func_name (value1,value2)
Keyword parameters
def func (p1 = v1, p2 = v2
..):
Func_body
# Call Function: Func (p1 = value1, p2 = value2
.)
Collect parameters
Put in a specific data structure the parameters that have no location and cannot be defined with the parameter position.
def func (*
args):
Func_body
# access to args by list usage gets the parameters passed in # Call: Func (P1, p2, p3,
..)
Collection of parameter mixed call order issues
Collect parameters, keyword parameters, common parameters can be mixed use
The rule of use is that common parameters and keyword parameters take precedence
When defining general parameters, keyword parameters, collect parameter tuple, collect parameters Dict
return value
The difference between a function and a procedure
You need to return the content with return,
If no return is returned, none is returned by default
Recursive functions
Python has a limit on recursion depth, exceeding the limit error
# Fibonacci Number # A list of numbers, the first value is 1, the second is also 1, and the value of each number is equal to the value of the first two digits and the # mathematical formula is: f (1) = 1, f (2) = 1, f (n) = f (n-1) + f (n-2) # for example: , 2,3,5,8,13 ..... # n denotes the value of the Fibonacci sequence of the nth number of digits 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))
N=1: Move a plate on a to C directly, a->c
n=2:
N=3:
n = N:
Put the small plate from A to B, A->b.
Put the big plate from A to C, A->c.
Put the small plate from B to C, B->c.
Put two plates on a, move through C to B, call recursive implementation
Move the largest remaining plate on a to C, A->c.
Put two plates on B, move to c with the aid of a, call recursion
N-1 a plate on a, with the help of C, move to B, call recursion
Put the biggest plate on a, and the only one, move to C, a->c
N-1 a plate on B, move to c with the aid of a, call recursion
Move one plate at a time
At any time the big plates are down, the small plates are on top.
Def
Hano (n, a, B, c):
‘‘‘
Recursive implementation of Hanoi
N: Representing several plates
A: stands for the first tower, the beginning of the tower
B: A tower representing the second tower, the middle transition
C: On behalf of the third tower, the target tower
"If n = = 1
:
Print (A, "--"
C
Return
None
‘‘‘
if n = = 2:
Print (A, "--", b)
Print (A, "--", c)
Print (b, "--", c)
Return None
"# N-1 a plate, from tower A to the tower C, move to Tower B Hano (n-1
, A, C, b)
Print (A, "--"
C
# N-1 a plate, from Tower B, with a tower, move to Tower C 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)
find function Help documentation
Use the Help function
Help (print)
Using __doc__
Def
Stu (name, age):
‘‘‘
This is the textual content of the document
:p Aram Name: Indicates the student's name
:p Aram Age: Indicates the student's ages
: return: This function has no value returned
"Pass Print
(Help (Stu))
Print ("*" * 20
)
Print (stu. __doc__)
Vii. Scope of variables
Category: By scope
LEGB Principles
L (local) local scope
E (enclosing function locale) outer nested functions Scope
The module scope where the G (Global module) function is defined
B (Buildin): Python built-in scope for magic
Promote local variables to global variables (using global)
Def
Fun ():
Global
B1
B1
= Print
(B1)
Print ("I AM in Fun"
)
# B2 's scope is fun b2 = Print
(B2)
Fun ()
Print (B1)
Globals, locals function
Local and global variables can be displayed through globals and locals
# Globals and locals # 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, returning the result of the execution of the expression
Eval (string_code, globals = none, locals = none)
EXEC () function
Similar to the Eval function, but does not return results
EXEC (String_code, globals = none, locals = none)
This article is dedicated to the small whites who are still on the basis of Python 0! It's not a problem to make sure you get started