Hello, I'm spicy.
Today, I'll bring you a summary of the basic knowledge of Python. It's no exaggeration to say that I didn't finish it in a week. This is the first play. If you like to remember three in a row, I'll quickly update the next play and strive to finish this series. I hope you can support me.
catalogue
notes
-
Classification of notes
-
Single line: # comment content, shortcut key ctrl+/
-
Multiline: '' comment content '' or ''comment content' '
-
-
The interpreter does not execute annotation content
Comments fall into two categories: = = single line comments = = and = = multi line comments = =.
-
Single-Line Comments
Only one line can be annotated. The syntax is as follows:
# Note Content
-
multiline comment
Multiple lines of content can be annotated. It is generally used to annotate a piece of code. The syntax is as follows:
""" First line comment Comment on the second line Comment on the third line """ ''' Note 1 Note 2 Note 3 '''
Shortcut key: = = ctrl +/==
variable
A variable is just the name of the memory address where the current data is stored.
identifier
The identifier naming rule is a unified specification for defining various names in Python, as follows:
-
It consists of numbers, letters and underscores
-
Cannot start with a number
-
Built in keywords cannot be used
-
Strictly case sensitive
Naming habits
-
See the name and know the meaning.
-
Big hump: that is, the first letter of each word is capitalized, such as MyName.
-
Small hump: words after the second (inclusive) are capitalized, such as myName.
-
Underline: for example: my_name.
Understanding data types
Method for detecting data type: type()
a = 1 print(type(a)) # < class' Int '> -- integer b = 1.1 print(type(b)) # < class' float '> -- floating point type c = True print(type(c)) # < class' bool '> Boolean d = '12345' print(type(d)) # < class' STR '> string e = [10, 20, 30] print(type(e)) # < class' list '> -- List f = (10, 20, 30) print(type(f)) # < class' tuple '> -- tuple h = {10, 20, 30} print(type(h)) # < class' set '> -- Set g = {'name': 'TOM', 'age': 20} print(type(g)) # < class' dict '> dictionary
Output
Function: the program outputs content to the user
print('hello Python') age = 19 print(age) # Demand: output "my age is 19 this year"
Format symbol
Format symbol | transformation |
---|---|
==%s== | character string |
==%d== | Signed decimal integer |
==%f== | Floating point number |
%c | character |
%u | Unsigned decimal integer |
%o | Octal integer |
%x | Hexadecimal integer (lowercase ox) |
%X | Hexadecimal integer (uppercase OX) |
%e | Scientific counting (lowercase 'e') |
%E | Scientific counting (capital 'E') |
%g | %Abbreviations for f and% e |
%G | %Abbreviations for f and% E |
Escape character
-
\n: Line feed.
-
\t: Tab, a tab key (4 spaces) distance.
Terminator
print('Output content', end="\n")
In Python, print(), by default, comes with the line break terminator end="\n", so every two prints will be displayed in line break directly. Users can change the terminator as needed.
Input
In Python, the function of a program to receive user input data is input.
input("Prompt information")
Input characteristics
-
When the program is executed to input, wait for user input, and continue to execute downward after input is completed.
-
In Python, after receiving user input, input is generally stored in variables for easy use.
-
In Python, input treats any received user input data as a string.
shifting clause
function | explain |
---|---|
==int(x [,base ])== | Convert x to an integer |
==float(x )== | Convert x to a floating point number |
complex(real [,imag ]) | Create a complex number. Real is the real part and imag is the imaginary part |
==str(x )== | Convert object x to string |
repr(x ) | Converts object x to an expression string |
==eval(str )== | Used to evaluate a valid Python expression in a string and return an object |
==tuple(s )== | Convert sequence s to a tuple |
==list(s )== | Convert sequence s to a list |
chr(x ) | Converts an integer to a Unicode character |
ord(x ) | Converts a character to its ASCII integer value |
hex(x ) | Converts an integer to a hexadecimal string |
oct(x ) | Converts an integer to an octal string |
bin(x ) | Converts an integer to a binary string |
Common functions for converting data types
-
int()
-
float()
-
str()
-
list()
-
tuple()
-
eval()
operator
Arithmetic operator
operator | describe | example |
---|---|---|
+ | plus | The output result of 1 + 1 is 2 |
- | reduce | The output result of 1-1 is 0 |
* | ride | 2 * 2 the output result is 4 |
/ | except | The output of 10 / 2 is 5 |
// | to be divisible by | 9 / / 4 the output is 2 |
% | Surplus | 9% 4 output is 1 |
** | index | 2 * * 4 the output result is 16, that is, 2 * 2 * 2 * 2 |
() | parentheses | Parentheses are used to improve the operation priority, that is, (1 + 2) * 3, and the output result is 9 |
Assignment Operators
operator | describe | example |
---|---|---|
= | assignment | Assign the result to the right of = to the variable to the left of the equal sign |
compound assignment operators
operator | describe | example |
---|---|---|
+= | Additive assignment operator | c += a is equivalent to c = c + a |
-= | Subtraction assignment operator | c -= a is equivalent to c = c- a |
*= | Multiplication assignment operator | c *= a is equivalent to c = c * a |
/= | Division assignment operator | c /= a is equivalent to c = c / a |
//= | Integer division assignment operator | c //= a is equivalent to c = c // a |
%= | Remainder assignment operator | C% = a is equivalent to C = C% a |
**= | Power assignment operator | c ** = a is equivalent to c = c ** a |
Comparison operator
operator | describe | example |
---|---|---|
== | Judge equality. If the results of two operands are equal, the condition result is true; otherwise, the condition result is false | If a = 3 and B = 3, then (a == b) is True |
!= | Not equal to. If the results of two operands are not equal, the condition is true; otherwise, the condition is false | If a = 3 and B = 3, then (a == b) is True. If a = 1 and B = 3, then (a! = b) is True |
> | Whether the result of the operand on the left side of the operator is greater than the result of the operand on the right side. If greater than, the condition is true; otherwise, it is false | If a = 7 and B = 3, then (a > b) is True |
< | Whether the operand result on the left side of the operator is less than the operand result on the right side. If less than, the condition is true; otherwise, it is false | If a = 7 and B = 3, then (a < b) is False |
>= | Whether the operand result on the left side of the operator is greater than or equal to the operand result on the right side. If greater than, the condition is true; otherwise, it is false | If a=7,b=3, (a < b) is False, if a=3,b=3, (a > = b) is True |
<= | Whether the operand result on the left side of the operator is less than or equal to the operand result on the right side. If less than, the condition is true; otherwise, it is false | If a = 3 and B = 3, then (a < = b) is True |
Logical operator
operator | Logical expression | describe | example |
---|---|---|---|
and | x and y | Boolean and: x and y return False if x is False, otherwise it returns the value of y. | True and False, return False. |
or | x or y | Boolean or: if x is True, it returns True, otherwise it returns the value of y. | False or True, returns True. |
not | not x | Boolean not: Returns False if x is True. If x is False, it returns True. | not True returns False, not False returns True |
Conditional statement
Suppose a scenario:
In fact, the so-called judgment here is a conditional statement, that is, if the condition is true, some codes will be executed, and if the condition is not true, these codes will not be executed.
grammar
if condition: Code 1 for conditional execution Code 2 for conditional execution ......
if...else...
Function: if the condition is true, execute the code below if; If the condition does not hold, execute the code below else.
if condition: Code 1 for conditional execution Code 2 for conditional execution ...... else: Code 1 executed when the condition is not true Code 2 executed when the condition is not true ......
Example: seniority judgment
age = int(input('Please enter your age:')) if age < 18: print(f'What is your age{age},One for child labor') elif (age >= 18) and (age <= 60): print(f'What is your age{age},Legal length of service') elif age > 60: print(f'What is your age{age},Can retire')
Expansion: age > = 18 and age < = 60 can be simplified to 18 < = age < = 60.
if nesting
if Condition 1: Code executed when condition 1 is true Code executed when condition 1 is true if Condition 2: Code executed when condition 2 is true Code executed when condition 2 is true
Application: guessing game
Demand analysis:
-
Characters participating in the game
-
game player
-
Manual punch
-
-
computer
-
Random punch
-
-
-
Judge whether to win or lose
-
Player wins
game player computer stone scissors scissors cloth cloth stone -
it ends in a draw
-
Player punches are the same as computer punches
-
-
Computer wins
-
Random method:
-
Export random module
-
random. RandInt (start, end)
""" Tip: 0-Stone, 1-Scissors, 2-cloth 1. punches Player input punch Computer random punch 2. Judge whether to win or lose Player wins it ends in a draw Computer wins """ # Import random module import random # Calculate the random number of the fist produced by the computer computer = random.randint(0, 2) print(computer) player = int(input('Please punch: 0-Stone, 1-Scissors, 2-Cloth:')) # Player wins p0:c1 or p1:c2 or p2:c0 if (player == 0 and computer == 1) or (player == 1 and computer == 2) or (player == 2 and computer == 0): print('Player wins') # Draw: player = = computer elif player == computer: print('it ends in a draw') else: print('Computer wins')
ternary operator
Ternary operators are also called ternary operators.
The syntax is as follows:
Value 1 if condition else Value 2
Quick experience:
a = 1 b = 2 c = a if a > b else b print(c)
Circulation
The function of loop: make the code execute repeatedly more efficiently.
Classification of cycles
In Python, loops are divided into while and for, and the final implementation effect is the same.
Syntax of while
while condition: Code 1 repeatedly executed when the condition is true Code 2 executed repeatedly when the condition is true ......
Application of while
Calculate 1-100 cumulative sum
Analysis: cumulative sum of 1-100, i.e. 1 + 2 + 3 + 4 +, That is, the addition result of the first two numbers + the next number (the previous number + 1).
i = 1 result = 0 while i <= 100: result += i i += 1 # Output 5050 print(result)
Note: in order to verify the accuracy of the program, you can change the small value first, and then change it to 1-100 for accumulation after the verification result is correct.
Calculate 1-100 even cumulative sum
Analysis: even sum of 1-100, i.e. 2 + 4 + 6 + 8, The way to get an even number is as follows:
-
An even number is a number with the remainder of and 2 as 0. You can add a conditional statement to judge whether it is an even number. If it is an even number, it will be accumulated
-
The initial value is 0 / 2, and the counter accumulates 2 each time
Method 1: conditional judgment and 2 remainder are accumulated
# Method 1: condition judgment and 2. If the remainder is 0, it will be accumulated i = 1 result = 0 while i <= 100: if i % 2 == 0: result += i i += 1 # Output 2550 print(result)
Method 2: counter control
# Method 2: the counter control increment is 2 i = 0 result = 0 while i <= 100: result += i i += 2 # Output 2550 print(result)
while loop nesting
Synopsis of the story: one day, my girlfriend was angry again. Punishment: say "daughter-in-law, I'm wrong" three times. Is this procedure a cycle? But if your girlfriend says: I have to brush today's dinner bowl, how does this program write?
while condition: print('Daughter in law, I was wrong') print('Brush the dinner bowl')
But if the girlfriend is still angry and the punishment should be implemented for three consecutive days, how to write the procedure?
while condition: while condition: print('Daughter in law, I was wrong') print('Brush the dinner bowl')
while Condition 1: Code executed when condition 1 is true ...... while Condition 2: Code executed when condition 2 is true ......
Summary: the so-called while loop nesting means that a while is nested inside a while. Each while is the same as the previous basic syntax.
for loop
grammar
for Temporary variable in sequence: Repeated code 1 Repeated code 2 ......
else
The loop can be used with else. The code indented below else refers to = = the code to be executed after the loop ends normally = =.
while...else
Demand: if your girlfriend is angry, you should be punished: say "daughter-in-law, I'm wrong" five times in a row. If the apology is completed normally, your girlfriend will forgive me. How to write this program?
i = 1 while i <= 5: print('Daughter in law, I was wrong') i += 1 print('My daughter-in-law forgave me...')
Think: can this print be executed without a loop?
grammar
while condition: Code executed repeatedly when the condition is true else: Code to be executed after the loop ends normally
Example
i = 1 while i <= 5: print('Daughter in law, I was wrong') i += 1 else: print('My daughter-in-law forgives me. I'm so happy, ha ha')
for...else
grammar
for Temporary variable in sequence: Repeatedly executed code ... else: Code to be executed after the loop ends normally
Else refers to the code to be executed after the normal end of the loop, that is, if the loop is terminated by break, the code indented below else will not be executed.
Example
str1 = 'itheima' for i in str1: print(i) else: print('Code executed after the loop ends normally')
summary
-
The function of loop: control the repeated execution of code
-
while syntax
while condition: Code 1 repeatedly executed when the condition is true Code 2 executed repeatedly when the condition is true ......
-
while loop nesting syntax
while Condition 1: Code executed when condition 1 is true ...... while Condition 2: Code executed when condition 2 is true ......
-
for loop syntax
for Temporary variable in sequence: Repeated code 1 Repeated code 2 ......
-
break exits the entire loop
-
Continue exit this loop and continue to execute the next repeated code
-
else
-
Both while and for can be used with else
-
Meaning of the code indented below else: the code executed when the loop ends normally
-
Breaking the loop does not execute the code indented below else
-
continue executes the indented code below else by exiting the loop
-
character string
String is the most commonly used data type in Python. We usually use quotation marks to create strings. Creating a string is as simple as assigning a value to a variable.
a = 'hello world' b = "abcdefg" print(type(a)) print(type(b))
Note: the console displays < class' STR '> as the result, that is, the data type is str (string).
String output
print('hello world') name = 'Tom' print('My name is%s' % name) print(f'My name is{name}')
String input
In Python, input() is used to receive user input.
-
code
name = input('Please enter your name:') print(f'The name you entered is{name}') print(type(name)) password = input('Please enter your password:') print(f'The password you entered is{password}') print(type(password))
section
Slicing refers to the operation of intercepting part of the operated object. String, list and tuple all support slicing.
grammar
sequence[Start position subscript:End position subscript:step]
be careful
-
It does not contain the data corresponding to the end position subscript, either positive or negative integers;
-
Step size is the selection interval, which can be positive or negative integers. The default step size is 1.
experience
name = "abcdefg" print(name[2:5:1]) # cde print(name[2:5]) # cde print(name[:5]) # abcde print(name[1:]) # bcdefg print(name[:]) # abcdefg print(name[::2]) # aceg print(name[:-1]) # abcdef, negative 1 indicates the penultimate data print(name[-4:-1]) # def print(name[::-1]) # gfedcba
modify
Modifying a string means modifying the data in the string in the form of a function.
-
replace(): replace
-
grammar
String sequence.replace(Old substring, New substring, Replacement times)
Note: replacement times: if the occurrence times of the substring are found, the replacement times are the occurrence times of the substring.
-
Quick experience
mystr = "hello world and itcast and itheima and Python" # Result: hello world he itcast he itheima he Python print(mystr.replace('and', 'he')) # Result: hello world he itcast he itheima he Python print(mystr.replace('and', 'he', 10)) # Result: hello world and itcast and itheima and Python print(mystr)
Note: data can be divided into = = variable type = = and = = immutable type = = according to whether it can be modified directly. When modifying string type data, the original string cannot be changed. It belongs to the type that cannot modify data directly, that is, immutable type.
-
split(): splits the string according to the specified character.
-
grammar
String sequence.split(Split character, num)
Note: num indicates the number of split characters. The number of data to be returned is num+1.
-
Quick experience
mystr = "hello world and itcast and itheima and Python" # Result: ['Hello world ',' itcast ',' itheima ',' Python '] print(mystr.split('and')) # Result: ['Hello world ',' itcast ',' itheima and Python '] print(mystr.split('and', 2)) # Results: ['Hello ',' world ',' and ',' itcast ',' and ',' itheima ',' and ',' Python '] print(mystr.split(' ')) # Results: ['Hello ',' world ',' itcast and itheima and Python '] print(mystr.split(' ', 2))
Note: if the split character is a substring in the original string, the substring will be lost after splitting.
-
join(): combine strings with one character or substring, that is, combine multiple strings into a new string.
-
grammar
Character or substring.join(A sequence of multiple strings)
-
Quick experience
list1 = ['chuan', 'zhi', 'bo', 'ke'] t1 = ('aa', 'b', 'cc', 'ddd') # Result: chuan_zhi_bo_ke print('_'.join(list1)) # Result: AA b... cc... ddd print('...'.join(t1))
-
capitalize(): converts the first character of a string to uppercase.
mystr = "hello world and itcast and itheima and Python" # Result: Hello world and itcast and itheima and python print(mystr.capitalize())
Note: after the capitalization () function is converted, only the first character of the string is capitalized, and all other characters are lowercase.
-
title(): converts the first letter of each word in the string to uppercase.
mystr = "hello world and itcast and itheima and Python" # Result: Hello World And Itcast And Itheima And Python print(mystr.title())
-
lower(): converts uppercase to lowercase in a string.
mystr = "hello world and itcast and itheima and Python" # Result: hello world and itcast and itheima and python print(mystr.lower())
-
upper(): converts the small case of the string to uppercase.
mystr = "hello world and itcast and itheima and Python" # Result: HELLO WORLD AND ITCAST AND ITHEIMA AND PYTHON print(mystr.upper())
judge
The so-called judgment is to judge whether it is True or False. The returned result is Boolean data type: True or False.
-
Startswitch(): check whether the string starts with the specified substring. If yes, it returns True; otherwise, it returns False. If the start and end position subscripts are set, check within the specified range.
-
grammar
String sequence.startswith(Substring, Start position subscript, End position subscript)
-
Quick experience
mystr = "hello world and itcast and itheima and Python " # Result: True print(mystr.startswith('hello')) # Result False print(mystr.startswith('hello', 5, 20))
-
Endswitch():: check whether the string ends with the specified substring. If yes, it returns True; otherwise, it returns False. If the start and end position subscripts are set, check within the specified range.
-
grammar
String sequence.endswith(Substring, Start position subscript, End position subscript)
-
Quick experience
mystr = "hello world and itcast and itheima and Python" # Result: True print(mystr.endswith('Python')) # Result: False print(mystr.endswith('python')) # Result: False print(mystr.endswith('Python', 2, 20))
-
isalpha(): returns True if the string has at least one character and all characters are letters; otherwise, returns False.
mystr1 = 'hello' mystr2 = 'hello12345' # Result: True print(mystr1.isalpha()) # Result: False print(mystr2.isalpha())
-
isdigit(): returns True if the string contains only numbers; otherwise, returns False.
mystr1 = 'aaa12345' mystr2 = '12345' # Result: False print(mystr1.isdigit()) # Result: False print(mystr2.isdigit())
-
isalnum(): returns True if the string has at least one character and all characters are letters or numbers; otherwise, returns False.
mystr1 = 'aaa12345' mystr2 = '12345-' # Result: True print(mystr1.isalnum()) # Result: False print(mystr2.isalnum())
-
isspace(): returns True if the string contains only white space; otherwise, returns False.
mystr1 = '1 2 3 4 5' mystr2 = ' ' # Result: False print(mystr1.isspace()) # Result: True print(mystr2.isspace())
summary
-
subscript
-
The number assigned by the computer to each element in the data sequence starting from 0
-
-
section
Sequence name[Start position subscript:End position subscript:step]
-
Common operation methods
-
find()
-
index()
-
list
Think: how does a person's name (TOM) write a stored program?
A: variables.
Thinking: if there are 100 students in a class and everyone's name should be stored, how should we write the program? Declare 100 variables?
A: just list. The list can store multiple data at one time.
Format of list
[Data 1, Data 2, Data 3, Data 4......]
The list can store multiple data at one time and can be of different data types.
Common operations of list
The function of list is to store multiple data at one time. Programmers can add, delete, modify and query these data.
lookup
subscript
name_list = ['Tom', 'Lily', 'Rose'] print(name_list[0]) # Tom print(name_list[1]) # Lily print(name_list[2]) # Rose
function
-
index(): returns the subscript of the specified data location.
-
grammar
List sequence.index(data, Start position subscript, End position subscript)
-
Quick experience
name_list = ['Tom', 'Lily', 'Rose'] print(name_list.index('Lily', 0, 2)) # 1
Note: if the searched data does not exist, an error will be reported.
-
count(): counts the number of times the specified data appears in the current list.
name_list = ['Tom', 'Lily', 'Rose'] print(name_list.count('Lily')) # 1
-
len(): access list length, that is, the number of data in the list.
name_list = ['Tom', 'Lily', 'Rose'] print(len(name_list)) # 3
Judge whether it exists
-
In: determines whether the specified data is in a list sequence. If yes, it returns True; otherwise, it returns False
name_list = ['Tom', 'Lily', 'Rose'] # Result: True print('Lily' in name_list) # Result: False print('Lilys' in name_list)
-
Not in: judge whether the specified data is not in a list sequence. If not, return True; otherwise, return False
name_list = ['Tom', 'Lily', 'Rose'] # Result: False print('Lily' not in name_list) # Result: True print('Lilys' not in name_list)
-
Experience case
Requirement: check whether the name entered by the user already exists.
name_list = ['Tom', 'Lily', 'Rose'] name = input('Please enter the name you want to search for:') if name in name_list: print(f'The name you entered is{name}, The name already exists') else: print(f'The name you entered is{name}, name does not exist')
increase
Function: add specified data to the list.
-
append(): append data to the end of the list.
-
grammar
List sequence.append(data)
-
experience
name_list = ['Tom', 'Lily', 'Rose'] name_list.append('xiaoming') # Results: ['Tom ',' Lily ',' Rose ',' Xiaoming '] print(name_list)
When adding data to the list, the specified data is directly added to the original list, that is, the original list is modified, so the list is variable type data.
-
Attention
If the data appended by append() is a sequence, the entire sequence is appended to the list
name_list = ['Tom', 'Lily', 'Rose'] name_list.append(['xiaoming', 'xiaohong']) # Results: ['Tom ',' Lily ',' Rose ',' Xiaoming ',' Xiaohong ']] print(name_list)
-
extend(): append data at the end of the list. If the data is a sequence, the data of this sequence will be added to the list one by one.
-
grammar
List sequence.extend(data)
-
Quick experience
2.1 single data
name_list = ['Tom', 'Lily', 'Rose'] name_list.extend('xiaoming') # Results: ['Tom ',' Lily ',' Rose ',' x ',' I ',' a ',' o ','m', 'I', 'n', 'g'] print(name_list)
2.2 sequence data
name_list = ['Tom', 'Lily', 'Rose'] name_list.extend(['xiaoming', 'xiaohong']) # Results: ['Tom ',' Lily ',' Rose ',' Xiaoming ',' Xiaohong '] print(name_list)
-
insert(): add data at the specified location.
-
grammar
List sequence.insert(Position subscript, data)
-
Quick experience
name_list = ['Tom', 'Lily', 'Rose'] name_list.insert(1, 'xiaoming') # Results: ['Tom', 'xiaoming', 'Lily', 'Rose'] print(name_list)
delete
-
del
-
grammar
del target
Quick experience
Delete list
name_list = ['Tom', 'Lily', 'Rose'] # Result: error message: name 'name_list' is not defined del name_list print(name_list)
Delete specified data
name_list = ['Tom', 'Lily', 'Rose'] del name_list[0] # Result: ['lily ',' Rose '] print(name_list)
-
pop(): delete the data of the specified subscript (the last by default) and return the data.
-
grammar
List sequence.pop(subscript)
-
Quick experience
name_list = ['Tom', 'Lily', 'Rose'] del_name = name_list.pop(1) # Result: Lily print(del_name) # Result: [Tom ',' Rose '] print(name_list)
-
remove(): removes the first match of a data in the list.
-
grammar
List sequence.remove(data)
-
Quick experience
name_list = ['Tom', 'Lily', 'Rose'] name_list.remove('Rose') # Result: [Tom ',' Lily '] print(name_list)
-
clear(): clear the list
name_list = ['Tom', 'Lily', 'Rose'] name_list.clear() print(name_list) # Result: []
modify
-
Modify specified subscript data
name_list = ['Tom', 'Lily', 'Rose'] name_list[0] = 'aaa' # Result: ['aaa ',' Lily ',' Rose '] print(name_list)
-
Reverse: reverse()
num_list = [1, 5, 2, 3, 6, 8] num_list.reverse() # Result: [8, 6, 3, 2, 5, 1] print(num_list)
-
Sort: sort()
-
grammar
List sequence.sort( key=None, reverse=False)
Note: reverse indicates the collation, reverse = True descending, reverse = False ascending (default)
-
Quick experience
num_list = [1, 5, 2, 3, 6, 8] num_list.sort() # Results: [1, 2, 3, 5, 6, 8] print(num_list)
copy
Functions: copy()
name_list = ['Tom', 'Lily', 'Rose'] name_li2 = name_list.copy() # Result: ['Tom ',' Lily ',' Rose '] print(name_li2)
List nesting
The so-called list nesting means that a list contains other sub lists.
Application scenario: the names of students in class 1, 2 and 3 should be stored, and the names of students in each class are in a list.
name_list = [['Xiao Ming', 'Xiao Hong', 'Little green'], ['Tom', 'Lily', 'Rose'], ['Zhang San', 'Li Si', 'Wang Wu']]
Thinking: how to find the data "Li Si"?
# Step 1: click the subscript to find the list where Li Si is located print(name_list[2]) # Step 2: from the list where Li Si is located, click the subscript to find the data Li Si print(name_list[2][1])
summary
-
Format of list
[Data 1, Data 2, Data 3]
-
Common operation methods
-
index()
-
len()
-
append()
-
pop()
-
remove()
-
-
List nesting
name_list = [['Xiao Ming', 'Xiao Hong', 'Little green'], ['Tom', 'Lily', 'Rose'], ['Zhang San', 'Li Si', 'Wang Wu']] name_list[2][1]
tuple
Thinking: if you want to store multiple data, but these data cannot be modified, what should you do?
A: list? A list can store multiple data at once, but the data in the list can be changed.
num_list = [10, 20, 30] num_list[0] = 100
==A tuple can store multiple data, and the data in the tuple cannot be modified==
Define tuple
Tuple features: define tuples, use = = parentheses = =, and = = commas = = to separate various data. Data can be of different data types.
# Multiple data tuples t1 = (10, 20, 30) # Single data tuple t2 = (10,)
Note: if the defined tuple has only one data, add a comma after the data, otherwise the data type is the only data type of the data
t2 = (10,) print(type(t2)) # tuple t3 = (20) print(type(t3)) # int t4 = ('hello') print(type(t4)) # str
Common operations of tuples
Tuple data does not support modification, but only search, as follows:
-
Find data by subscript
tuple1 = ('aa', 'bb', 'cc', 'bb') print(tuple1[0]) # aa
-
index(): find a data. If the data exists, the corresponding subscript will be returned. Otherwise, an error will be reported. The syntax is the same as the index method of list and string.
tuple1 = ('aa', 'bb', 'cc', 'bb') print(tuple1.index('aa')) # 0
-
count(): counts the number of times a data appears in the current tuple.
tuple1 = ('aa', 'bb', 'cc', 'bb') print(tuple1.count('bb')) # 2
-
len(): counts the number of data in tuples.
tuple1 = ('aa', 'bb', 'cc', 'bb') print(len(tuple1)) # 4
Note: if the direct data in the tuple is modified, an error will be reported immediately
tuple1 = ('aa', 'bb', 'cc', 'bb') tuple1[0] = 'aaa'
However, if there is a list in the tuple, modifying the data in the list is supported, so consciousness is very important.
tuple2 = (10, 20, ['aa', 'bb', 'cc'], 50, 30) print(tuple2[2]) # Access to list # Results: (10, 20, ['aaaaa ',' BB ',' CC '], 50, 30) tuple2[2][0] = 'aaaaa' print(tuple2)
summary
-
Define tuple
t1 = (10, 20, 30) t2 = (10,)
-
Common operation methods
-
index()
-
len()
-
Dictionaries
Thinking 1: if there are multiple data, such as' Tom ',' male ', 20, how to store them quickly?
Answer: List
list1 = ['Tom', 'male', 20]
Thinking 2: how to find the data 'Tom'?
A: just find the data with subscript 0.
list1[0]
Thinking 3: if the data order changes in the future, as shown below, can the data 'Tom' be accessed with list1[0]?.
list1 = ['male', 20, 'Tom']
A: No, the subscript of the data 'Tom' is 2 at this time.
Thinking 4: when the data order changes, the subscript of each data will also change. How to ensure that the same standard can be used to find data before and after the data order changes?
A: dictionary. The data in the dictionary appears in the form of = = key value pair = =. The dictionary data has nothing to do with the data order, that is, the dictionary does not support subscripts. No matter how the data changes in the later stage, you only need to find the data according to the name of the corresponding key.
Syntax for creating Dictionaries
Dictionary features:
-
The symbol is = = braces==
-
The data is in the form of = = key value pair = =
-
Each key value pair is separated by = = comma = =
# There is a data dictionary dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} # Empty dictionary dict2 = {} dict3 = dict()
Note: generally, the key in front of the colon is called key, abbreviated as k; The value following the colon is v for short.
Common operations of dictionary
increase
Writing method: = = dictionary sequence [key] = value==
Note: if the key exists, modify the value corresponding to the key; If the key does not exist, add this key value pair.
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} dict1['name'] = 'Rose' # Results: {name ':'rose', 'age': 20, 'gender':'male '} print(dict1) dict1['id'] = 110 # {'name': 'Rose', 'age': 20, 'gender': 'male', 'id': 110} print(dict1)
Note: the dictionary is of variable type.
Delete
-
del() / del: delete the dictionary or delete the specified key value pair in the dictionary.
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} del dict1['gender'] # Result: {name ':'Tom','age ': 20} print(dict1)
-
clear(): clear the dictionary
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} dict1.clear() print(dict1) # {}
change
Writing method: = = dictionary sequence [key] = value==
Note: if the key exists, modify the value corresponding to the key; If the key does not exist, add this key value pair.
check
Value lookup
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} print(dict1['name']) # Tom print(dict1['id']) # report errors
If the key currently searched exists, the corresponding value is returned; Otherwise, an error is reported.
get()
-
grammar
Dictionary sequence.get(key, Default value)
Note: if the key currently searched does not exist, the second parameter (default value) is returned. If the second parameter is omitted, None is returned.
-
Quick experience
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} print(dict1.get('name')) # Tom print(dict1.get('id', 110)) # 110 print(dict1.get('id')) # None
keys()
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} print(dict1.keys()) # dict_keys(['name', 'age', 'gender'])
values()
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} print(dict1.values()) # dict_values(['Tom', 20,' male '])
items()
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'} print(dict1.items()) # dict_ Items ([('name ',' Tom '), ('age', 20), ('gender ',' male ')])
summary
-
Definition dictionary
dict1 = {'name': 'Python', 'age': 30} dict2 = {} dict3 = dict()
-
Common operation
-
Add / change
-
Dictionary sequence[key] = value
-
lookup
-
Dictionary sequence [key]
-
keys()
-
values()
-
items()
-
aggregate
Create collection
You use {} or set() to create a collection, but you can only use set() if you want to create an empty collection, because {} is used to create an empty dictionary.
s1 = {10, 20, 30, 40, 50} print(s1) s2 = {10, 30, 20, 10, 30, 40, 30, 50} print(s2) s3 = set('abcdefg') print(s3) s4 = set() print(type(s4)) # set s5 = {} print(type(s5)) # dict
characteristic:
-
Set can remove duplicate data;
-
The set data is out of order, so subscripts are not supported
Collection common operation methods
Add data
-
add()
s1 = {10, 20} s1.add(100) s1.add(10) print(s1) # {100, 10, 20}
Because the set has the function of de duplication, no operation will be performed when the data added to the set is the existing data of the current set.
-
update(), the appended data is a sequence.
s1 = {10, 20} # s1.update(100) # report errors s1.update([100, 200]) s1.update('abc') print(s1)
Delete data
-
remove(), delete the specified data in the collection. If the data does not exist, an error will be reported.
s1 = {10, 20} s1.remove(10) print(s1) s1.remove(10) # report errors print(s1)
-
discard(), delete the specified data in the collection. If the data does not exist, no error will be reported.
s1 = {10, 20} s1.discard(10) print(s1) s1.discard(10) print(s1)
-
pop(), randomly delete a data in the collection and return the data.
s1 = {10, 20, 30, 40, 50} del_num = s1.pop() print(del_num) print(s1)
Find data
-
In: judge whether the data is in the set sequence
-
Not in: judge that the data is not in the set sequence
s1 = {10, 20, 30, 40, 50} print(10 in s1) print(10 not in s1)
summary
-
Create collection
-
There are data sets
s1 = {Data 1, Data 2, ...}
-
No data set
s1 = set()
-
-
Common operation
-
Add data
-
add()
-
update()
-
-
Delete data
-
remove()
-
discard()
-
-
Public operation
operator
operator | describe | Supported container types |
---|---|---|
+ | merge | String, list, tuple |
* | copy | String, list, tuple |
in | Does the element exist | String, list, tuple, dictionary |
not in | Does the element not exist | String, list, tuple, dictionary |
+
# 1. String str1 = 'aa' str2 = 'bb' str3 = str1 + str2 print(str3) # aabb # 2. List list1 = [1, 2] list2 = [10, 20] list3 = list1 + list2 print(list3) # [1, 2, 10, 20] # 3. Tuple t1 = (1, 2) t2 = (10, 20) t3 = t1 + t2 print(t3) # (10, 20, 100, 200)
*
# 1. String print('-' * 10) # ---------- # 2. List list1 = ['hello'] print(list1 * 4) # ['hello', 'hello', 'hello', 'hello'] # 3. Tuple t1 = ('world',) print(t1 * 4) # ('world', 'world', 'world', 'world')
In or not in
# 1. String print('a' in 'abcd') # True print('a' not in 'abcd') # False # 2. List list1 = ['a', 'b', 'c', 'd'] print('a' in list1) # True print('a' not in list1) # False # 3. Tuple t1 = ('a', 'b', 'c', 'd') print('aa' in t1) # False print('aa' not in t1) # True
Public method
function | describe |
---|---|
len() | Calculate the number of elements in the container |
Del or del() | delete |
max() | Returns the maximum value of the element in the container |
min() | Returns the minimum value of the element in the container |
range(start, end, step) | Generate a number from start to end in step for the for loop |
enumerate() | The function is used to combine a traversable data object (such as list, tuple or string) into an index sequence, and list data and data subscripts at the same time. It is generally used in the for loop. |
len()
# 1. String str1 = 'abcdefg' print(len(str1)) # 7 # 2. List list1 = [10, 20, 30, 40] print(len(list1)) # 4 # 3. Tuple t1 = (10, 20, 30, 40, 50) print(len(t1)) # 5 # 4. Assembly s1 = {10, 20, 30} print(len(s1)) # 3 # 5. Dictionary dict1 = {'name': 'Rose', 'age': 18} print(len(dict1)) # 2
del()
# 1. String str1 = 'abcdefg' del str1 print(str1) # 2. List list1 = [10, 20, 30, 40] del(list1[0]) print(list1) # [20, 30, 40]
max()
# 1. String str1 = 'abcdefg' print(max(str1)) # g # 2. List list1 = [10, 20, 30, 40] print(max(list1)) # 40
min()
# 1. String str1 = 'abcdefg' print(min(str1)) # a # 2. List list1 = [10, 20, 30, 40] print(min(list1)) # 10
range()
# 1 2 3 4 5 6 7 8 9 for i in range(1, 10, 1): print(i) # 1 3 5 7 9 for i in range(1, 10, 2): print(i) # 0 1 2 3 4 5 6 7 8 9 for i in range(10): print(i)
Note: the sequence generated by range() does not contain the end number.
enumerate()
-
grammar
enumerate(Traversable object, start=0)
Note: the start parameter is used to set the starting value of the subscript of traversal data, which is 0 by default.
-
Quick experience
list1 = ['a', 'b', 'c', 'd', 'e'] for i in enumerate(list1): print(i) for index, char in enumerate(list1, start=1): print(f'The subscript is{index}, The corresponding character is{char}')
Container type conversion
tuple()
Function: convert a sequence into tuples
list1 = [10, 20, 30, 40, 50, 20] s1 = {100, 200, 300, 400, 500} print(tuple(list1)) print(tuple(s1))
list()
Function: convert a sequence into a list
t1 = ('a', 'b', 'c', 'd', 'e') s1 = {100, 200, 300, 400, 500} print(list(t1)) print(list(s1))
set()
Function: convert a sequence into a set
list1 = [10, 20, 30, 40, 50, 20] t1 = ('a', 'b', 'c', 'd', 'e') print(set(list1)) print(set(t1))
be careful:
-
Collection can quickly complete list de duplication
-
Collection does not support subscripts
summary
-
operator
-
+
-
in / not in
-
-
Public method
-
len()
-
del()
-
range()
-
enumerate()
-
-
Data type conversion
-
tuple()
-
list()
-
set()
-
Derivation
Function: use an expression to create a regular list or control a regular list.
List derivation is also called list generation.
Quick experience
Requirement: create a 0-10 list.
-
while loop implementation
# 1. Prepare an empty list list1 = [] # 2. Write cycle, and add numbers to the empty list list1 in turn i = 0 while i < 10: list1.append(i) i += 1 print(list1)
-
for loop implementation
list1 = [] for i in range(10): list1.append(i) print(list1)
-
List derivation implementation
list1 = [i for i in range(10)] print(list1)
List derivation with if
Requirement: create an even list of 0-10
-
Method 1: range() step implementation
list1 = [i for i in range(0, 10, 2)] print(list1)
-
Method 2: if implementation
list1 = [i for i in range(10) if i % 2 == 0] print(list1)
Multiple for loops implement list derivation
Requirement creation list is as follows:
[(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
-
The code is as follows:
list1 = [(i, j) for i in range(1, 3) for j in range(3)] print(list1)
Dictionary derivation
Think: if there are two lists:
list1 = ['name', 'age', 'gender'] list2 = ['Tom', 20, 'man']
How to quickly merge into one dictionary?
Answer: Dictionary derivation
Dictionary derivation function: quickly merge the list into a dictionary or extract the target data in the dictionary.
Quick experience
-
Create a dictionary: the dictionary key is a 1-5 number, and the value is the power of the number.
dict1 = {i: i**2 for i in range(1, 5)} print(dict1) # {1: 1, 2: 4, 3: 9, 4: 16}
-
Merge the two lists into one dictionary
list1 = ['name', 'age', 'gender'] list2 = ['Tom', 20, 'man'] dict1 = {list1[i]: list2[i] for i in range(len(list1))} print(dict1)
-
Extract target data from dictionary
counts = {'MBP': 268, 'HP': 125, 'DELL': 201, 'Lenovo': 199, 'acer': 99} # Demand: extract dictionary data with the above number of computers greater than or equal to 200 count1 = {key: value for key, value in counts.items() if value >= 200} print(count1) # {'MBP': 268, 'DELL': 201}
Set derivation
Requirement: create a set with data to the power of 2 in the list below.
list1 = [1, 1, 2]
The code is as follows:
list1 = [1, 1, 2] set1 = {i ** 2 for i in list1} print(set1) # {1, 4}
Note: the collection has data De duplication function.
summary
-
Function of derivation: simplify code
-
Deductive writing
# List derivation [xx for xx in range()] # Dictionary derivation {xx1: xx2 for ... in ...} # Set derivation {xx for xx in ...}
Function one
Function function
Demand: users withdraw money from ATM:
-
After entering the password, the "select function" interface is displayed
-
After querying the balance, the select function interface is displayed
-
After withdrawing 2000 yuan, the "select function" interface is displayed
Features: the "select function" interface needs to be repeatedly output to the user. How to realize it?
The function is to integrate = = a code block with independent functions = = into a whole and name it. Call this name = = where needed to complete the corresponding requirements.
During the development of function, code reuse = = = can be realized more efficiently.
To use a function
Define function
def Function name(parameter): Code 1 Code 2 ......
Call function
Function name(parameter)
be careful:
-
Parameters are optional for different requirements.
-
In Python, functions must be defined before they are used.
Quick experience
Demand: reproduce ATM withdrawal function.
-
Build the overall framework (reproduction requirements)
print('The password is correct and the login is successful') # The "select function" interface is displayed print('Balance query completed') # The "select function" interface is displayed print('I withdrew 2000 yuan') # The "select function" interface is displayed
-
Determine the content of "select function" interface
print('Check the balance') print('deposit') print('withdraw money')
-
Encapsulate the selection function
Note: we must first define functions and then call functions.
# Encapsulating ATM function options -- defining functions def select_func(): print('-----Please select a function-----') print('Check the balance') print('deposit') print('withdraw money') print('-----Please select a function-----')
-
Call function
Call the function where you want to display the select function.
print('The password is correct and the login is successful') # Display "select function" interface -- call function select_func() print('Balance query completed') # Display "select function" interface -- call function select_func() print('I withdrew 2000 yuan') # Display "select function" interface -- call function select_func()
Parameter action of function
Thinking: the completion requirements are as follows: how to write a program when a function completes the addition of two numbers 1 and 2?
# Define function def add_num1(): result = 1 + 2 print(result) # Call function add_num1()
Think: add above_ Num1 function can only add numbers 1 and 2. If you want this function to be more flexible, you can calculate the sum of any two numbers specified by the user. How to write the program?
Analysis: if you want to specify a specific number when calling a function, you need to receive the number specified by the user when defining a function. The number specified when calling the function and the number received when defining the function are the parameters of the function.
# When defining the function, the parameters a and b for receiving user data are defined at the same time. A and b are formal parameters def add_num2(a, b): result = a + b print(result) # When calling the function, real data 10 and 20 are passed in, and the real data is an argument add_num2(10, 20)
Function return value
For example, when we go shopping in the supermarket, such as buying cigarettes, will the salesperson return us the product of cigarettes after giving the money? In the function, if we need to return the result to the user, we need to use the return value of the function.
def buy(): return 'smoke' # Use variables to save function return values goods = buy() print(goods)
application
Requirements: make a calculator, calculate the sum of any two numbers, and save the results.
def sum_num(a, b): return a + b # Save the return value of the function with the result variable result = sum_num(1, 2) print(result)
Documentation for functions
Thinking: after defining a function, how can a programmer write a program that can quickly prompt the function?
Answer: Notes
Think: if there is a lot of code, do we need to find the location of this function definition in a lot of code to see the comments? What if you want to view the function more conveniently?
Answer: function description document
The function description document is also called the function description document.
grammar
-
Documentation for defining functions
def Function name(parameter): """ Describe the location of the document """ code ......
-
View the documentation for the function
help(Function name)
Quick experience
def sum_num(a, b): """ Summation function """ return a + b help(sum_num)
Function nested call
The so-called function nested call refers to = = another function is called in one function = =.
-
Example
def testB(): print('---- testB start----') print('Here is testB Code executed by function...(ellipsis)...') print('---- testB end----') def testA(): print('---- testA start----') testB() print('---- testA end----') testA()
-
If a function B is called in function A, then the task in function B is executed before the last function A executes.
Function application
Function calculation
-
Find the sum of three numbers
def sum_num(a, b, c): return a + b + c result = sum_num(1, 2, 3) print(result) # 6
-
Average the three numbers
def average_num(a, b, c): sumResult = sum_num(a, b, c) return sumResult / 3 result = average_num(1, 2, 3) print(result) # 2.0
summary
-
Function: encapsulate code and reuse code efficiently
-
Function usage steps
-
Define function
def Function name(): Code 1 Code 2 ...
-
Call function
Function name()
-
-
Function parameters: real data can be passed in during function call to increase the flexibility of function use
-
Formal parameter: parameter written during function definition (non real data)
-
Argument: parameter written during function call (real data)
-
-
Return value of function
-
Function: returns the required calculation result after function call
-
Writing method
return expression
-
-
Documentation for functions
-
Function: save function explanation information
-
Writing method
def Function name(): """ Function description document """
-
-
Nested function call: a function is nested inside another function
Function two
Variable scope
Variable scope refers to the effective range of variables, which is mainly divided into two categories: = = local variables = = and = = global variables = =.
-
local variable
The so-called local variables are variables defined inside the function body, that is, they only take effect inside the function body.
def testA(): a = 100 print(a) testA() # 100 print(a) # Error: name 'a' is not defined
Variable a is a variable defined inside the testA function. If it is accessed outside the function, an error will be reported immediately.
Function of local variable: temporarily save data inside the function body, that is, destroy the local variable after the function call is completed.
-
global variable
The so-called global variable refers to the variable that can take effect both inside and outside the function.
Think: what if there is A data to be used in both function A and function B?
A: store this data in a global variable.
# Define global variable a a = 100 def testA(): print(a) # Access global variable a and print the data stored in variable a def testB(): print(a) # Access global variable a and print the data stored in variable a testA() # 100 testB() # 100
Thinking: the testB function needs to modify the value of variable a to 200. How to modify the program?
a = 100 def testA(): print(a) def testB(): a = 200 print(a) testA() # 100 testB() # 200 print(f'global variable a = {a}') # Global variable a = 100
Think: is the variable a in a = 200 inside the testB function modifying the global variable a?
A: No. After observing the above code, it is found that the data of a obtained in line 15 is 100, which is still the value when defining the global variable a, and there is no return
200 inside the testB function. To sum up: a = 200 inside the testB function defines a local variable.
Thinking: how to modify global variables inside the function body?
a = 100 def testA(): print(a) def testB(): # Global keyword declares that a is a global variable global a a = 200 print(a) testA() # 100 testB() # 200 print(f'global variable a = {a}') # Global variable a = 200
Multi function program execution flow
Generally, in the actual development process, a program is often composed of multiple functions (classes will be explained later), and multiple functions share some data, as shown below:
-
Shared global variables
# 1. Define global variables glo_num = 0 def test1(): global glo_num # Modify global variables glo_num = 100 def test2(): # Call the modified global variable in test1 function print(glo_num) # 2. Call test1 function and execute the internal code of the function: declare and modify global variables test1() # 3. Call test2 function and execute the function internal code: print test2() # 100
-
The return value is passed as a parameter
def test1(): return 50 def test2(num): print(num) # 1. Save the return value of function test1 result = test1() # 2. Pass the variable of the function return value as a parameter to the test2 function test2(result) # 50
Return value of function
Think: if a function has two return s (as shown below), how does the program execute?
def return_num(): return 1 return 2 result = return_num() print(result) # 1
A: only the first return is executed because return can exit the current function, so the code below return will not be executed.
Think: if a function needs to have multiple return values, how to write code?
def return_num(): return 1, 2 result = return_num() print(result) # (1, 2)
be careful:
-
return a, b. when multiple data are returned, the default is tuple type.
-
Return can be followed by a list, tuple, or dictionary to return multiple values.
Parameters of function
Position parameters
Positional parameters: when calling a function, parameters are passed according to the parameter positions defined by the function.
def user_info(name, age, gender): print(f'What's your name{name}, Age is{age}, Gender is{gender}') user_info('TOM', 20, 'male')
Note: the order and number of parameters passed and defined must be consistent.
Keyword parameters
Function call, specified in the form of "key = value". It can make the function clearer and easier to use, and eliminate the sequence requirements of parameters.
def user_info(name, age, gender): print(f'What's your name{name}, Age is{age}, Gender is{gender}') user_info('Rose', age=20, gender='female') user_info('Xiao Ming', gender='male', age=16)
Note: when calling a function, if there is a location parameter, the location parameter must be in front of the keyword parameter, but there is no order between the keyword parameters.
Default parameters
Default parameters are also called default parameters. They are used to define functions and provide default values for parameters. When calling a function, the value of the default parameter may not be passed (Note: all location parameters must appear in front of the default parameters, including function definition and call).
def user_info(name, age, gender='male'): print(f'What's your name{name}, Age is{age}, Gender is{gender}') user_info('TOM', 20) user_info('Rose', 18, 'female')
Note: when calling a function, if the value is passed for the default parameter, the default parameter value will be modified; Otherwise, use this default value.
Indefinite length parameter
Variable length parameters are also called variable parameters. It is used in scenarios where it is uncertain how many parameters will be passed during the call (it is OK not to pass parameters). At this time, it is very convenient to transfer the parameters by using the packaging location parameter or the package keyword parameter.
-
Package location transfer
def user_info(*args): print(args) # ('TOM',) user_info('TOM') # ('TOM', 18) user_info('TOM', 18)
Note: all parameters passed in will be collected by the args variable, which will be combined into a tuple according to the position of the parameters passed in. Args is a tuple type, which is package position transfer.
-
Package keyword delivery
def user_info(**kwargs): print(kwargs) # {'name': 'TOM', 'age': 18, 'id': 110} user_info(name='TOM', age=18, id=110)
To sum up: both package location transfer and package keyword transfer are a process of package grouping.
Unpacking and exchanging variable values
Unpacking
-
Unpacking: tuples
def return_num(): return 100, 200 num1, num2 = return_num() print(num1) # 100 print(num2) # 200
-
Unpacking: Dictionary
dict1 = {'name': 'TOM', 'age': 18} a, b = dict1 # Unpack the dictionary and take out the key of the dictionary print(a) # name print(b) # age print(dict1[a]) # TOM print(dict1[b]) # 18
Exchange variable values
Demand: there are variables a = 10 and b = 20. Exchange the values of the two variables.
-
Method 1
The data is stored by means of a third variable.
# 1. Define intermediate variables c = 0 # 2. Store the data of a to c c = a # 3. Assign the data 20 of b to a, where a = 20 a = b # 4. Assign the data 10 of the previous c to B, where b = 10 b = c print(a) # 20 print(b) # 10
-
Method 2
a, b = 1, 2 a, b = b, a print(a) # 2 print(b) # 1
quote
Understanding references
In python, values are passed by reference.
We can use id() to determine whether two variables are references to the same value. We can understand the id value as the address identification of that memory.
# 1. int type a = 1 b = a print(b) # 1 print(id(a)) # 140708464157520 print(id(b)) # 140708464157520 a = 2 print(b) # 1. Description: int type is immutable print(id(a)) # 140708464157552. At this time, the memory address of data 2 is obtained print(id(b)) # 140708464157520 # 2. List aa = [10, 20] bb = aa print(id(aa)) # 2325297783432 print(id(bb)) # 2325297783432 aa.append(30) print(bb) # [10, 20, 30], the list is of variable type print(id(aa)) # 2325297783432 print(id(bb)) # 2325297783432
Reference as argument
The code is as follows:
def test1(a): print(a) print(id(a)) a += a print(a) print(id(a)) # int: the id value is different before and after calculation b = 100 test1(b) # List: the id values before and after calculation are the same c = [11, 22] test1(c)
Variable and immutable types
The so-called variable type and immutable type mean that data can be modified directly. If it can be modified directly, it is variable, otherwise it is immutable
-
Variable type
-
list
-
Dictionaries
-
aggregate
-
-
Immutable type
-
integer
-
float
-
character string
-
tuple
-
summary
-
Variable scope
-
Global: functions can take effect both inside and outside the body
-
Local: the current function body takes effect internally
-
-
Function multiple return value writing method
return Expression 1, Expression 2...
-
Parameters of function
-
Position parameters
-
The number and writing order of formal parameters and arguments must be consistent
-
-
Keyword parameters
-
Writing method: key=value
-
Features: the writing order of formal parameters and arguments can be inconsistent; Keyword parameters must be written after positional parameters
-
-
Default parameters
-
The default parameter is the default parameter
-
Writing method: key=vlaue
-
-
Variable length position parameter
-
Collect all location parameters and return a tuple
-
-
Variable length keyword parameter
-
Collect all keyword parameters and return a dictionary
-
-
-
Reference: in Python, data is passed by reference
Function three
Application: student management system
System introduction
Requirements: enter the system display system function interface, and the functions are as follows:
-
1. Add student
-
2. Delete student
-
3. Modify student information
-
4. Query student information
-
5. Display all student information
-
6. Exit the system
The system has 6 functions, which users can select according to their own needs.
Step analysis
-
Display function interface
-
User input function serial number
-
Execute different functions (functions) according to the function serial number entered by the user
3.1 defining functions
3.2 calling functions
Requirement realization
Display function interface
Define function print_info, responsible for displaying system functions.
def print_info(): print('-' * 20) print('Welcome to the student management system') print('1: Add student') print('2: Delete student') print('3: Modify student information') print('4: Query student information') print('5: Display all student information') print('6: Exit the system') print('-' * 20) print_info()
The user enters the serial number and selects the function
user_num = input('Please select the function serial number you need:')
Perform different functions according to user selection
if user_num == '1': print('Add student') elif user_num == '2': print('Delete student') elif user_num == '3': print('Modify student information') elif user_num == '4': print('Query student information') elif user_num == '5': print('Display all student information') elif user_num == '6': print('Exit the system')
At work, you need to tune your code according to your actual needs.
-
The code that the user selects the system function needs to be recycled until the user voluntarily exits the system.
-
If the user enters a number other than 1-6, the user needs to be prompted.
while True: # 1. Display function interface print_info() # 2. User selection function user_num = input('Please select the function serial number you need:') # 3. Perform different functions according to user selection if user_num == '1': print('Add student') elif user_num == '2': print('Delete student') elif user_num == '3': print('Modify student information') elif user_num == '4': print('Query student information') elif user_num == '5': print('Display all student information') elif user_num == '6': print('Exit the system') else: print('Input error, please re-enter!!!')
Define functions for different functions
All function functions operate student information. All stored student information should be a = = global variable = =, and the data type is = = list = =.
info = []
1.3.4.1 adding students
-
requirement analysis
-
Receive the student information entered by the user and save it
-
Judge whether to add student information
2.1 if the student's name already exists, an error will be reported
2.2 if the student's name does not exist, prepare an empty dictionary, add the data entered by the user to the dictionary, and then add dictionary data to the list
-
Call this function where the corresponding if condition holds
-
code implementation
def add_info(): """ Add student """ # Receive user input student information new_id = input('Please enter student number:') new_name = input('Please enter your name:') new_tel = input('Please enter your phone number:') # Declare info as a global variable global info # Check whether the name entered by the user exists. If it exists, an error will be reported for i in info: if new_name == i['name']: print('The user already exists!') return # If the name entered by the user does not exist, add the student information info_dict = {} # Append the data entered by the user to the dictionary info_dict['id'] = new_id info_dict['name'] = new_name info_dict['tel'] = new_tel # Append the learner's dictionary data to the list info.append(info_dict) print(info)
Delete student
-
requirement analysis
Delete according to the student name entered by the user
-
User input target student name
-
Check if this student exists
2.1 if it exists, delete the data from the list
2.2 if it does not exist, it will prompt "the user does not exist"
-
Call this function where the corresponding if condition holds
-
code implementation
# Delete student def del_info(): """Delete student""" # 1. The user enters the name of the student to be deleted del_name = input('Please enter the name of the student to delete:') global info # 2. Judge whether the student exists: if the entered name exists, it will be deleted; otherwise, an error will be reported for i in info: if del_name == i['name']: info.remove(i) break else: print('The student does not exist') print(info)
Modify student information
-
requirement analysis
-
User input target student name
-
Check if this student exists
2.1 if it exists, modify the student's information, such as mobile phone number
2.2 if it does not exist, an error is reported
-
Call this function where the corresponding if condition holds
-
code implementation
# Modify function def modify_info(): """Modify function""" # 1. The user inputs the name of the student to be modified modify_name = input('Please enter the name of the student to be modified:') global info # 2. Judge whether the student exists: if the entered name exists, modify the mobile phone number, otherwise an error will be reported for i in info: if modify_name == i ['name']: i['tel'] = input('Please enter a new phone number:') break else: print('The student does not exist') print(info)
Query student information
-
requirement analysis
-
User input target student name
-
Check if the delegates are present
2.1 if it exists, the information of this student will be displayed
2.2 if it does not exist, an error will be reported
-
Call this function where the corresponding if condition holds
-
code implementation
# Query students def search_info(): """Query students""" # 1. Enter the name of the student to find: search_name = input('Please enter the name of the student you want to find:') global info # 2. Judge whether the student exists: if the entered name exists, the student information will be displayed; otherwise, an error message will be displayed for i in info: if search_name == i['name']: print('The student information found is as follows:----------') print(f"The student number of the student is{i['id']}, Name is{i['name']}, The phone number is{i['tel']}") break else: print('The student does not exist')
Display all student information
-
requirement analysis
Print all student information
-
code implementation
# Display all student information def print_all(): """ Display all student information """ print('Student number\t full name\t cell-phone number') for i in info: print(f'{i["id"]}\t{i["name"]}\t{i["tel"]}')
1.3.4.6 exit the system
When the user enters the function No. 6, he / she should exit the system. The code is as follows:
...... elif user_num == '6': exit_flag = input('Are you sure you want to exit? yes or no') if exit_flag == 'yes': break
Recursion
Recursion is a programming idea. Application scenarios:
-
In our daily development, if we want to traverse all the files under a folder, we usually use recursive implementation;
-
In the subsequent algorithm courses, many algorithms are inseparable from recursion, such as quick sorting.
Recursive characteristics
-
The function calls itself internally
-
There must be an exit
Application: Digital summation within 3
-
code
# 3 + 2 + 1 def sum_numbers(num): # 1. If it is 1, directly return to 1 - exit if num == 1: return 1 # 2. If it is not 1, repeat the accumulation and return the result return num + sum_numbers(num-1) sum_result = sum_numbers(3) # The output is 6 print(sum_result)
lambda expression
If a function has a return value and only one sentence of code, you can use lambda to simplify it.
lambda syntax
lambda Parameter lists: expressions
be careful
-
The parameters of lambda expression are optional, and the parameters of function are fully applicable in lambda expression.
-
lambda expressions can accept any number of parameters, but can only return the value of one expression.
quick get start
# function def fn1(): return 200 print(fn1) print(fn1()) # lambda expressions fn2 = lambda: 100 print(fn2) print(fn2())
Note: the lambda expression is printed directly, and the memory address of the lambda is output
Example: calculate a + b
Function implementation
def add(a, b): return a + b result = add(1, 2) print(result)
Thinking: simple requirements, more code?
lambda implementation
fn1 = lambda a, b: a + b print(fn1(1, 2))
Parameter form of lambda
No parameters
fn1 = lambda: 100 print(fn1())
One parameter
fn1 = lambda a: a print(fn1('hello world'))
Default parameters
fn1 = lambda a, b, c=100: a + b + c print(fn1(10, 20))
Variable parameter: * args
fn1 = lambda *args: args print(fn1(10, 20, 30))
Note: after the variable parameters here are passed into lambda, the return value is tuple.
Variable parameters: * * kwargs
fn1 = lambda **kwargs: kwargs print(fn1(name='python', age=20))
Application of lambda
lambda with judgment
fn1 = lambda a, b: a if a > b else b print(fn1(1000, 500))
The list data is sorted by the value of the dictionary key
students = [ {'name': 'TOM', 'age': 20}, {'name': 'ROSE', 'age': 19}, {'name': 'Jack', 'age': 22} ] # Sort by name value in ascending order students.sort(key=lambda x: x['name']) print(students) # Sort by name value in descending order students.sort(key=lambda x: x['name'], reverse=True) print(students) # Sort in ascending order by age value students.sort(key=lambda x: x['age']) print(students)
Higher order function
==Pass the function as a parameter = =. Such a function is called a high-order function, which is the embodiment of functional programming. Functional programming refers to this highly abstract programming paradigm.
Experience higher order functions
In Python, the abs() function can calculate the absolute value of a number.
abs(-10) # 10
The round() function completes the rounding calculation of numbers.
round(1.2) # 1 round(1.9) # 2
Demand: sum any two numbers after sorting them according to the specified requirements.
-
Method 1
def add_num(a, b): return abs(a) + abs(b) result = add_num(-1, 2) print(result) # 3
-
Method 2
def sum_num(a, b, f): return f(a) + f(b) result = sum_num(-1, 2, abs) print(result) # 3
Note: after comparing the two methods, it is found that the code of method 2 will be more concise and the function flexibility will be higher.
Functional programming uses a lot of functions to reduce the repetition of code, so the program is relatively short and the development speed is fast.
Built in higher order function
map()
map(func, lst). The passed function variable func is applied to each element of the lst variable, and the result is returned as a new list (Python 2) / iterator (Python 3).
Requirement: calculate the power 2 of each number in list1 sequence.
list1 = [1, 2, 3, 4, 5] def func(x): return x ** 2 result = map(func, list1) print(result) # <map object at 0x0000013769653198> print(list(result)) # [1, 4, 9, 16, 25]
reduce()
reduce(func, lst), where func must have two parameters. The result of each func calculation continues to accumulate with the next element of the sequence.
Note: the parameter func passed in by reduce() must receive 2 parameters.
Requirement: calculate the cumulative sum of each number in list1 sequence.
import functools list1 = [1, 2, 3, 4, 5] def func(a, b): return a + b result = functools.reduce(func, list1) print(result) # 15
filter()
The filter(func, lst) function is used to filter the sequence, filter out unqualified elements, and return a filter object. If you want to convert to a list, you can use list() to convert.
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def func(x): return x % 2 == 0 result = filter(func, list1) print(result) # <filter object at 0x0000017AF9DC3198> print(list(result)) # [2, 4, 6, 8, 10]
summary
-
recursion
-
The function calls itself internally
-
There must be an exit
-
-
lambda
-
grammar
lambda parameter list: expression
-
Parameter form of lambda
-
No parameters
lambda: expression
-
One parameter
lambda parameter: expression
-
Default parameters
lambda key=value: expression
-
Variable length position parameter
lambda *args: expression
-
Variable length keyword parameter
lambda **kwargs: expression
-
-
-
Higher order function
-
Function: pass the function as a parameter to simplify the code
-
Built in higher order function
-
map()
-
reduce()
-
filter()
-
-
File operation
Role of file operation
Thinking: what is a document?
Think: what does a file operation contain?
Answer: open, close, read, write, copy
Thinking: what is the role of file operation?
A: read content, write content, backup content
Summary: the function of file operation is = = to store some contents (data) so that the program can be used directly in the next execution without having to make a new copy, saving time and effort = =.
Basic operation of files
File operation steps
-
Open file
-
Read and write operations
-
Close file
Note: you can only open and close files without any read-write operations.
open
In python, you can use the open function to open an existing file or create a new file. The syntax is as follows:
open(name, mode)
Name: is the string of the name of the target file to be opened (which can contain the specific path where the file is located).
Mode: set the mode of opening files (access mode): read-only, write, append, etc.
Open file mode
pattern | describe |
---|---|
r | Open the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode. |
rb | Open a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode. |
r+ | Open a file for reading and writing. The file pointer will be placed at the beginning of the file. |
rb+ | Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. |
w | Open a file for writing only. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. |
wb | Open a file in binary format for writing only. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. |
w+ | Open a file for reading and writing. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. |
wb+ | Open a file in binary format for reading and writing. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. |
a | Open a file for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing. |
ab | Open a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing. |
a+ | Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file is opened in append mode. If the file does not exist, create a new file for reading and writing. |
ab+ | Open a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing. |
Quick experience
f = open('test.txt', 'w')
Note: f in this case is the file object of the open function.
File object method
Write
-
grammar
Object object.write('content')
-
experience
# 1. Open the file f = open('test.txt', 'w') # 2. File writing f.write('hello world') # 3. Close the file f.close()
be careful:
-
W and a modes: if the file does not exist, the file is created; If the file exists, the w mode is cleared before writing, and the a mode is appended directly to the end.
-
r mode: if the file does not exist, an error is reported.
Read
-
read()
File object.read(num)
Num indicates the length of the data to be read from the file (in bytes). If num is not passed in, it means that all the data in the file is read.
-
readlines()
readlines can read the contents of the whole file at one time in the form of lines, and return a list, in which the data of each line is an element.
f = open('test.txt') content = f.readlines() # ['hello world\n', 'abcdefg\n', 'aaa\n', 'bbb\n', 'ccc'] print(content) # Close file f.close()
-
readline()
readline() reads one line at a time.
f = open('test.txt') content = f.readline() print(f'First line:{content}') content = f.readline() print(f'Second line:{content}') # Close file f.close()
seek()
Function: used to move the file pointer.
The syntax is as follows:
File object.seek(Offset, Starting position)
Starting position:
-
0: beginning of file
-
1: Current location
-
2: End of file
close
File object.close()
File backup
Requirement: the user inputs any file name in the current directory, and the program completes the backup function of the file (the backup file name is xx [backup] suffix, for example: test [backup]. txt).
step
-
Receive the file name entered by the user
-
Planning backup file name
-
Backup file write data
code implementation
-
Receive user input destination file name
old_name = input('Please enter the file name you want to back up:')
-
Planning backup file name
2.1 extracting suffix of target file
2.2 file name of organization backup, xx [backup] suffix
# 2.1 extract the subscript of the suffix point of the file index = old_name.rfind('.') # print(index) # In suffix Subscript of # print(old_name[:index]) # Source file name (no suffix) # 2.2 organization new file name old file name + [backup] + suffix new_name = old_name[:index] + '[backups]' + old_name[index:] # Print new file name (with suffix) # print(new_name)
-
Backup file write data
3.1 open source and backup files
3.2 write source file data to backup file
3.3 closing documents
# 3.1 opening files old_f = open(old_name, 'rb') new_f = open(new_name, 'wb') # 3.2 write source file data to backup file while True: con = old_f.read(1024) if len(con) == 0: break new_f.write(con) # 3.3 closing documents old_f.close() new_f.close()
reflection
If entered by the user txt, this is an invalid file. How can the program change it to limit that only valid file names can be backed up?
A: add condition judgment.
old_name = input('Please enter the file name you want to back up:') index = old_name.rfind('.') if index > 0: postfix = old_name[index:] new_name = old_name[:index] + '[backups]' + postfix old_f = open(old_name, 'rb') new_f = open(new_name, 'wb') while True: con = old_f.read(1024) if len(con) == 0: break new_f.write(con) old_f.close() new_f.close()
Operation of files and folders
In Python, the operation of files and folders depends on the relevant functions in the os module. The specific steps are as follows:
-
Import os module
import os
-
Using os module related functions
os.Function name()
File rename
os.rename(Destination file name, New file name)
Delete file
os.remove(Destination file name)
create folder
os.mkdir(Folder name)
remove folders
os.rmdir(Folder name)
Get current directory
os.getcwd()
Change default directory
os.chdir(catalogue)
Get directory list
os.listdir(catalogue)
Application case
Requirement: batch modify the file name, which can add and delete the specified string.
-
step
-
Sets the identity of the string to be added or deleted
-
Gets all files in the specified directory
-
Add / delete the specified string of the original file name to construct a new name
-
os.rename() rename
-
code
import os # Set rename ID: if it is 1, the specified character will be added; if flag is 2, the specified character will be deleted flag = 1 # Gets the specified directory dir_name = './' # Gets the list of files in the specified directory file_list = os.listdir(dir_name) # print(file_list) # Traverse the files in the file list for name in file_list: # Add specified character if flag == 1: new_name = 'Python-' + name # Delete specified character elif flag == 2: num = len('Python-') new_name = name[num:] # Print the new file name to test the correctness of the program print(new_name) # rename os.rename(dir_name+name, dir_name+new_name)
summary
-
File operation steps
-
open
File object = open(Target file, Access mode)
-
operation
-
read
File object.read() File object.readlines() File object.readline()
-
write
File object.write()
-
seek()
-
-
close
File object.close()
-
-
Primary access mode
-
w: Write. If the file does not exist, create a new file
-
r: If the file does not exist, an error will be reported
-
a: Add
-
-
File and folder operations
-
Rename: OS rename()
-
Get current directory: OS getcwd()
-
Get directory list: OS listdir()
-
Object oriented Foundation
Understanding object orientation
Object oriented is an abstract programming idea, which is common in many programming languages.
Summary: = = object oriented is to treat programming as a thing. For the outside world, things are used directly, regardless of their internal situation. Programming is to set what things can do==
Classes and objects
In the process of object-oriented programming, there are two important parts: class {and object
Relationship between class and object: use class to create an object.
Understanding classes and objects
class
Class is the general name of a series of things with the same = = characteristics = = and = = behavior = =. It is an abstract concept = =, not a real thing.
-
Characteristics are attributes
-
Behavior is method
object
Objects are real things created by classes
Note: in development, there are classes before objects.
Object oriented implementation method
Define class
There are two classes in Python 2: Classic class and new class
-
grammar
class Class name(): code ......
Note: the class name shall meet the identifier naming rules and follow the = = big hump naming habit = =.
-
experience
class Washer(): def wash(self): print('I can wash clothes')
-
Expansion: Classic
A class that does not derive from any built-in type is called a classic class
class Class name: code ......
create object
Object, also known as instance.
-
grammar
Object name = Class name()
-
experience
# create object haier1 = Washer() # <__main__.Washer object at 0x0000018B7B224240> print(haier1) # The haier object calls the instance method haier1.wash()
Note: the process of creating an object is also called instantiating an object.
self
self refers to the object that calls the function.
# 1. Definition class class Washer(): def wash(self): print('I can wash clothes') # <__main__.Washer object at 0x0000024BA2B34240> print(self) # 2. Create object haier1 = Washer() # <__main__.Washer object at 0x0000018B7B224240> print(haier1) # haier1 object calls instance method haier1.wash() haier2 = Washer() # <__main__.Washer object at 0x0000022005857EF0> print(haier2)
Note: the results obtained by printing the object and self are consistent, both of which are the memory address of the current object.
Add and get object properties
Object properties can be added and obtained either outside the class or inside the class.
Add object attribute syntax outside class
Object name.Attribute name = value
-
experience
haier1.width = 500 haier1.height = 800
Get object properties outside class
-
grammar
Object name.Attribute name
-
experience
print(f'haier1 What is the width of the washing machine{haier1.width}') print(f'haier1 What is the height of the washing machine{haier1.height}')
Class to get object properties
-
grammar
self.Attribute name
-
experience
# Define class class Washer(): def print_info(self): # Class to get instance properties print(f'haier1 What is the width of the washing machine{self.width}') print(f'haier1 What is the height of the washing machine{self.height}') # create object haier1 = Washer() # Add instance properties haier1.width = 500 haier1.height = 800 haier1.print_info()
Magic method
In Python__ xx__ The function of () is called magic method, which refers to the function with special function.
__init__()
Experience__ init__ ()
==__ init__ () method: initializes an object==
class Washer(): # Functions that define initialization functions def __init__(self): # Add instance properties self.width = 500 self.height = 800 def print_info(self): # Class to call instance properties print(f'What is the width of the washing machine{self.width}, Height is{self.height}') haier1 = Washer() haier1.print_info()
be careful:
-
__ init__ () method is called by default when creating an object and does not need to be called manually
-
__ init__ The self parameter in (self) does not need to be passed by the developer. The python interpreter will automatically pass the current object reference.
With parameters__ init__ ()
Thinking: a class can create multiple objects. How to set different initialization properties for different objects?
Answer: pass parameters.
class Washer(): def __init__(self, width, height): self.width = width self.height = height def print_info(self): print(f'What is the width of the washing machine{self.width}') print(f'What is the height of the washing machine{self.height}') haier1 = Washer(10, 20) haier1.print_info() haier2 = Washer(30, 40) haier2.print_info()
__str__()
When using print to output an object, the memory address of the object is printed by default. If the class is defined__ str__ Method, the data return ed from this method will be printed.
class Washer(): def __init__(self, width, height): self.width = width self.height = height def __str__(self): return 'This is the instruction manual of Haier washing machine' haier1 = Washer(10, 20) # This is the instruction manual of Haier washing machine print(haier1)
__del__()
When an object is deleted, the python interpreter also calls by default__ del__ () method.
class Washer(): def __init__(self, width, height): self.width = width self.height = height def __del__(self): print(f'{self}The object has been deleted') haier1 = Washer(10, 20) # <__ main__. Washer object at 0x000002618223278 > object has been deleted del haier1
Comprehensive application
Roasted sweet potatoes
Demand
Demand main line:
-
Roasted time and corresponding sweet potato state:
0-3 minutes: raw
3-5 minutes: half cooked
5-8 minutes: cooked
More than 8 minutes: burnt
-
Seasoning added:
Users can add spices according to their wishes
Step analysis
The demand involves a thing: sweet potato, so the case involves a class: sweet potato.
5.1.2.1 definition class
-
Properties of sweet potato
-
Baking time
-
State of sweet potato
-
Seasoning added
-
-
Method for producing sweet potato
-
Roasted
-
The user sets the time for each roast of sweet potato according to their wishes
-
Judge the total baking time of sweet potato and modify the state of sweet potato
-
-
Add seasoning
-
You can set the seasoning to be added according to your wishes
-
Store the seasoning added by the user
-
-
-
Display object information
5.1.2.2 create objects and call relevant instance methods
code implementation
5.1.3.1 definition class
-
Sweet potato attribute
-
Define the initialization attribute of sweet potato, and update the instance attribute according to the program in the later stage
-
class SweetPotato(): def __init__(self): # Baking time self.cook_time = 0 # State of sweet potato self.cook_static = 'raw' # Seasoning list self.condiments = []
5.1.3.2 define the method of roasting sweet potato
class SweetPotato(): ...... def cook(self, time): """Method for roasting sweet potato""" self.cook_time += time if 0 <= self.cook_time < 3: self.cook_static = 'raw' elif 3 <= self.cook_time < 5: self.cook_static = 'halfcooked' elif 5 <= self.cook_time < 8: self.cook_static = 'Ripe' elif self.cook_time >= 8: self.cook_static = 'It's burnt'
5.1.3.3 write str magic method, which is used to output object status
class SweetPotato(): ...... def __str__(self): return f'This sweet potato is roasted{self.cook_time}minute, Status is{self.cook_static}'
5.1.3.4 create objects, test instance properties and instance methods
digua1 = SweetPotato() print(digua1) digua1.cook(2) print(digua1)
5.1.3.5 define the method of adding seasoning and call the instance method
class SweetPotato(): ...... def add_condiments(self, condiment): """Add seasoning""" self.condiments.append(condiment) def __str__(self): return f'This sweet potato is roasted{self.cook_time}minute, Status is{self.cook_static}, The spices added are{self.condiments}' digua1 = SweetPotato() print(digua1) digua1.cook(2) digua1.add_condiments('soy sauce') print(digua1) digua1.cook(2) digua1.add_condiments('chili powder') print(digua1) digua1.cook(2) print(digua1) digua1.cook(2) print(digua1)
Code overview
# Define class class SweetPotato(): def __init__(self): # Baking time self.cook_time = 0 # State of sweet potato self.cook_static = 'raw' # Seasoning list self.condiments = [] def cook(self, time): """Method for roasting sweet potato""" self.cook_time += time if 0 <= self.cook_time < 3: self.cook_static = 'raw' elif 3 <= self.cook_time < 5: self.cook_static = 'halfcooked' elif 5 <= self.cook_time < 8: self.cook_static = 'Ripe' elif self.cook_time >= 8: self.cook_static = 'It's burnt' def add_condiments(self, condiment): """Add seasoning""" self.condiments.append(condiment) def __str__(self): return f'This sweet potato is roasted{self.cook_time}minute, Status is{self.cook_static}, The spices added are{self.condiments}' digua1 = SweetPotato() print(digua1) digua1.cook(2) digua1.add_condiments('soy sauce') print(digua1) digua1.cook(2) digua1.add_condiments('chili powder') print(digua1) digua1.cook(2) print(digua1) digua1.cook(2) print(digua1)
Move furniture
demand
Place furniture smaller than the remaining area of the house in the house
Step analysis
Demand involves two things: house and furniture, so the case involves two categories: house and furniture.
5.2.2.1 definition class
-
House class
-
Instance properties
-
House location
-
Floor area of the house
-
Remaining area of house
-
List of furniture in the house
-
-
Example method
-
Accommodating furniture
-
-
Display house information
-
-
Furniture
-
Furniture name
-
Furniture floor area
-
5.2.2.2 create objects and call related methods
code implementation
5.2.3.1 definition class
-
Furniture
class Furniture(): def __init__(self, name, area): # Furniture name self.name = name # Furniture floor area self.area = area
-
House class
class Home(): def __init__(self, address, area): # geographical position self.address = address # House area self.area = area # Remaining area self.free_area = area # Furniture list self.furniture = [] def __str__(self): return f'The house is located in{self.address}, area covered{self.area}, Remaining area{self.free_area}, Furniture has{self.furniture}' def add_furniture(self, item): """Accommodating furniture""" if self.free_area >= item.area: self.furniture.append(item.name) # After the furniture is moved in, the remaining area of the house = the previous remaining area - the area of the furniture self.free_area -= item.area else: print('The furniture is too large and the remaining area is insufficient to accommodate')
Create an object and call instance properties and methods
bed = Furniture('Double bed', 6) jia1 = Home('Beijing', 1200) print(jia1) jia1.add_furniture(bed) print(jia1) sofa = Furniture('sofa', 10) jia1.add_furniture(sofa) print(jia1) ball = Furniture('Basketball Court', 1500) jia1.add_furniture(ball) print(jia1)
summary
-
An important part of object-oriented
-
class
-
Create class
-
class Class name(): code
-
object
Object name = Class name()
-
-
Add object properties
-
Outside class
Object name.Attribute name = value
-
Inside the class
self.Attribute name = value
-
-
Get object properties
-
Outside class
Object name.Attribute name
-
Inside the class
self.Attribute name
-
-
Magic method
-
__ init__ (): initialization
-
__ str__ (): output object information
-
__ del__ (): called when an object is deleted
-
Object oriented - inheritance
Concept of inheritance
Inheritance in life generally means that children inherit the property of their parents.
-
Extension 1: classic or old style
A class that does not derive from any built-in type is called a classic class.
class Class name: code ......
-
Expansion 2: new type
class Class name(object): code
Python object-oriented inheritance refers to the ownership relationship between multiple classes, that is, the subclass inherits all the attributes and methods of the parent class by default, as follows:
# Parent class A class A(object): def __init__(self): self.num = 1 def info_print(self): print(self.num) # Subclass B class B(A): pass result = B() result.info_print() # 1
In Python, all classes inherit the object class by default. The object class is the top-level class or base class; Other subclasses are called derived classes.
Single inheritance
Story line: a pancake fruit teacher has worked in the pancake fruit industry for many years and developed a set of exquisite techniques for sharing pancake fruit. Master wants to teach this skill to his only and most proud apprentice.
Analysis: does the apprentice want to inherit all the skills of master?
# 1. Master class class Master(object): def __init__(self): self.kongfu = '[Gufa pancake fruit formula]' def make_cake(self): print(f'application{self.kongfu}Making pancake fruit') # 2. Apprentice class class Prentice(Master): pass # 3. Create an object daqiu daqiu = Prentice() # 4. Object access instance properties print(daqiu.kongfu) # 5. Object calling instance method daqiu.make_cake()
Multiple inheritance
Story promotion: Xiao Ming is a good child who loves learning. He wants to learn more pancake fruit technology, so he searches and studies on Baidu
The so-called multiple inheritance means that a class inherits multiple parent classes at the same time.
class Master(object): def __init__(self): self.kongfu = '[Gufa pancake fruit formula]' def make_cake(self): print(f'application{self.kongfu}Making pancake fruit') # Create school class class School(object): def __init__(self): self.kongfu = '[Pancake fruit formula]' def make_cake(self): print(f'application{self.kongfu}Making pancake fruit') class Prentice(School, Master): pass daqiu = Prentice() print(daqiu.kongfu) daqiu.make_cake()
Note: when a class has multiple parent classes, the properties and methods with the same name of the first parent class are used by default.
Subclasses override methods and properties with the same name as the parent class
Story: after Xiaoming mastered the skills of his master and training, he devoted himself to developing a new set of pancake fruit technology with his own unique formula.
class Master(object): def __init__(self): self.kongfu = '[Gufa pancake fruit formula]' def make_cake(self): print(f'application{self.kongfu}Making pancake fruit') class School(object): def __init__(self): self.kongfu = '[Pancake fruit formula]' def make_cake(self): print(f'application{self.kongfu}Making pancake fruit') # Original formula class Prentice(School, Master): def __init__(self): self.kongfu = '[Original pancake fruit formula]' def make_cake(self): print(f'application{self.kongfu}Making pancake fruit') daqiu = Prentice() print(daqiu.kongfu) daqiu.make_cake() print(Prentice.__mro__)
A child class and a parent class have properties and methods with the same name. The properties and methods with the same name of the child class are used by default.
The subclass calls the method and property of the parent class with the same name
Story: many customers want to eat pancakes and fruits of ancient law and dark horse technology.
class Master(object): def __init__(self): self.kongfu = '[Gufa pancake fruit formula]' def make_cake(self): print(f'application{self.kongfu}Making pancake fruit') class School(object): def __init__(self): self.kongfu = '[Dark horse pancake fruit formula]' def make_cake(self): print(f'application{self.kongfu}Making pancake fruit') class Prentice(School, Master): def __init__(self): self.kongfu = '[Original pancake fruit formula]' def make_cake(self): # If the properties and methods of the parent class are called first, the parent class property will override the class property. Therefore, before calling the property, call the initialization of your own child class self.__init__() print(f'application{self.kongfu}Making pancake fruit') # Invoke the parent class method, but to ensure that the property that is called is also a parent class, we must call the initialization of the parent class before calling the method. def make_master_cake(self): Master.__init__(self) Master.make_cake(self) def make_school_cake(self): School.__init__(self) School.make_cake(self) daqiu = Prentice() daqiu.make_cake() daqiu.make_master_cake() daqiu.make_school_cake() daqiu.make_cake()
Multilayer inheritance
Story: after N years, Xiao Ming is old and wants to pass on all his skills to his disciples.
class Master(object): def __init__(self): self.kongfu = '[Gufa pancake fruit formula]' def make_cake(self): print(f'application{self.kongfu}Making pancake fruit') class School(object): def __init__(self): self.kongfu = '[Pancake fruit formula]' def make_cake(self): print(f'application{self.kongfu}Making pancake fruit') class Prentice(School, Master): def __init__(self): self.kongfu = '[Original pancake fruit formula]' def make_cake(self): self.__init__() print(f'application{self.kongfu}Making pancake fruit') def make_master_cake(self): Master.__init__(self) Master.make_cake(self) def make_school_cake(self): School.__init__(self) School.make_cake(self) # Disciple class Tusun(Prentice): pass xiaoqiu = Tusun() xiaoqiu.make_cake() xiaoqiu.make_school_cake() xiaoqiu.make_master_cake()
super() calls the parent class method
class Master(object): def __init__(self): self.kongfu = '[Gufa pancake fruit formula]' def make_cake(self): print(f'application{self.kongfu}Making pancake fruit') class School(Master): def __init__(self): self.kongfu = '[Pancake fruit formula]' def make_cake(self): print(f'application{self.kongfu}Making pancake fruit') # Method 2.1 # super(School, self).__init__() # super(School, self).make_cake() # Method 2.2 super().__init__() super().make_cake() class Prentice(School): def __init__(self): self.kongfu = '[Original pancake fruit technology]' def make_cake(self): self.__init__() print(f'application{self.kongfu}Making pancake fruit') # Subclasses call the methods and properties of the parent class with the same name: encapsulate the properties and methods of the parent class with the same name again def make_master_cake(self): Master.__init__(self) Master.make_cake(self) def make_school_cake(self): School.__init__(self) School.make_cake(self) # Call the property and method with the same name of the parent class at once def make_old_cake(self): # Method 1: code redundancy; If the parent class name changes, the code here needs to be modified frequently # Master.__init__(self) # Master.make_cake(self) # School.__init__(self) # School.make_cake(self) # Method 2: super() # Method 2.1 super (current class name, self) Function () # super(Prentice, self).__init__() # super(Prentice, self).make_cake() # Method 2.2 super() Function () super().__init__() super().make_cake() daqiu = Prentice() daqiu.make_old_cake()
Note: use super() to automatically find the parent class. Call order follows__ mro__ The order of class properties. It is more suitable for single inheritance.
Private rights
Define private properties and methods
In Python, you can set private permissions for instance properties and methods, that is, set an instance property or instance method not to inherit from subclasses.
Story: while inheriting technology to his apprentice, Xiao Ming doesn't want to inherit his money (200000 billion) to his apprentice. At this time, he has to set private permissions for the instance property of money.
How to set private permissions: precede the property name and method name with two underscores _.
class Master(object): def __init__(self): self.kongfu = '[Gufa pancake fruit formula]' def make_cake(self): print(f'application{self.kongfu}Making pancake fruit') class School(object): def __init__(self): self.kongfu = '[Pancake fruit formula]' def make_cake(self): print(f'application{self.kongfu}Making pancake fruit') class Prentice(School, Master): def __init__(self): self.kongfu = '[Original pancake fruit formula]' # Define private properties self.__money = 2000000 # Define private methods def __info_print(self): print(self.kongfu) print(self.__money) def make_cake(self): self.__init__() print(f'application{self.kongfu}Making pancake fruit') def make_master_cake(self): Master.__init__(self) Master.make_cake(self) def make_school_cake(self): School.__init__(self) School.make_cake(self) # Disciple class Tusun(Prentice): pass daqiu = Prentice() # Object cannot access private properties and private methods # print(daqiu.__money) # daqiu.__info_print() xiaoqiu = Tusun() # Subclasses cannot inherit private properties and private methods of the parent class # print(xiaoqiu.__money) # Unable to access instance properties__ money # xiaoqiu.__info_print()
Note: private properties and private methods can only be accessed and modified in classes.
Get and modify private property values
In Python, the function name get is generally defined_ XX is used to obtain private properties and define set_xx is used to modify private property values.
class Master(object): def __init__(self): self.kongfu = '[Gufa pancake fruit formula]' def make_cake(self): print(f'application{self.kongfu}Making pancake fruit') class School(object): def __init__(self): self.kongfu = '[Pancake fruit formula]' def make_cake(self): print(f'application{self.kongfu}Making pancake fruit') class Prentice(School, Master): def __init__(self): self.kongfu = '[Original pancake fruit formula]' self.__money = 2000000 # Get private properties def get_money(self): return self.__money # Modify private properties def set_money(self): self.__money = 500 def __info_print(self): print(self.kongfu) print(self.__money) def make_cake(self): self.__init__() print(f'application{self.kongfu}Making pancake fruit') def make_master_cake(self): Master.__init__(self) Master.make_cake(self) def make_school_cake(self): School.__init__(self) School.make_cake(self) # Disciple class Tusun(Prentice): pass daqiu = Prentice() xiaoqiu = Tusun() # Call get_ The money function gets the value of the private property money print(xiaoqiu.get_money()) # Call set_ The money function modifies the value of the private property money xiaoqiu.set_money() print(xiaoqiu.get_money())
summary
-
Characteristics of inheritance
-
By default, a subclass has all the properties and methods of its parent class
-
Subclasses override methods and properties with the same name as the parent class
-
Subclasses call methods and properties with the same name as the parent class
-
-
The super() method calls the parent class method quickly
-
Private rights
-
Properties and methods that cannot be inherited to subclasses need to add private permissions
-
grammar
class Class name(): # Private property __Attribute name = value # Private method def __Function name(self): code
-
Object oriented - other
Three characteristics of object oriented
-
encapsulation
-
The operation of writing properties and methods into a class is encapsulation
-
Encapsulation can add private permissions to properties and methods
-
-
inherit
-
The subclass inherits all the properties and methods of the parent class by default
-
Subclasses can override parent class properties and methods
-
-
polymorphic
-
Different objects are passed in to produce different results
-
polymorphic
Understanding polymorphism
Polymorphism means that a class of things has multiple forms (an abstract class has multiple subclasses, so the concept of polymorphism depends on inheritance).
-
Definition: polymorphism is a way of using objects. Subclasses override parent methods and call the same parent methods of different subclass objects to produce different execution results
-
Benefits: flexible call, with polymorphism, it is easier to write general code and make general programming to adapt to the changing needs!
-
Implementation steps:
-
Define the parent class and provide public methods
-
Define subclasses and override parent methods
-
By passing subclass objects to the caller, you can see that different subclasses have different execution effects
-
Experience polymorphism
class Dog(object): def work(self): # The parent class provides uniform methods, even empty methods print('Play wherever you mean...') class ArmyDog(Dog): # Inherit Dog class def work(self): # Subclasses override methods with the same name as parent classes print('follow up the enemy...') class DrugDog(Dog): def work(self): print('Trace drugs...') class Person(object): def work_with_dog(self, dog): # Pass in different objects and execute different codes, that is, different work functions dog.work() ad = ArmyDog() dd = DrugDog() daqiu = Person() daqiu.work_with_dog(ad) daqiu.work_with_dog(dd)
Class properties and instance properties
Class properties
Setting and accessing class properties
-
Class attribute is the attribute owned by the class object, which is shared by all instance objects of the class.
-
Class properties can be accessed using class objects or instance objects.
class Dog(object): tooth = 10 wangcai = Dog() xiaohei = Dog() print(Dog.tooth) # 10 print(wangcai.tooth) # 10 print(xiaohei.tooth) # 10
Advantages of class properties
-
Class properties are defined when a recorded item of data is always consistent.
-
Instance properties require each object to open up a separate memory space for recording data, while class properties are shared by the whole class, occupying only one memory, which saves more memory space.
Modify class properties
Class properties can only be modified through class objects, not instance objects. If class properties are modified through instance objects, it means that an instance property is created.
class Dog(object): tooth = 10 wangcai = Dog() xiaohei = Dog() # Modify class properties Dog.tooth = 12 print(Dog.tooth) # 12 print(wangcai.tooth) # 12 print(xiaohei.tooth) # 12 # You cannot modify properties through objects. If you do, you will actually create an instance property wangcai.tooth = 20 print(Dog.tooth) # 12 print(wangcai.tooth) # 20 print(xiaohei.tooth) # 12
Instance properties
class Dog(object): def __init__(self): self.age = 5 def info_print(self): print(self.age) wangcai = Dog() print(wangcai.age) # 5 # print(Dog.age) # Error: instance property cannot be accessed through class wangcai.info_print() # 5
Class methods and static methods
Class method
Class method characteristics
-
The decorator @ classmethod needs to be used to identify it as a class method. For a class method, the first parameter must be a class object. Generally, cls is used as the first parameter.
Class method usage scenario
-
When class objects need to be used in methods (such as accessing private class properties, etc.), class methods are defined
-
Class methods are generally used in conjunction with class properties
class Dog(object): __tooth = 10 @classmethod def get_tooth(cls): return cls.__tooth wangcai = Dog() result = wangcai.get_tooth() print(result) # 10
Static method
Static method characteristics
-
It needs to be decorated through the decorator @ staticmethod. Static methods do not need to pass class objects or instance objects (formal parameters do not have self/cls).
-
Static methods can also be accessed through instance objects and class objects.
Static method usage scenario
-
Static methods are defined when neither instance objects (such as instance objects and instance properties) nor class objects (such as class properties, class methods, creating instances, etc.) need to be used in methods
-
Canceling unnecessary parameter passing is helpful to reduce unnecessary memory occupation and performance consumption
class Dog(object): @staticmethod def info_print(): print('This is a dog class used to create dog instances....') wangcai = Dog() # Static methods can be accessed using both objects and classes wangcai.info_print() Dog.info_print()
summary
-
Three characteristics of object oriented
-
encapsulation
-
inherit
-
polymorphic
-
-
Class properties
-
Attributes belonging to class objects, which are common to all objects
-
-
Instance properties
-
Class method
@classmethod def xx(): code
-
Static method
@staticmethod def xx(): code
abnormal
Understand exceptions
When an error is detected, the interpreter cannot continue to execute. Instead, some error prompts appear, which is the so-called "exception".
For example, open a nonexistent file in r mode.
open('test.txt', 'r')
Abnormal writing
grammar
try: Possible error codes except: Code to execute if an exception occurs
Quick experience
Requirement: try to open the file in r mode. If the file does not exist, open it in w mode.
try: f = open('test.txt', 'r') except: f = open('test.txt', 'w')
Catch specified exception
grammar
try: Possible error codes except Exception type: Code executed if the exception type is caught
experience
try: print(num) except NameError: print('There are errors')
be careful:
-
If the exception type of the code you are trying to execute is inconsistent with the exception type you are trying to catch, you cannot catch an exception.
-
Generally, there is only one line of code to try to execute below try.
Catch multiple specified exceptions
When capturing multiple exceptions, you can put the name of the exception type to be captured after exception and write it in tuple.
try: print(1/0) except (NameError, ZeroDivisionError): print('There are errors')
Capture exception description information
try: print(num) except (NameError, ZeroDivisionError) as result: print(result)
Catch all exceptions
Exception is the parent of all program exception classes.
try: print(num) except Exception as result: print(result)
Abnormal else
else represents the code to execute if there are no exceptions.
try: print(1) except Exception as result: print(result) else: print('I am else,It is the code executed when there is no exception')
finally of exception
finally indicates the code to be executed regardless of whether there is an exception, such as closing a file.
try: f = open('test.txt', 'r') except Exception as result: f = open('test.txt', 'w') else: print('Nothing unusual. I'm so happy') finally: f.close()
Exception passing
Experience exception delivery
Requirements:
1. Try to open test. In read-only mode Txt file. If the file exists, read the file content. If the file does not exist, prompt the user.
2. Read content requirements: try to read the content circularly. If the user accidentally terminates the program during reading, exception will catch the exception and prompt the user.
import time try: f = open('test.txt') try: while True: content = f.readline() if len(content) == 0: break time.sleep(2) print(content) except: # If an exception occurs during the reading of the file, it will be caught # For example, press ctrl+c print('Reading data terminated unexpectedly') finally: f.close() print('Close file') except: print("There is no such file")
Custom exception
In Python, the syntax for throwing custom exceptions is raise exception class object.
Requirement: if the password length is insufficient, an exception will be reported (if the user enters the password, if the length is less than 3 digits, an error will be reported, that is, a user-defined exception will be thrown and caught).
# Custom Exception class, inheriting Exception class ShortInputError(Exception): def __init__(self, length, min_len): self.length = length self.min_len = min_len # Sets the description of the exception thrown def __str__(self): return f'The length you entered is{self.length}, Not less than{self.min_len}Characters' def main(): try: con = input('Please input a password:') if len(con) < 3: raise ShortInputError(len(con), 3) except Exception as result: print(result) else: print('The password has been entered') main()
summary
-
Exception syntax
try: Possible exception codes except: Code to execute if an exception occurs else: No code executed abnormally finally: Code to execute whether or not there is an exception
-
Catch exception
except Exception type: code except Exception type as xx: code
-
Custom exception
# 1. Custom exception class class Exception class name(Exception): code # Sets the description of the exception thrown def __str__(self): return ... # 2. Throw an exception raise Exception class name() # Catch exception except Exception...
Modules and packages
Module
A python module is a python file that is written in py ends with Python object definitions and python statements.
Modules can define functions, classes and variables, and modules can also contain executable code.
Import module
How to import modules
-
import module name
-
from module name import function name
-
from module name import*
-
import module name as alias
-
from module name import function name as alias
Detailed introduction of import method
import
-
grammar
# 1. Import module import Module name import Module name 1, Module name 2... # 2. Call function Module name.Function name()
-
experience
import math print(math.sqrt(9)) # 3.0
from..import..
-
grammar
from Module name import Function 1, Function 2, Function 3...
-
experience
from math import sqrt print(sqrt(9))
from .. import *
-
grammar
from Module name import *
-
experience
from math import * print(sqrt(9))
as definition alias
-
grammar
# Module definition alias import Module name as alias # Feature definition alias from Module name import function as alias
-
experience
# Module alias import time as tt tt.sleep(2) print('hello') # Feature alias from time import sleep as sl sl(2) print('hello')
Production module
In Python, each Python file can be used as a module, and the name of the module is the name of the file. That is, the custom module name must conform to the identifier naming rules.
Definition module
Create a new Python file named my_module1.py and define the testA function.
def testA(a, b): print(a + b)
Test module
In actual development, when a developer writes a module, in order to make the module achieve the desired effect in the project, the developer will add some test information to the py file, For example, in my_module1.py file.
def testA(a, b): print(a + b) testA(1, 1)
At this time, whether the current file or other files that have imported the module will automatically call the testA function when running.
The solution is as follows:
def testA(a, b): print(a + b) # This function is called only in the current file, and the other functions do not match the testA function call. if __name__ == '__main__': testA(1, 1)
Call module
import my_module1 my_module1.testA(1, 1)
matters needing attention
If you use from import .. Or from Import * when importing multiple modules, and there is a function with the same name in the module. When the function with the same name is called, the function of the later imported module is called.
-
experience
# Module 1 code def my_test(a, b): print(a + b) # Module 2 code def my_test(a, b): print(a - b) # Import module and call function code from my_module1 import my_test from my_module2 import my_test # my_ The test function is a function in module 2 my_test(1, 1)
Module positioning sequence
When importing a module, the Python parser searches the module location in the following order:
-
current directory
-
If it is not in the current directory, Python searches each directory under the shell variable PYTHONPATH.
-
If none is found, Python looks at the default path. Under UNIX, the default path is generally / usr/local/lib/python/
The module search path is stored in sys. Of the system module Path variable. The variable contains the current directory, PYTHONPATH and the default directory determined by the installation process.
-
be careful
-
Do not duplicate your own file name with the existing module name, otherwise the module function cannot be used
-
When using the from module name import function, if the function name is repeated, the last defined or imported function is called.
-
__all__
If a module file has__ all__ Variable. When importing with from xxx import *, only the elements in this list can be imported.
-
my_module1 module code
__all__ = ['testA'] def testA(): print('testA') def testB(): print('testB')
-
File code of the import module
from my_module1 import * testA() testB()
package
Packages organize related modules together, that is, put them in the same folder, and create a folder named__ init__.py file, then this folder is called a package.
Make package
[New] - [Python Package] - enter package name - [OK] - create a New function module (associated module).
Note: after creating a new package, it will be automatically created inside the package__ init__.py file, which controls the import behavior of the package.
Quick experience
-
New package mypackage
-
New module in package: my_module1 and my_module2
-
The codes in the module are as follows
# my_module1 print(1) def info_print1(): print('my_module1')
# my_module2 print(2) def info_print2(): print('my_module2')
Import package
Method 1
import Package name.Module name Package name.Module name.target
experience
import my_package.my_module1 my_package.my_module1.info_print1()
Method 2
Note: must be in__ init__. Add to py file__ all__ = [] controls the list of modules allowed to be imported.
from Package name import * Module name.target
experience
from my_package import * my_module1.info_print1()
summary
-
Import module method
import Module name from Module name import target from Module name import *
-
Import package
import Package name.Module name from Package name import *
-
__ all__ = []: list of modules or functions allowed to be imported
Previous highlights:
I modified ban Hua's boot password in Python and found her secret after logging in again!