Python Programming From Introduction To Practice
Python Programming From Introduction To Practice
Controller is the command system of computer, which is used to control the operation of oth C - 742
2. Arithmetic unit
xml - 735
An arithmetic unit is the operation function of a computer. It is used for arithmetic opera less - 697
ps: controller + calculator = cpu, cpu is equivalent to human brain
github - 694
3. Memory
External storage (such as disk), which is equivalent to a notebook, is used to store data permanent
4. input device
Input device is a tool for calculating and receiving external input data, such as keyboard
5. output device
Output device is a tool for computer to output data, such as display and printer, which is
ps: memory such as memory and disk are both input devices and output devices, collectively referred
The three core hardware are CPU, memory and hard disk.
The program is stored in the hard disk first. The program runs by loading the code from the hard disk into the memory, and
then the cpu reads the instructions from the memory.
1, Application software (such as qq, word, storm video, we learn python to develop application soft
2, The operating system, a bridge between the application software and hardware of the operating sy
operating system
computer hardware
#Machine language
The instructions described by binary code 0 and 1 are called machine instructions. Because the
To write a program in machine language, the programmer should first memorize all the instructio
Machine language is understood and used by microprocessors. There are up to 100000 machine lang
g
...
...
#Integration example
The program can be understood by the computer without any obstacles, run directly, and perform eff
assembly language
Assembly language only uses an English label to represent a group of binary instructions. There is no doubt that assembly
language is a progress compared with machine language, but the essence of assembly language is still direct operation of
hardware, so assembly language is still relatively low-level / low-level language, close to computer hardware
#Assembly language
The essence of assembly language is the same as that of machine language, which is directly operat
For the assembled hello world, to print a sentence of hello world, you need to write more than ten
; hello.asm
; exit program
Compared with machine language, it is relatively simple and efficient to write programs with Engli
It is still a direct operation of hardware. Compared with machine language, the complexity is sligh
It also depends on specific hardware and has poor cross platform performance
high-level language
From the perspective of human (slave owner), high-level language is to speak human language, that is, to write programs
with human characters, while human characters are sending instructions to the operating system, rather than directly
operating the hardware. Therefore, high-level language deals with the operating system. The high-level language here
refers to the high-level, developers do not need to consider the hardware details, so the development efficiency can be
greatly improved, But because high-level language is far away from hardware and closer to human language, which can
be understood by human beings, and computers need to be understood through translation, so the execution efficiency will
be lower than low-level language.
According to the different ways of translation, there are two kinds of high-level languages
Similar to Google translation, it compiles all code of the program into binary instructions that can be recognized by the
computer, and then the operating system will directly operate the hardware with the compiled binary instructions, as
follows
Compilation refers to "translating" the program source code into the target code (i.e. machine lan
Therefore, the target program can be executed independently from its language environment, which is
Once the application needs to be modified, it must first modify the source code, then recompile and
However, if there is only target file but no source code, it will be inconvenient to modify. So the
Compiled code is translated for a certain platform. The results of current platform translation ca
#Others
The compiler translates the source program into the target program and saves it in another file. Th
Most software products are distributed to users in the form of target program, which is not only co
C. C + +, Ada and Pascal are all compiled and implemented
In the implementation of interpretive language, the translator does not generate the target machin
This kind of intermediate code is different from the machine code. The interpretation of the interm
Software interpreters often lead to low execution efficiency.
Code operation depends on the interpreter. Different platforms have corresponding versions of the
#Others
For an interpreted Basic language, a special interpreter is needed to interpret and execute Basic
This interpretative language translates every time it is executed, so it is inefficient. Generally
For example: Tcl, Perl, Ruby, VBScript, JavaScript, etc
Java is a special programming language. Java programs also need to be compiled, but they are not di
The bytecode is then interpreted on the Java virtual machine.
summary
To sum up, choose different programming languages to develop application program comparison
#1. Execution efficiency: machine language > assembly language > high level language (compiled > in
#2. Development efficiency: machine language < assembly language < high level language (compiled <
#3. Cross platform: interpretive type has a strong cross platform type
Python advocates beauty, clarity and simplicity. It is an excellent and widely used language
# Jython
JPython The interpreter uses JAVA Prepared by python The interpreter can directly Python Code com
# IPython
IPython Is based on CPython An interactive interpreter on top, that is, IPython It's just an enha
CPython use>>>As a prompt, and IPython use In [No]:As a prompt.
# PyPy
PyPy yes Python Developers for better Hack Python But with Python Realized by language Python Int
# IronPython
IronPython and Jython Similar, but IronPython It's running at Microsoft.Net On platform Python T
# 1. Open a text editing tool, write the following code, and save the file, where the path of the
print('hello world')
Summary:
#1. In interactive mode, code execution results can be obtained immediately, and debugging programs
#2. If you want to permanently save your code, you must write it to a file
#3. In the future, we mainly need to open the interactive mode to debug some code and verify the r
5.2 notes
Before we formally learn python syntax, we must introduce a very important syntax in advance: Annotation
1. What is annotation
Annotation is the explanation of the code. The content of annotation will not be run as code
2. Why comment
1. Single line comments are marked with a ා, which can be directly above or directly behind the co
2. Multiline comments can use three pairs of double quotes "" "" ""
1. You don't need to annotate all of them. You just need to annotate the parts that you think are i
Problem 1: we learned that a python program needs to operate at least two software from development to operation
2. Open cmd and enter the command to execute the pyton program
Problem 2: in the development process, there is no code prompt and error correction function
To sum up, if a tool can integrate the functions of n software, code prompt and error correction, i
stay test.py Write the code in. You can use the tab key to complete the beginning of the keyword, and there will be an error
prompt for the code
Bivariate
1 Wh t i bl ?
1, What are variables?
#Variable is the variable that can be changed. Quantity refers to the state of things, such as peop
#The essence of program execution is a series of state changes. Change is the direct embodiment of
name = 'harry' # Write down the person's name as' harry '
When the interpreter executes the code defined by the variable, it will apply for memory space to store the variable value,
and then bind the memory address of the variable value to the variable name. Take age=18 as an example, as shown in
the following figure
# The value can be referenced by the variable name, and we can print it with the function of pri
print(age) # Find the value 18 through the variable name age, then execute print(18), output: 18
#Naming conventions
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec
Age = 18. It is strongly recommended not to use Chinese names
# Style 1: hump
AgeOfTony = 56
NumberOfStudents = 80
# Style 2: pure lowercase underline (in python, this style is recommended for variable name nami
age_of_tony = 56
number_of_students = 80
It reflects the unique number of variables in memory. Different memory addresses and IDS must be d
#2,type
#3,value
Variable value
3, Constant
3.1 what is constant?
Constants are quantities that do not change during program operation
Binary type
2.1 int integer
2.1.1 function
It is used to record the integer related status of person's age, year of birth, number of students, etc
2.1.2 definitions
age=18
birthday=1990
student_count=48
2.2 float
2.2.1 function
It is used to record the decimal related status of people's height, weight, salary, etc
2.2.2 definition
height=172.3
weight=103.5
salary=15000.89
>>> a = 1
>>> b = 3
>>> c = a + b
>>> c
2. Compare sizes
>>> x = 10
>>> y = 11
>>> x > y
False
3.2 definitions
name = 'harry'
sex = 'male'
With single quotation mark, double quotation mark and multiple quotation marks, you can define a string, which is
essentially indistinguishable, but
MSG = "my name is Tony, I'm 18 years old!" (inner layer has single quotation mark, outer layer nee
#2. Multiple quotes can write multiple lines of strings
msg = '''
There are only two kinds of people in the world. For example, when a bunch of grapes arrive
As usual, the first kind of people should be optimistic, because every one he eats is the b
But the fact is just the opposite, because the second kind of people still have hope, the f
'''
3.3 use
Numbers can be added, subtracted, multiplied, and divided. What about strings? Yes, but you can onl
>>> name = 'tony'
'tony18'
't t t t t '
'tonytonytonytonytony'
Four list
4.1 function
If we need to use a variable to record the names of multiple students, it is impossible to use the number type. The string
type can be recorded, for example
stu_names = 'Zhang Sanli, Si Wangwu', but the purpose of saving is to get the name of the second student. At this time, if
you want to get the name of the second student, it's quite troublesome. The list type is specially used to record the values
of multiple attributes of the same kind (such as the names of multiple students in the same class, multiple hobbies of the
same person, etc.), and the access is very convenient
4.2 definitions
4.3 use
# 1. The list type uses an index to correspond to the value, and the index represents the positio
>>> stu_names=['Zhang San','Li Si','Wang Wu']
>>> stu_names[0]
'Zhang San'
>>> stu_names[1]
'Li Si'
>>> stu_names[2]
'Wang Wu'
>>> students_info=[['tony',18,['jack',]],['jason',18,['play','sleep']]]
>>> students_info[0][2][0] #Take out the first student 's first hobby
'play'
5.2 definitions
>>> person_info={'name':'tony','age':18,'height':185.3}
5.3 use
# 1. The dictionary type uses the key to correspond to the value. The key can describe the value
>>> person_info={'name':'tony','age':18,'height':185.3}
>>> person_info['name']
'tony'
>>> person_info['age']
18
>>> person_info['height']
185.3
>>> students=[
... {'name':'tony','age':38,'hobbies':['play','sleep']},
... {'name':'jack','age':18,'hobbies':['read','sleep']},
... {'name':'rose','age':58,'hobbies':['music','read','sleep']},
... ]
'sleep'
Six bool
6.1 function
It is used to record the true and false states
6.2 definitions
6.3 use
It is usually used as a condition of judgment. We will use it in if judgment
From the logic level alone, we define variables to store variable values for later use. To obtain v
There is no doubt that the application and recovery of memory space are very energy consuming, and
#1. The relationship between variable name and value memory address is stored in the stack area
#2. The variable values are stored in the heap area, and the contents of the heap area are recycled
Indirect reference refers to the memory address that can be reached by further reference after starting from stack area to
heap area.
as
l2 = [20, 30] # The list itself is directly referenced by the variable name l2, and the containe
x = 10 # Value 10 is directly referenced by variable name x
l1 = [x, l2] # The list itself is directly referenced by the variable name l1, and the contained
Variable value 18 is associated with a variable name age, which is called reference count 1
Reference count increase:
m=age (when the memory address of age is given to m, m and age are all associated with 18, so the reference count of
variable value 18 is 2)
age=10 (the name is disassociated from the value 18, and then associated with 3. The reference count of the variable
value 18 is 1)
del m (del means to disassociate variable name x from variable value 18. At this time, the reference count of variable 18 is
0)
Once the reference count of value 18 changes to 0, the memory address occupied by it should be recycled by the
interpreter's garbage collection mechanism
A fatal weakness of the reference counting mechanism is circular reference (also known as cross reference)
# As follows, we define two lists, namely list 1 and list 2 for short. Variable name l1 points to
>>> l1=['xxx'] # List 1 is referenced once, and the reference count of list 1 changes to 1
>>> l2=['yyy'] # List 2 is referenced once, and the reference count of list 2 changes to 1
>>> l1.append(l2) # Append Listing 2 to l1 as the second element, and the reference
>>> l2.append(l1) # Append Listing 1 to l2 as the second element, and the reference
>>> l1
>>> l2
>>> l1[1][1][0]
'xxx'
python introduces "mark clear" and "generational recycle" to solve the problem of circular reference and low efficiency of
reference count
Container objects (such as list, set, dict, class, instance) can contain references to other objects, so circular references
may be generated. The mark clear count is to solve the problem of circular references.
The method of mark / clear algorithm is that when the available memory space of the application is exhausted, the whole
program will be stopped, and then two works will be carried out, the first is the mark, the second is the clear
Generation:
The core idea of generational recycling is: in the case of multiple scans, there is no recovered variable. The gc mechanism
will think that this variable is a common variable, and the frequency of gc scanning for it will be reduced. The specific
implementation principle is as follows:
Generation refers to the classification of variables into different levels (i.e. different generati
The newly defined variable is placed in the new generation level, assuming that the new generation
Recycling:
For example, as soon as a variable is transferred from the new generation to the youth generation,
There is no doubt that if there is no generational recycling, that is, the reference counting mecha
To sum up
In the background of garbage cleaning and memory freeing, garbage collection mechanism allows gene
1.3.1 input:
#In python3, the input function will wait for the user's input. Any content entered by the user wil
>>>Username = input ('Please enter your username: ')
#Knowledge:
#1. There is a raw in python2_ The input function is as like as two peas in the python3 input.
#2. There is also an input function in python2, which requires the user to input a clear data type,
>>>L = input ('whatever type of input will be saved as: ')
>>> type(l)
<type 'list'>
hello world
# The default print function has an end parameter. The default value of this parameter is "\ n"
print("aaaa",end='')
print("bbbb",end='&')
print("cccc",end='@')
To replace some contents of a string and then output it is to format the output.
We often output content with some fixed format, such as: 'hello dear XXX! Your monthly call fee is XXX, and the balance is
xxx '. What we need to do is to replace XXX with specific content.
>>> print('dear%s Hello! you%s The monthly call charge is%d,The balance is%d' %('tony',12,103,11
//Hello, dear tony! Your call charge in December is 103, and the balance is 11
age = input('your age: ') #User input 18 will be saved as string 18, unable to pass to% d
# Exercise 2: the user enters the name, age, work, hobbies, and then prints them into the follow
------------ info of Tony -----------
Name : Tony
Age : 22
Sex : male
Job : Teacher
If we want to assign the same value to multiple variable names at the same time, we can do this
>>> z=10
>>> y=z
>>> x=y
>>> x,y,z
>>> x=y=z=10
>>> x,y,z
>>> temp=m
>>> temp=m
>>> m=n
>>> n=temp
>>> m,n
(20, 10)
>>> m=10
>>> n=20
>>> m,n
(20, 10)
If we want to take out multiple values in the list and assign them to multiple variable names in turn, we can do this
>>> nums=[11,22,33,44,55]
>>>
>>> a=nums[0]
>>> b=nums[1]
>>> c=nums[2]
>>> d=nums[3]
>>> e=nums[4]
>>> a,b,c,d,e
>>> a,b,c,d,e=nums # nums contains multiple values, just like a compressed package. It is named a
>>> a,b,c,d,e
Note that for the above decompression and assignment, the number of variable names on the left side of the equal sign
must be the same as the number of values on the right side, otherwise an error will be reported
>>> a,b=nums
>>> a,b,c,d,e,f=nums
But if we only want to take a few values of the head and tail, we can use*_ matching
>>> a,b,*_=nums
>>> a,b
(11, 22)
ps: string, dictionary, tuple and set type all support decompression and assignment
You can use and to connect multiple conditions, which will be judged from left to right. Once a condition is False, you don't
need to judge from right. You can immediately determine that the final result is False. Only when the results of all
conditions are True, the final result is True.
>>> 2 > 1 and 1 != 1 and True and 3 > 2 # After judging the second condition, it will end immedia
False
2.4.2 consecutive or
You can use or to connect multiple conditions, which will be judged from left to right. Once a condition is True, you don't
need to judge from right. You can immediately determine that the final result is True. Only when the results of all conditions
are False, the final result is False
are False, the final result is False
>>> 2 > 1 or 1 != 1 or True or 3 > 2 # When the first condition is judged, it ends immediately, a
True
False
#2. It's best to use parentheses to distinguish priorities, which means the same as above
'''
(1) The highest priority of not is to reverse the result of the condition immediately following, so
(2) If all statements are connected with and, or all statements are connected with or, then the cal
(3) If there are both and and or in the statement, first enclose the left and right conditions of a
'''
False
#3. Short circuit operation: once the result of logical operation can be determined, the current ca
>>> 10 and 0 or '' and 0 or 'abc' or 'egon' == 'dsb' and 333 or 10 > 4
>>> (10 and 0) or ('' and 0) or 'abc' or ('egon' == 'dsb' and 333) or 10 > 4
Back: 'abc'
>>> 1 or 3
>>> 1 and 3
>>> 0 and 2 or 1
>>> 0 and 2 or 1 or 4
False
Note: Although the following two judgments can achieve the same effect, we recommend the second format, because the
semantics of not in is more explicit
True
True
#1. The same ID and memory address means the same type and value
#2. The same value type must be the same, but the id may be different, as follows
>>> id(x),id(y) # x and y have different IDS, but they have the same values
(4327422640, 4327422256)
True
>>> x is y # is compares the id. the values of x and y are the same, but the id can be different
False
So there must be a corresponding mechanism in the program to control the judgment ability of the computer
Use the if keyword to implement the branch structure. The complete syntax is as follows
Code 1
Code 2
......
elif condition 2: if the result of condition 2 is True, execute in sequence: Code 3, code 4
Code 3
Code 4
......
elif condition 3: if the result of condition 3 is True, execute in sequence: code 5, code 6
Code 5
Code 6
......
Code 7
Code 8
......
#Note:
#1. python uses the same indentation (4 spaces for an indentation) to identify a group of code bloc
#2. The condition can be any expression, but the execution result must be of boolean type
#2.1, None, 0, empty (empty string, empty list, empty dictionary, etc.) the Boolean value co
#2.2. The rest are True
Case 1:
age_of_girl=31
print('Hello, auntie')
Case 2:
If: the age of a woman is more than 30, then: call aunt, otherwise: call Miss
age_of_girl=18
print('Hello, auntie')
else:
print('Hello, miss')
Case 3:
If a woman's age is more than 18 and less than 22 years old, her height is more than 170, her weight is less than 100 and
she is beautiful, then: to express her love, otherwise: to call her aunt**
age_of_girl=18
height=171
weight=99
is_pretty=True
if age_of_girl >= 18 and age_of_girl < 22 and height > 170 and weight < 100 and is_pretty == True
print('Confession...')
else:
print('Hello, auntie')
Case 4:
score=input('>>: ')
score=int(score)
print('excellent')
print('good')
print('ordinary')
else:
print('Very bad')
Case 5: if nesting
#Otherwise: print...
age_of_girl=18
height=171
weight=99
is_pretty=True
success=False
if age_of_girl >= 18 and age_of_girl < 22 and height > 170 and weight < 100 and is_pretty == True
if success:
else:
else:
print('Hello, auntie')
else:
Exercise 2:
#!/usr/bin/env python
'''
'''
if name == 'egon':
print('Super administrator')
print('General administrator')
print('Business Director')
else:
print('Ordinary users')
So there must be a corresponding mechanism in the program to control the computer to have the ability of human beings
to do things in this cycle
In python, there are two circulation mechanisms: while and for. The while loop is called conditional loop. The syntax is as
follows
while condition:
Code 1
Code 2
Code 3
Step 2: judge the condition again after execution. If the condition is True, execute again: Code 1
#The basic logic of the user authentication program is to receive the user name and password inp
username = "jason"
password = "123"
print("Login succeeded")
else:
#Generally, in case of authentication failure, the user will be required to re-enter the user nam
username = "jason"
password = "123"
# First verification
print("Login succeeded")
else:
# Second verification
print("Login succeeded")
else:
# Third verification
print("Login succeeded")
else:
#Even if you are Xiaobai, do you think it's too low? You have to modify the function three times
#Even if you are Xiaobai, do you think it s too low? You have to modify the function three times
#So how to make a program repeat a piece of code many times without writing duplicate code? Loop
username = "jason"
password = "123"
count = 0
print("Login succeeded")
else:
count += 1
After using the while loop, the code is indeed much simpler, but the problem is that the user can not end the loop after
entering the correct user name and password, so how to end the loop? This needs to use break!
username = "jason"
password = "123"
count = 0
print("Login succeeded")
else:
count += 1
If there are many layers nested in the while loop, to exit each layer loop, you need to have a break in each layer loop
username = "jason"
password = "123"
count = 0
print("Login succeeded")
if cmd == 'quit':
break # Used to end the layer cycle, i.e. the second layer cycle
break # Used to end the layer cycle, i.e. the first layer cycle
else:
count += 1
For nested multi-layer while loops, if our purpose is clear that we want to directly exit the loops of all layers in a certain
layer, there is a trick, that is, let all the conditions of the while loop use the same variable, the initial value of the variable is
True, once the value of the variable is changed to False in a certain layer, the loops of all layers will end
username = "jason"
password = "123"
count = 0
tag = True
while tag:
print("Login succeeded")
while tag:
if cmd == 'quit':
tag = False # tag becomes False, and the conditions of all while loops become Fa
break
break # Used to end the layer cycle, i.e. the first layer cycle
else:
count += 1
break means to end this layer's cycle, while continue is used to end this cycle and directly enter the next cycle
number=11
while number>1:
number -= 1
if number==7:
continue # End this loop, that is, the code after continue will not run, but directly ent
print(number)
After the while loop, we can follow the else statement. When the while loop executes normally and is not interrupted by
break, it will execute the statement after else. Therefore, we can use else to verify whether the loop ends normally
count = 0
count += 1
print("Loop",count)
else:
//output
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
//The loop is running normally. It is not interrupted by break, so this line of code is executed
count = 0
count += 1
if count == 3:
break
print("Loop",count)
else:
//output
Loop 1
Loop 2
-----out of while loop ------ #Since the loop is interrupted by break, the output statement afte
Exercise 1:
Find the maximum multiple of the number 7 between 1 and 100 (the result is 98)
number = 100
if number %7 == 0:
print(number)
break
number -= 1
Exercise 2:
age=18
count=0
while count<3:
count+=1
guess = int(input(">>:"))
else:
The second way to implement the loop structure is the for loop. All the things that the for loop can do can be realized by
the while loop. The reason why the for loop is used is that the use of the for loop is more concise than that of the while
loop when it takes values (i.e. traversal values),
for variable name in iteratable object: ා at this time, you only need to know that the iteratable
Code one
Code two
...
#Example 1
print(item)
#Operation results
b
b
#Step 1: read out the first value from the list ['a','b','c '] and assign it to item (item ='a'),
#Step 2: read out the second value from the list ['a','b','c '] and assign it to the item (item ='
#Step 3: repeat the above process until the values in the list are read out
print(count)
count = 0
print(count)
count += 1
# Complex version: while loop can traverse the dictionary, which will be described in detail in t
*****
*****
*****
for i in range(3):
for j in range(5):
print("*",end='')
Note: break and continue can also be used for loops, with the same syntax as while loops
Exercise 1:
for i in range(1,10):
for j in range(1,i+1):
print()
Exercise 2:
Print pyramid
# analysis
'''
#max_level=5
# mathematical expression
*Number=2*current_level-1
'''
# realization:
max_level=5
for i in range(max_level-current_level):
for j in range(2*current_level-1):
print()
# 1. Definition:
# 1.1 int can directly convert a string composed of pure integers to integers. If it contains any
>>> s = '123'
>>> res,type(res)
>>> int('12.3') # Error demonstration: the string contains a non integer symbol
>>> bin(3)
'0b11'
>>> oct(9)
'0o11'
>>> hex(17)
'0x11'
>>> int('0b11',2)
>>> int('0o11',8)
>>> int('0x11',16)
17
>>> s = '12.3'
>>> res=float(s)
>>> res,type(res)
2.3 use
The number type is mainly used for mathematical operation and comparison operation, so there is no built-in method to
master except for the combination of number type and operator
Three strings
3.1 definition:
# Definition: include a string of characters in single quotation mark \ double quotation mark \ t
name1 = 'jason' # Nature: name = str('content in any form ')
# Data type conversion: str() can convert any data type to a string type, for example
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
3.3 use
3.3.1 priority operation
>>> str1[6]
>>> str1[-4]
# 1.3 for str, the value can only be taken according to the index and cannot be changed
# 2. Slice (look at the head and ignore the tail, step size)
# 2.1 ignore head and tail: take out all characters with index from 0 to 8
>>> str1[0:9]
hello pyt
# 2.2 step size: 0:9:2. The third parameter 2 represents step size. It will start from 0 and acc
>>> str1[0:9:2]
hlopt
!nohtyp olleh
# 3. Length len
# 3.1 get the length of the string, that is, the number of characters. All the characters in quot
>>> len(str1) # Spaces are also characters
13
True
True
# 5.strip remove the characters specified at the beginning and end of the string (remove space by
# 5.1 no characters are specified in brackets. The first and last blank characters (spaces, n, t
>>> str1 = ' life is short! '
>>> str1.strip()
life is short!
>>> str2.strip('*')
tony
# 6. split
# 6.1 no characters are specified in brackets, and spaces are used as segmentation symbols by def
>>> str3='hello world'
>>> str3.split()
['hello', 'world']
# 6.2 if the separator character is specified in the bracket, the string will be cut according to
>>> str4 = '127.0.0.1'
>>> str4.split('.')
['127', '0', '0', '1'] # Note: the result of split cutting is the list data type
# 7. Circulation
>>> for line in str5: # Extract each character in the string in turn
... print(line)
...
//this
//day
//you
//good
//Do you
'tony'
tony***
**tony
2. lower(),upper()
my name is tony!
MY NAME IS TONY!
3. startswith,endswith
# Startswitch() determines whether the string starts with the character specified in parentheses
>>> str3.startswith('t')
True
>>> str3.startswith('j')
False
# Endswitch() determines whether the string ends with the character specified in parentheses, and
>>> str3.endswith('jam')
True
>>> str3.endswith('tony')
False
Before we used% s to format and output strings, when passing values, we must strictly follow the position to correspond
to% s one by one, while the built-in method format of strings provides a position independent way of passing values
Case:
# format parentheses can completely disrupt the order when passing parameters, but they can stil
>>> str4 = 'my name is {name}, my age is {age}!'.format(age=18,name='tony')
>>> str4
>>> str4
# Similar to the usage of% s, the passed in value will correspond to {} one by one according to t
>>> str4 = 'my name is {}, my age is {}!'.format('tony', 18)
>>> str4
# Take the values passed in by format as a list, and then use {index} to get values
>>> str4
>>> str4
>>> str4
5.split,rsplit
# Split will split the string from left to right, and you can specify the number of times to cut
>>> str5='C:/a/b/c/d.txt'
>>> str5.split('/',1)
['C:', 'a/b/c/d.txt']
# rsplit is just the opposite of split. It cuts from right to left. You can specify the number of
>>> str5='a|b|c'
>>> str5.rsplit('|',1)
['a|b', 'c']
6. join
# Take multiple strings from the iteratable object, and then splice them according to the specif
'%' j i ('h ll ') # T k lti l t i f th t i 'h ll ' d li th ith% t
>>> '%'.join('hello') # Take multiple strings from the string 'hello' and splice them with% as t
'h%e%l%l%o'
>>> '|'.join(['tony','18','read']) # Extract multiple strings from the list and splice them wit
'tony|18|read'
7. replace
>>> str7 = 'my name is tony, my age is 18!' # Change tony's age from 18 to 73
>>> str7 = str7.replace('18', '73') # Syntax: replace('old content ',' new content ')
>>> str7
>>> str7
8.isdigit
# Judge whether the string is composed of pure numbers, and the return result is True or False
>>> str8.isdigit()
True
>>> str8.isdigit()
False
# 1.find,rfind,index,rindex,count
# 1.1 find: find the starting index of the substring from the specified range, return the number
>>> msg='tony say hello'
>>> msg.find('o',1,3) # Find the index of character o in characters with index 1 and 2 (regardle
1
# 1.2 index: the same as find, but an error will be reported if it cannot be found
# 1.4 count: count the number of times a string appears in a large string
# 2.center,ljust,rjust,zfill
>>> name='tony'
>>> name.center(30,'-') # The total width is 30, the string is displayed in the middle, not eno
-------------tony-------------
>>> name.ljust(30,'*') # The total width is 30, the string is aligned to the left, not filled w
tony**************************
>>> name.rjust(30,'*') # The total width is 30, the string is aligned to the right, not filled w
**************************tony
>>> name.zfill(50) # The total width is 50, the string is right aligned, not enough to be filled
0000000000000000000000000000000000000000000000tony
# 3.expandtabs
>>> name
tony hello
tony hello
# 4.captalize,swapcase,title
# 4.1 capitalization
>>> message.capitalize()
>>> message1.swapcase()
>>> msg.title()
#In Python 3
#isdigt:bytes,unicode
>>> num1.isdigit()
True
>>> num2.isdigit()
True
>>> num3.isdigit()
False
>>> num4.isdigit()
False
>>> num2.isdecimal()
True
>>> num3.isdecimal()
False
>>> num4.isdecimal()
False
#I snumberic:unicode , Chinese number, Roman number (no IsNumeric method for bytes type)
>>> num2.isnumeric()
True
>>> num3.isnumeric()
True
>>> num4.isnumeric()
True
>>> num5.isdigit()
False
>>> num5.isdecimal()
False
>>> num5.isnumeric()
False
'''
//Summary:
//The most commonly used is isdigit, which can judge the types of bytes and unicode, which i
//If you want to judge Chinese numbers or roman numbers, you need to use isnumeric.
'''
# 6.is others
True
False
>>> name.isidentifier()
True
True
False
False
>>> name.istitle() # Whether the initial letters of words in the string are all uppercase
False
Four lists
4.1 definition
# Definition: separate multiple values of any data type with commas within []
# Any data type that can be traversed by the for loop can be passed to list() to be converted int
>>> list('wdad') # Results: ['w ',' d ',' a ',' d ']
4.3 use
4.3.1 priority operation
# 1. Value by index memory (forward access + reverse access): can be saved or retrieved
>>> my_friends=['tony','jason','tom',4,5]
>>> my_friends[0]
tony
>>> my_friends[-1]
# 1.3 for list, the value of specified location can be modified according to index or index. Howe
>>> my_friends = ['tony','jack','jason',4,5]
>>> my_friends
# 2. Slice (look at the head and ignore the tail, step size)
# 2.1 take care of the head and ignore the tail: take out the elements with an index of 0 to 3
>>> my_friends[0:4]
# 2.2 step size: 0:4:2. The third parameter 2 represents step size. It will start from 0 and acc
>>> my_friends[0:4:2]
['tony', 'tom']
# 3. Length
>>> len(my_friends)
True
True
# 5. Add
>>> l1 = ['a','b','c']
>>> l1.append('d')
>>> l1
# 5.2 extend() adds multiple elements at the end of the list at one time
>>> l1.extend(['a','b','c'])
>>> l1
>>> l1
# 6. Delete
# 6.1 del
>>> l = [11,22,33,44]
>>> l
[11,22,44]
# 6.2 pop() deletes the last element of the list by default and returns the deleted value. You ca
>>> l = [11,22,33,22,44]
>>> res=l.pop()
>>> res
44
>>> res=l.pop(1)
>>> res
22
# 6.3 remove() indicates which element to delete with the name in parentheses. There is no retur
>>> l = [11,22,33,22,44]
>>> res=l.remove(22) # Find the element to be deleted in the first bracket from left to right
>>> print(res)
None
>>> l = [11,22,33,44]
>>> l.reverse()
>>> l
[44,33,22,11]
# 8.1 during sorting, the list elements must be of the same data type and cannot be mixed. Otherw
>>> l = [11,22,3,42,7,55]
>>> l.sort()
>>> l
[3, 7, 11, 22, 42, 55] # Sort from small to large by default
>>> l = [11,22,3,42,7,55]
>>> l.sort(reverse=True) # reverse is used to specify whether to sort falls. The default value
>>> l
# 8.2 knowledge:
# We can directly compare the size of the commonly used number types, but in fact, strings, list
>>> l1=[1,2,3]
>>> l2=[2,]
>>> l2 > l1
True
# The size between characters depends on their order in the ASCII table, and the larger the late
>>> s1='abc'
>>> s2='az'
>>> s2 > s1 # The first character of s1 and s2 does not distinguish the winner, but the second c
True
>>> l = ['A','z','adjk','hello','hea']
>>> l.sort()
>>> l
# 9. Circulation
print(line)
'tony'
'jack'
'jason'
>>> l=[1,2,3,4,5,6]
>>> l[0:3:1]
>>> l[2::-1]
>>> l[::-1]
[6, 5, 4, 3, 2, 1]
Quintuple
5.1 function
A tuple is similar to a list in that it can store multiple elements of any type. The difference is that the elements of a tuple
cannot be modified, that is, a tuple is equivalent to an immutable list, which is used to record multiple fixed and immutable
values and is only used to retrieve
# Any data type that can be traversed by the for loop can be passed to tuple() to be converted i
>>> tuple('wdad') # Result: ('w ',' d ',' a ',' d ')
# tuple() will traverse every element contained in the data type just like for loop and put it i
5.4 use
# 1. Value by index (forward + reverse): can only be fetched, cannot be modified, otherwise an e
>>> tuple1[0]
>>> tuple1[-2]
22
>>> tuple1[0:6:2]
# 3. Length
>>> len(tuple1)
True
False
# 5. Cycle
... print(line)
hhaha
15000.0
11
22
33
Six Dictionaries
6.1 definition method
# Definition: separate multiple elements with commas within {}, each of which is key:value Value
info={'name':'tony','age':18,'sex':'male'} #Essence info=dict({....})
>>> info=dict([['name','tony'],('age',18)])
>>> info
# Conversion 2: fromkeys will take each value from the tuple as a key, and then make up with None
>>> {}.fromkeys(('name','age','sex'),None)
6.3 use
6.3.1 priority operation
# 1.1 take
>>> dic = {
... }
>>> dic['name']
'xxx'
>>> dic['hobbies'][1]
'basketball'
# 1.2 for assignment, if the key does not exist in the dictionary, it will be added key:value
>>> dic
# 1.3 for assignment, if the key originally exists in the dictionary, the value corresponding to
>>> dic['name'] = 'tony'
>>> dic
# 2. Length len
>>> len(dic)
>>> 'name' in dic # Determine whether a value is the key of the dictionary
True
# 4. Delete
>>> dic.pop('name') # Delete the key value pair of the dictionary by specifying the key of the d
>>> dic
>>> dic = {'age': 18, 'hobbies': ['play game', 'basketball'], 'name': 'xxx'}
>>> dic.keys()
>>> dic.values()
>>> dic.items()
# 6. Cycle
... print(key)
...
age
hobbies
name
... print(key)
...
age
hobbies
name
... print(key)
...
18
xxx
... print(key)
...
('age', 18)
('name' 'xxx')
( name , xxx )
1. get()
>>> dic.get('k1')
'jason' # If the key exists, get the value value corresponding to the key
>>> res=dic.get('xxx') # key does not exist, no error will be reported, but no will be returned
>>> print(res)
None
>>> res=dic.get('xxx',666) # When the key does not exist, the default returned value can be set
>>> print(res)
666
2. pop()
>>> v = dic.pop('k2') # Delete the key value pair corresponding to the specified key and return
>>> dic
>>> v
'Tony'
3. popitem()
>>> item = dic.popitem() # Randomly delete a set of key value pairs and return the deleted key v
>>> dic
>>> item
('k1', 'jason')
4. update()
# Update the old dictionary with the new one, modify if there is one, and add if there is none
>>> dic.update({'k1':'JN','k4':'xxx'})
>>> dic
5. fromkeys()
>>> dic
6. setdefault()
# If the key does not exist, add a new key value pair and return the new value
>>> dic={'k1':111,'k2':222}
>>> res=dic.setdefault('k3',333)
>>> res
333
# If the key exists, no modification will be made, and the value corresponding to the existing ke
>>> dic={'k1':111,'k2':222}
>>> res=dic.setdefault('k1',666)
>>> res
111
Seven sets
7.1 function
Set, list, tuple and dict can store multiple values, but set is mainly used for: de duplication and relational operation
7.2 definitions
"""
Definition: separate multiple elements with commas in {}, and the set has the following three chara
1: Each element must be of immutable type
"""
#Note 1: the list type is the index corresponding value, and the dictionary is the key correspondin
#Note 2: {} can be used to define both dict and collection, but the elements in the dictionary must
d = {} ා default is empty dictionary
# Any data type that can be traversed by the for loop (emphasis: every value traversed must be im
>>> s = set([1,2,3,4])
>>> s1 = set((1,2,3,4))
>>> s2 = set({'name':'jason',})
>>> s3 = set('egon')
>>> s,s1,s2,s3
7.4 use
7.4.1 relation operation
We define two sets, friends and friends2, to store the names of two people's friends, and then take these two sets as
examples to explain the relationship operation of sets
The relationship between the two sets is shown in the figure below
# 1. Union / Union (|): ask all friends of two users (only one duplicate friend is left)
{'kevin', 'zero'}
{'ricky', 'Jy'}
# 4.Symmetric difference set(^) # Ask the unique friends of two users (that is, remove the shared
>>> friends1 ^ friends2
{'kevin', 'zero', 'ricky', 'Jy'}
False
True
True
False
False
# 7. Subsets
True
True
#2. The set itself is out of order. After de duplication, the original order cannot be preserved
An example is as follows
>>> l=['a','b',1,'a','a']
>>> s=set(l)
{'b', 'a', 1}
>>> l_new
['b', 'a', 1] # The repetitions are removed, but the order is disrupted
# For immutable types, and to ensure the order, we need to write our own code, for example
l=[
{'name':'lili','age':18,'sex':'male'},
{'name':'jack','age':73,'sex':'male'},
{'name':'tom','age':20,'sex':'female'},
{'name':'lili','age':18,'sex':'male'},
{'name':'lili','age':18,'sex':'male'},
new_l=[]
for dic in l:
new_l.append(dic)
print(new_l)
# Results: it not only eliminates the repetition, but also ensures the order, and it is aimed at
[
# 1. Length
>>> s={'a','b','c'}
>>> len(s)
# 2. Member operation
>>> 'c' in s
True
# 3. Circulation
... print(item)
...
7.5 exercise
"""
1, Relational operation
There are two sets as follows: python is the name set of students who sign up for python course, a
pythons={'jason','egon','kevin','ricky','gangdan','biubiu'}
linuxs={'kermit','tony','gangdan'}
1. Find out the name set of students who enroll in both python and linux courses
3. Find out the names of students who only sign up for python course
4. Find out the name set of students who do not have both courses at the same time
"""
#Find out the name set of students who enroll in both python and linux courses
#Find out the names of students who only sign up for python courses
#Find out the name set of students who do not have both courses at the same time
**Immutable type: * when the value is changed the memory address is also changed that is the id is also changed It is
Immutable type: when the value is changed, the memory address is also changed, that is, the id is also changed. It is
proved that the original value is not being changed, and a new value is generated
Number type:
>>> x = 10
>>> id(x)
1830448896
>>> x = 20
>>> id(x)
1830448928
# The memory address has changed, indicating that integer type is immutable data type, and float
character string
>>> x = "Jy"
>>> id(x)
938809263920
>>> x = "Ricky"
>>> id(x)
938809264088
list
>>> id(list1)
486316639176
>>> id(list1)
486316639176
>>> list1.append('lili')
>>> id(list1)
486316639176
# When you operate on the value of a list, the value changes but the memory address does not cha
tuple
>>> t1 = ("tom","jack",[1,2])
# The element in the tuple cannot be modified, which means that the memory address pointed to by
>>> t1 = ("tom","jack",[1,2])
>>> id(t1[0]),id(t1[1]),id(t1[2])
>>> t1[2][0]=111 # If there is a variable type in the tuple, it can be modified, but the modified
>>> t1
Dictionaries
>>>
>>> id(dic)
4327423112
>>> dic['age']=19
>>> dic
>>> id(dic)
4327423112
# When the dictionary is operated, the id of the dictionary is the same when the value changes, t
1. Number type:
2. String type
3. List type
4. Tuple type
5. Dictionary type
6. Collection type
','age':73,'sex':'male'},
{'name':'tom','age':20,'sex':'female'},
{'name':'lili','age':18,'sex':'male'},
{'name':'lili','age':18,'sex':'male'},
]
new l=[]
_ []
for dic in l:
if dic not in new_l:
new_l.append(dic)
print(new_l)
Results: it not only eliminates the repetition, but also ensures the order, and it is aimed at the
immutable type of de duplication
[
{'age': 18, 'sex': 'male', 'name': 'lili'},
{'age': 73, 'sex': 'male', 'name': 'jack'},
{'age': 20, 'sex': 'female', 'name': 'tom'}
]
```python
# 1. Length
>>> s={'a','b','c'}
>>> len(s)
# 2. Member operation
>>> 'c' in s
True
# 3. Circulation
... print(item)
...
7.5 exercise
"""
1, Relational operation
There are two collections as follows: python is the collection of students' names who sign up for
pythons={'jason','egon','kevin','ricky','gangdan','biubiu'}
linuxs={'kermit','tony','gangdan'}
1. Find out the name set of students who enroll in both python and linux courses
3. Find out the names of students who only sign up for python course
4. Find out the name set of students who do not have both courses at the same time
"""
#Find out the name set of students who enroll in both python and linux courses
#Find out the names of students who only sign up for python courses
#Find out the names of students who do not have both courses at the same time
**Immutable type: * when the value is changed, the memory address is also changed, that is, the id is also changed. It is
proved that the original value is not being changed, and a new value is generated
Number type:
>>> x = 10
>>> id(x)
1830448896
>>> x = 20
>>> id(x)
1830448928
# The memory address has changed, indicating that integer type is immutable data type, and float
character string
>>> x = "Jy"
>>> id(x)
938809263920
>>> x = "Ricky"
>>> id(x)
938809264088
list
>>> list1 = ['tom','jack','egon']
>>> id(list1)
486316639176
>>> id(list1)
486316639176
>>> list1.append('lili')
>>> id(list1)
486316639176
# When you operate on the value of a list, the value changes but the memory address does not cha
tuple
>>> t1 = ("tom","jack",[1,2])
# The element in the tuple cannot be modified, which means that the memory address pointed to by
>>> t1 = ("tom","jack",[1,2])
>>> id(t1[0]),id(t1[1]),id(t1[2])
>>> t1[2][0]=111 # If there is a variable type in the tuple, it can be modified, but the modified
>>> t1
Dictionaries
>>>
>>> id(dic)
4327423112
>>> dic['age']=19
>>> dic
>>> id(dic)
4327423112
# When the dictionary is operated, the id of the dictionary is the same when the value changes, t
1. Number type:
2. String type
3. List type
4. Tuple type
5. Dictionary type
6. Collection type
Topics: Python Assembly Language Programming Linux