[python] review before the exam, sorting out basic knowledge points of python grammar

Article directory

1. Constants and expressions

print(1) #这里的1就是一个常量
print(1+2+3) #这里的1+2+3就是一个表达式

Constants and expressions are very simple, and they are not used much, just understand

2. Variables and data types

Variables are used to save data. If we need to use a piece of data frequently, creating a variable to save the data will be very convenient for later use.

create variable

#语法: 
变量名 = 数据

The = here is not equal in mathematics, but an assignment operation
变量的命名规则 :

  • Variable names must consist of numbers, letters and underscores and cannot be expressions
  • cannot start with a number
  • Cannot use keywords as variable names

type of data

Variable type: in order to distinguish different variables
Python中的数据类型只有整型(int),浮点型(float)和字符串类型

have to be aware of is:

  • The value range of int in Python is infinite
  • float in Python is a double precision floating point number
  • The string type should wrap the data in single quotes or double quotes
  • The type of string can be spliced, that is, splicing a string to the end of the last string to get a larger string String using + to splice

dynamic type

Dynamic type means that the data type in python can be changed

a = 1
print(type(a))
# 输出结果:<class 'int'>
a = 1.5
print(type(a))
# 输出结果:<class 'float'>
a = "hello world"
print(type(a))
# 输出结果:<class 'str'>

Data Type Conversion

Data type conversion is also used in normal times.
The syntax of data type conversion is:

# 要转换为的数据类型(变量名)
num = 1
str(num)
str_num = str(num)
# 对于转换后的数据类型建议用个变量接收一下
print(type(num)) # 输出 <class 'int'>
print(type(str_num)) # 输出 <class 'str'>
print(str_num) # 输出 1

so pay attentionData type conversion does not change the original variable type, but to get a modified data type of data, if you want to use this data, you need to use another variable to accept

Integers, floating-point numbers and strings can be converted to each other, but they cannot be converted casually
需要注意:

  1. Any data type can be converted to a string
  2. To convert a string to a number, there must be only numbers in the string
  3. When converting a floating point number to an integer, it will be lost to the decimal part

3. Notes

The comment side plays
the role of explaining the code . There are three ways to comment on the code.

Notes in python symbol
line comment #
docstring """Comment content"""or'''Comment content''(Three double/single quotation marks are used as the beginning and end, and cannot be mixed)

4. String

how strings are defined

There are three ways to define a string:

# 字符串的定义方式
str1 = 'python'
str2 = "python"
str3 = """python"""

Among them, str3 is defined in the same way as the comment. When there is a variable to accept, it is a string. If there is no variable, it is a comment. There are
如果想要的定义字符串里本身包含单引号或双引号,要怎么进行解决
three methods:

  1. Single quotes are defined, strings can be replaced by double quotes
  2. Double quotes are defined, strings can be replaced by single quotes
  3. Use \ (escape character)

Example:

str1 = "'python'"
str2 = '"python"'
str3 = "\"python"

print(str1)
print(str2)
print(str3)
# 输出结果:
# 'python'
# "python"
# "python

concatenation of strings

The splicing of strings is to splice two or more strings into a larger string. The splicing of strings should use +
example:

print("人生苦短," + "我学python")
str = "python"
print("人生苦短,"+"我学"+str)
# 输出结果:
# 人生苦短,我学python
# 人生苦短,我学python

It should be noted that the splicing of strings, 只能是字符串类型的数据进行拼接but not the splicing of non-string data

String formatting①

In order to solve the problem that strings cannot be spliced ​​with non-string types, you can use string formatting at this time

symbolic representation describe
%s Convert the content to a string and place it in the placeholder
%d Convert the content to an integer and place it in the placeholder
%f Convert the content to a floating point type and place it in the placeholder

Example: %s

  • % means I want to take place
  • s refers to the place where the variable is converted into a string and placed in the placeholder

Examples are as follows:

str1 = "python"
print("我要学%s" %str1)
str2 = 2023
print("现在是%s年,我要学%s" % (str2,str1))
# 输出结果:
# 我要学python
# 现在是2023年,我要学python

Notice:当只有多个字符串使用占位符进行拼接时,需要使用括号将变量括起来,变量与变量之间用逗号隔开

Precision Control for String Formatting

Accuracy control is mainly for numbers, and the symbol is expressed as mn

  • m: empty width, the set width is smaller than the number itself, it will not take effect (rarely used)
  • n: Control the precision of the decimal point, the requirement is a number, rounded up

example

a = 11
b = 123456
c = 12.345
print("设置数字宽度为5,a为:%5d" %a)
print("设置数字宽度为5,b为:%5d" %b)
print("设置宽度为6,小数精度为2位,c为:%7.2f" %c)
print("宽度不限制,小数精度为2位,c为:%.2f" %c)

# 输出结果:
# 设置数字宽度为5,a为:   11
# 设置数字宽度为5,b为:123456
# 设置宽度为6,小数精度为2位,c为:  12.35
# 宽度不限制,小数精度为2位,c为:12.35
# 注: .也算一个宽度

There are spaces in the output of the above example, and the displayed effect is not very obvious, so it is recommended to try to run it with a compiler

String formatting②

Although using placeholders can splice strings and control precision, python also provides us with another way to splice strings

Grammar format: f"content{variable}"

The f here is format, the meaning of formatting
Example:

num1 = "python"
print(f"人生苦短,我学{num1}")
num2 = 100
num3 = 41.9
print(f"张三有{num2}元,网购花了{num3}元")

# 输出结果为:
# 人生苦短,我学python
# 张三有100元,网购花了41.9元
  • 这种格式化字符串的方式,什么类型都可以进行格式化,但不会对精度进行控制

format the expression

For variables that are only used once in the code, we don't need to define variables for assignment, but directly use expressions to represent them.
Example:

print("1*1 = %d" % (1*1))
print(f"1*1 = {1*1}")
print("浮点数在python中的类型名是: %s" % type(1.23))

# 输出结果:
# 1*1 = 1
# 1*1 = 1
# 浮点数在python中的类型名是: <class 'float'>

5. Enter from the console (input)

input reads the input content from the keyboard, and you can use variables to receive the input content.
One thing to note, input输入的语句接收的内容都是字符串类型even if you input integers and floating point numbers, if you want to get integer and floating point data, then需要数据类型转换

num1 = input("你的兴趣爱好是:")
print(num1)
num2 = input()
num3 = input()
print(f"num1的数据类型是:{type(num1)}")
print(f"num2的数据类型是:{type(num2)}")
print(f"num3的数据类型是:{type(num3)}")
# 输出结果:
# 你的兴趣爱好是:唱跳rap篮球 (用户进行输入)
# 唱跳rap篮球
# 15 (用户进行输入)
# 12.54 (用户进行输入)
# num1的数据类型是:<class 'str'>
# num2的数据类型是:<class 'str'>
# num3的数据类型是:<class 'str'>

6. Operators

arithmetic operator

operator describe
+ add
- reduce
* take
/ remove
// evenly divisible
% Take the remainder
** Exponent (power)

Arithmetic operators are similar to operators in mathematics, but there is one thing to note: / This operator , in other languages ​​such as C/Java, this / means an integer, but it is different in python, in python This / is the same as in mathematics, for example, the result of 5/2 in python is 2.5结果是一个浮点数

assignment operator

The assignment operator is "=", which is to assign one data to another variable
. Among them, there are some compound assignment operators

operator example
+= b+=a is equivalent to b=b+a
-= b-=a is equivalent to b=ba
*= b*=a is equivalent to b=b*a
/= b/=a is equivalent to b=b/a
%= b%=a is equivalent to b=b%a
**= b**=a is equivalent to b=b**a
//= b//=a is equivalent to b=b//a

Boolean type and comparison operators

Boolean type is used to represent true and false
Comparison operators are used to calculate true and false

In fact, the boolean type belongs to the number type, but there are only two values:True(真)和False(假) 在数字中对应的就是1和0

Let's look at the comparison operator is actually very easy to understand, look at the code and output results:

ret1 = 1 < 2
ret2 = 1 > 2
print(ret1)
print(ret2)
print(f"ret1的类型是: {type(ret1)}")
print(f"ret2的类型是: {type(ret2)}")
# 输出结果:
# True
# False
# ret1的类型是: <class 'bool'>
# ret2的类型是: <class 'bool'>

This is similar to judging the truth or falsehood of a proposition in mathematics. True is True and false is False.
The comparison operators are as follows:

operator describe
== Determine whether the content is equal
!= Determine whether the content is not equal
> Determine whether the value on the left of the greater than sign is greater than the value on the right
< Determine whether the value on the left of the less than sign is less than the value on the right
>= Determine whether the value on the left of the greater than sign is greater than or equal to the right
<= Determine whether the value on the left of the less than sign is less than or equal to the right

Note: Return True if satisfied, otherwise return False

7. Conditional statements

The Boolean type and comparison operators Learn the basics of conditional statements

if statement

# 语法格式:
if 判断条件:
    如果为True,执行代码

Look at the code first:

a = 5
b = 7
print(f"a = {a}")
print(f"b = {b}")
if a < b:
    print("5 < 7")
    print("5 < 7为True,所以输出")

if a > b:
    print("5 > 7")
    print("5 > 7为False,所以不输出")

print("不受条件控制的影响")
# 输出结果
# a = 5
# b = 7
# 5 < 7
# 5 < 7为True,所以输出
# 不受条件控制的影响

In fact, the syntax format is very simple, but there are some points to note:

  • The result of the judgment condition must be True or False
  • There is strict indentation in Python. The if statement and the code to be executed when the if statement is true are not aligned. There are 4 spaces in front of the code to be executed when the if statement is true.
  • Multiple statements can be written in the if statement, but they will only be executed when the condition is True
  • Don't forget the "colon" after the judgment condition

if else statement

# 语法格式
if 判断语句:
	执行语句
else:
	执行语句

Look at the code first:

a = 5
b = 7
if a < b:
    print("a < b")
if a >= b:
    print("a >= b")

if a < b:
    print("a < b")
else:
    print("a >= b")
# 输出结果
# a < b
# a < b
  • else does not need a conditional judgment statement, as long as the if condition is not met, it will go back to execute the statement in the else
  • The code block of else should also be indented

if elif else statement

Students who have studied other programming languages ​​should know that the judgment statement should be if else if and else, elif is actually the abbreviation of else if, but there is no else if in python

语法格式如下:
if 判断条件:
    条件满足执行代码
elif 判断条件:
    条件满足执行代码
elif 判断条件:
    条件满足执行代码
...
else:
    条件满足执行代码 # 这里的条件满足 是指else上面的判断语句均不满足
  • elif can write multiple
  • When judging the conditions, they are executed sequentially. As long as one condition is met, the subsequent ones will not be executed.
  • Note the indentation

Let's take a look at a case:

val = int(input("请输入成绩: "))
if val < 60:
    print("成绩评定为: 不及格")
elif val < 70: 
    print("成绩评定为: 及格")
elif val < 85:
    print("成绩评定为: 良好")
else:
    print("成绩评定为: 优秀")

# 输出结果:
# 请输入成绩: 80
# 成绩评定为: 良好

Note: The above val < 70 can actually be understood as 60 <= val <= 70, because if val < 60, it will be output directly: the grade is evaluated as: if it fails, it will not judge the following conditions. It can be val < 70 This conditional judgment shows that val must be greater than or equal to 60. val<85 is the same as above

It's okay 将input语句直接写在判断条件中, but it's not recommended to write like this, the readability becomes worse

Nesting of judgment statements

The judgment statement can be nested. For example, it is no problem to insert an if elif else statement in an if else statement. But最好不要嵌套太多的条件判断语句,可读性不好. 尽量还是要追求简洁

8. Loop

Loops are also very common in our daily life, such as: music carousels, looping billboards, etc.

while loop

# 语法:
while 条件:
    条件为真,执行代码
    只要条件满足,代码就会无限去执行
    ...
条件为假,退出循环
  • 循环语句首先会对条件进行判断,如果条件为真,就会执行while语句中的代码,每次执行完就会重新判断条件是否为真(True),如果为真就继续为真,如果为假(False)退出循环
  • Set the loop condition. If the condition is always true, the code in the while will be executed all the time without exiting the loop.
  • Note the indentation

Example:

# 循环输出1~100之间的所有奇数
i = 1
while i < 100:
    print(i)
    i += 2
# 输出结果:
# 1
# 3
# ...
# 97
# 99

When i increases to 101, the condition i < 99 is not satisfied, so the loop is exited and the program ends.
Therefore, if a statement that outputs the value of i is added at the end of the code, the output result is 101

Nesting of loop statements

循环语句和条件判断语句一样,可以嵌套
Next, use an example to print the table of nine-nine punishment formulas to explain how to nest

# 打印九九乘法口诀表
i = 1
while i < 10:
    j = i
    while j < 10:
        print(f"{i} * {j} = {i*j}")
        j += 1
    i += 1

Notice:

  1. Here i=j and j+=1 are in loop 1, not loop 2
  2. Loop 1 controls i from 1 to 9
  3. Loop 2 controls j from i to 9

for loop

The for loop in python is not the same as the for loop in other languages. Although the function of the while loop is similar, there are still some differences:

  • The loop condition of the while loop can be customized
  • The for loop is a "polling" mechanism, which chases and processes a batch of content
# 语法
for 临时变量 in 临时处理数据集:
    条件为真时执行代码
条件为假退出循环

Example:

str1 = "python"
for ch in str1:
	# 使用ch这个临时变量,逐个取出str1中的每一个字符
    print(ch)
# 输出:
# p
# y
# t
# h
# o
# n
  • for循环无法定义循环条件, can only remove data one by one for processing
  • Pay attention to the indentation problem

range statement

# 语法:
range(num)
# 获取一个从0开始,到num(不包括num)结束的数字序列

range(num1,num2)
# 获得一个从num1开始到num2(不包括num2)的数字序列

range(num1,num2,step)
# 获得一个从num1开始到num2(不包括num2)的数字序列
# 但是每个数字之间的步长为step

Example 1:

for x in range(3):
    print(x)
# 输出结果:
# 0
# 1
# 2

Example 2:

for x in range(2,5):
    print(x)
# 输出结果:
# 2
# 3
# 4

Example 3:

for x in range(1,10,3):
    print(x)
# 输出结果:
# 1
# 4
# 7

特别提醒:如果要用区间的话,在计算机中基本上都是左闭右开的区间,这一点需要注意

continue和break

continue的作用:中断本次循环,直接进入下一次循环
continue用于:for循环和while循环,效果时相同的

Example:

# 输出0~9之间的所有奇数
for x in range(10):
    if x % 2 == 0:
        continue
    print(x)
# 输出结果:
# 1
# 3
# 5
# 7
# 9  

Use x to take the remainder of 2, if it is equal to 0, it means it is an even number, then interrupt this cycle and directly enter the next cycle, so as to achieve the effect of outputting all odd numbers between 0 and 9

9. Function

what is the function

A function is an organized, reusable piece of specific code that does something

Benefits of using functions :

  • Encapsulate the function in the function, which can be called at any time and repeatedly
  • Improve code reusability and improve efficiency

Function definition and call

# 函数定义的语法
def 函数名(形参..):
    函数体 # 也就是函数要实现的功能
    return 返回值

# 函数的调用
函数名()
# 如果有参数要传参
# 如果有返回值可以用变量进行接受返回值
  • 参数和返回值可以省略
  • Functions must be defined before using

Example:

def func():
    print("hello python")

func()
# 输出结果:
# hello python

The incoming parameters of the function

I just introduced the situation where the function has no parameters, now let’s talk about the situation with parameters
Example:

def add(x, y):
    print(f"{x}+{y}={x+y}")

add(2, 5)
  • 函数定义时的参数叫形式参数(形参),参数之间要使用逗号隔开
  • 函数调用时传的2和5这种的叫实际参数(实参),也就是函数调用时真正使用的参数,按照顺序进行传入参数,参数之间使用逗号隔开
  • The number of formal parameters is unlimited

function return value

The previous example of finding the sum of two numbers is a direct output without a return value.
If I want to get the sum of two numbers, I need to use the return value of the function

# 使用方法:
def 函数名(形参..):
    函数体 # 也就是函数要实现的功能
    return 返回值

变量 = 函数名(形参..)

Example:

def add(x, y):
    return x + y

ret = add(2, 3)
print(ret)
# 输出:
# 5

函数在执行完return语句后,如果后面还有语句的话,那么后面是不会执行的

None type

如果函数没有写return语句,那么函数的返回值就是None
None is empty, meaningless

Example:

def func():
    print("hello python")

ret = func()
print(f"无返回值的函数,返回的值为:{ret}")
print(f"无返回值的的函数,返回值的数据类型为:{type(ret)}")
# 输出结果
# hello python
# 无返回值的函数,返回的值为:None
# 无返回值的的函数,返回值的数据类型为:<class 'NoneType'>

nested function calls

Functions can also be called nestedly, that is, calling another function in one function
Example:

def fun2():
    print(2)
    
def func1():
    print(1)
    fun2()
    
func1()
# 输出结果:
# 1
# 2

Scope of variables in functions

变量主要分为两类:全局变量和局部变量

A local variable is a variable defined inside the function body, this variable只在函数体内部生效
局部变量的作用:用于保存变量,代码执行完后临时变量就销毁了

Example:

def func():
    num = 12
    print(num)

print(num)
# 这么写会报错
# 因此num的作用域只在函数体内部

全局变量是 在函数体内外都能生效的变量,定义在函数外即可

Example 2:

num = 1
def func1():
    print(num)

def func2():
    num = 12
    print(num)

func1()
func2()
print(num)
# 输出结果:
# 1
# 12
# 1
  • 局部变量的优先级大于全局变量

Because num in fun2 is a local variable, the local takes precedence, so 12 will be output, and the value of the global variable num outside will not be changed.

如果要在函数体内部改变全局变量的值,则需要使用global关键字
Example:

num = 1
def func():
    global num
    num = 12
    print(num)

func()
print(num)
# 输出结果:
# 12
# 12

global关键字的作用:将函数内部声明的变量变为全局变量

10. list (list)

The list is built in python 可变序列and is an ordered continuous memory space containing several elements.
All elements are stored in [],
and the elements are separated by commas.

list definition

There are two ways to define a list:

  1. 使用字面值创建列表
  2. 使用list()创建列表

Example:

# 使用使用字面值创建列表
# []就代表一个空列别
a = []
print(type(a))

# 使用list()创建列表
b = list()
print(type(b))

# 输出的结果为:
# <class 'list'>
# <class 'list'>

Lists can be initialized when they are defined , but unlike arrays in C/Java, arrays can only hold variables of the same type . For example, integer arrays can only hold elements of integer type, while lists are different.Lists can store elements of different data types
Example:

a = [1,2,3]
print(a)
# 输出[1, 2, 3]

b = list((1,2,3))
print(b)
# 输出[1, 2, 3]

c = [1,1.2,"ads",False,[1,2,3]];#也可以存放列表的数据
print(c)
# 输出[1, 1.2, 'ads', False, [1, 2, 3]]

List subscript access

For the elements of the list, you can passlist name [subscript]This form of accessing
注意:这里的下标都是从0开始的 ,下标的有效范围是0到列表长度-1
如果超出下标的有效范围,那么就会出现异常
列表的长度可以直接使用内置函数len(列表名)获取
len() can not only find the length of the list, but also find the length of strings, tuples, dictionaries, etc.

# 下标的范围[0,2]
a = [1,2,3]
print(len(a))
# 输出结果:3
print(a[1]) #对列表的元素进行访问
# 输出结果:2
a[2] = 5 #对列表的元素进行修改
print(a)
# 输出结果:[1, 2, 5]

Subscripts in python can also be written as negative numbers

a = [1,2,3]
print(a[len(a)-1])
# 输出结果:3
print(a[-1])
# 输出结果:3

For the -1 here, it can be understood as len (list name) -1, len (list name) is omitted, and it can also be understood as the last element. As long as you can remember, you can understand it in any way. If it
is Subscripts are represented by negative numbers , thenThe effective range of the subscript is [-len (list name), -1]

Subscripts for nested lists

When talking about the list definition, I said that the element type of the list is not limited, of course, it is also possible to store the list in the list
Example:

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

For nested lists in this kind of list, subscript indexes are also supported.
For example:

a = [[1, 2, 3], [4, 5, 6]]
print(a[0][1])
# 输出结果:
# 2

The above code can be divided into two steps to understand:

  1. It can be seen that [1,2,3] and [4,5,6] are two elements in the a list, and a[0] is the list of [1,2,3]
  2. a[0][1] is equivalent to accessing the second element of the list [1,2,3], so the output result is 2

Common methods for lists

Here are some commonly used built-in functions in the list:

method illustrate
ListName.append(x) Add element x to the last position of the list
ListName.extend(L) Append all elements in the list L to the end of the list
List name.insert(index,x) Insert element x at index position of the list
listname.remove(x) removes the first occurrence of element x in the list
ListName.pop([index]) Delete and return the element at the specified position of the list object, the default is the last element
ListName.clear() Delete all elements in the list, but keep the list object
listname.index(x) Return the subscript of the first element whose value is x, if x does not exist, an exception will be thrown
ListName.count(x) Returns the number of specified element x in the list
ListName.reverse() Flip list elements in place
List name.sort(key=None,reverse=False) Sort list elements in-place
ListName.copy() shallow copy of list elements
len(list name) Count the number of elements in a list

11. Tuples

Tuples, like lists, can store multiple elements of different data types
与列表最大的不同就是:列表是可变的,而元组不可变

Definition of tuple

元组的定义: 使用()定义元组,元素之间使用逗号隔开

a = (1, 2, True, "python")
b = ((1, 2, 3), (4, 5, 6))

Tuples can also be nested

如果想要定义空元组,也可以使用关键字tuple进行定义

Example:

a = ()
b = tuple()
print(a)
print(type(a))
print(b)
print(type(b))

# 输出结果:
# ()
# <class 'tuple'>
# ()
# <class 'tuple'>

如果用tuple 定义元组,实际上是得到了元组的类对象

Define a tuple with only one element

如果要定义只有一个元素的元组,需要在元素的后面加一个 "逗号"

Example:

str1 = ("python")
print(type(str1))

str2 = ("python",)
print(type(str2))

# 输出结果:
# <class 'str'>
# <class 'tuple'>

一定不能省略逗号,如果省略,就不是元组了

元组的下标访问

其实元组的下标访问和列表是一样的,掌握了列表的下标访问,那元组也就不在话下了

元组的常用方法

方法 描述
元组名.index(x) 查询x在元组中的下标,如果存在返回下标,否则会报错
元组名.count(x) 统计x在元组中出现的次数
len(元组名) 返回元组的元素个数

12.再识字符串(str)

虽然之前介绍了字符串,但是是以数据类型的角度来介绍字符串的,而现在要以数据容器的视角来看字符串

字符串是字符的容器,可以存放任意多个字符

字符串的下标索引

字符串也可以通过下标进行访问里面的字符

  • 从前往后,下标从0开始
  • 从后往前,下标从-1开始

示例:

str1 = "python"
print(f"2下标的字符是: {str1[2]}")
print(f"-2下标的字符是: {str1[-2]}")

# 输出结果:
# 2下标的字符是: t
# -2下标的字符是: o

字符串和元组一样,是无法修改的数据容器
如果想要通过下标进行修改特定的字符,编译器则会报错

字符串的常用方法

方法 描述
字符串.index(要查找字符串) 查找特定字符串的下标索引
字符串.replace(字符串1,字符串2) 将全部的字符串1都替换为字符串2,但不会修改原本的字符串,而是得到一个新字符串
字符串.split(分割符字符串) 按照指定分隔符字符串,将字符串分成多个字符串,并存在列表中,字符串本身不变,而是得到一个新的列表对象
字符串.strip(字符串) ()里字符串可以传也可以不传,不传参就是去除前后空格,传参则去除前后指定字符串,这里依旧不修改字符串本身,而是得到一个新的字符串
字符串.count(字符串) 统计某个字符串在字符串中出现的次数
len(字符串) 得到字符串的长度

13.集合(set)

集合是一种无序可变的容器对象
集合最大的特点:同一个集合内元素是不允许有重复的

集合的定义

集合的定义使用 {} ,但{}不能用于定义空集合!!! 可以使用set()定义一个空集合
元素之间用逗号隔开

a = set()
# 自动去重
b = {
    
    1,"python",2.3,1,"python",2.3,1,"python",2.3,"python"}
print(type(a))
print(b)
print(type(b))

# 输出结果:
# <class 'set'>
# {1, 2.3, 'python'}
# <class 'set'>
  • 集合是不支持下标索引访问

集合的常用方法

方法 描述
集合.add(元素) 集合内添加一个元素
集合.remove(元素) 删除集合内指定的元素
集合.pop() 从集合内随机取出一个元素
集合.clear() 清除集合
集合1.difference(集合2) 得到一个新的集合,包含两个集合的差集,原集合不变
集合1.difference_update(集合2) 从集合1中删除集合2中存在的元素,集合1改变,集合2不变
集合1.union(集合2) 得到一个新的集合,内含两个集合的所有元素,原集合不变
len(集合) 统计集合中(去重后)元素的个数

14.字典(dict)

字典的定义

字典的定义也是使用 {} 定义空字典也可以使用dict()
不过字典元素的类型则需要是 键值对(key : value)
key和value可以是任意类型的,但是key不能是字典

  • 字典中不允许key重复
a = {
    
    }
b = dict()
c = {
    
    "张三":95, "李四":89,"王五":97}
print(type(a))
print(type(b))
print(c)
print(type(c))

# 输出结果:
# <class 'dict'>
# <class 'dict'>
# {'张三': 95, '李四': 89, '王五': 97}
# <class 'dict'> 

键和值之间用 : 分割
每个键值对之间用逗号分割

  • 字典不支持下标索引访问元素,但是可以通过Key值找到对应的Value值
# 语法:
字典名[Key]

使用起来和下标索引访问是差不多的
示例:

a = {
    
    "张三":95, "李四":89,"王五":97}
print(a["张三"])

# 输出结果:
# 95

字典的常用方法

方法 描述
字典[Key] = Value 如果Key存在,就是修改元素. 如果不存在,就相当于新增一个元素
字典.pop(Key) 取出对应的Value,同时删除Key和Value
字典.clear() 清空字典
字典.keys() 取出字典中所有的Key,一般用于for循环遍历字典
len(字典) 统计字典中元素的个数

15.文件操作

文件操作就太好用代码进行演示,因此每个人的电脑里的文件都是不一样的,所有就没怎么有示例了. 见谅!
文件主要有三个操作:打开文件,读写文件和关闭文件

文件编码

编码(coding)是指用代码来表示各组数据资料,使其成为可利用计算机进行处理和分析的信息。

文件的编码有很多,例如:GBK,Unicode,UTF-8等等
其中UTF-8是我们最常用的,UTF-8也被称为万国码,只要没有特殊要求都可以设置成UTF-8编码

文件的打开

python中,使用open()函数,可以打开一个文件或者创建一个新文件

# open函数的介绍:
f = open(name,mode,encoding)
  • name:就是要打开文件的文件名(也可以是文件所在的具体路径)
  • mode:设置文件的访问模式:读取,写入,追加
  • encoding:编码格式(推荐使用UTF-8)
  • f是一个文件对象

mode的三种访问模式:

模式 描述
r 以只读的方式打开文件
w 对文件进行写入,如果文件存在,则会把原来的内容全部删掉,从头编辑,如果文件不存在,则会创建一个新文件
a 对文件进行追加,如果文件存在,则会在原内容后面追加新的内容,如果不存在,则会创建新文件并追加内容

open()函数中encoding的不是第三位,不能直接传参数,而是要用encoding="编码格式"

示例:

open("文件名", "访问模式", encoding="UTF-8")

注意上面的encoding

文件的读取

文件读取相关的方法有三个:

方法 描述
文件对象.read(num) num表示要从文中取出的数据长度(单位是字节),如果没有传入num,就会读文件中的所有数据
文件对象.readlines() 按照行的方式对整个文件内容进行一次性读取数据,并返回一个列表,每一行的数据为一个元素
文件对象.readline() 每次只读取一行的数据

注意:在读取文件的时候会有一个文件指针记录读取的位置,下一次读就会从文件指针的地方开始读
例如:如果调用read()来读取文件,但没有把文件读完,在调用一次read()方法,那么会从上一次read()最后一读到的地方开始读取

除了上述的三种方法,也可以使用for循环来读取文件

# 使用方法:
# f是文件对象
for line in f:
    print(line)

文件的关闭

关闭文件可以使用文件对象.close()方法

如果不关闭文件,程序不会停止,那么这个文件就会一直被编译器占用
为了避免忘记关闭文件,我们就可以使用with open这种写法

with open()

# 语法:
# f是文件对象
with open(name,mode) as f:
    进行文件操作
  • 这种写法可以自动帮我们关闭文件

文件的写入

文件写入有三个步骤:1.打开文件 2.调用文件对象的write()方法 3.调用文件对象的flush()方法
示例:

# 1.打开文件 mode记得设置为"w"(写入)
f = open("文件名", "w", encoding="UTF-8")
# 2.调用文件对象的write()方法
f.write("hello python")
# 3.刷新缓冲区
f.flush()

注意:

  • 调用write()方法,内容不会直接写到文件中,而是会先存储在缓冲区中
  • 调用flush()方法后,刷新缓冲区之后,文件才会真正写到文件中
  • close()方法中是内置了flush()功能的,不调用flush()方法而调用close()方法也是可以将内容写入文件的
  • write()方法写文件时,若文件存在,会将原文件中的内容给删掉,再写入内容.如果不存在,则会创建新文件并写入内容

文件的追加

文件的追加和上面的文件写入差不多,只需要将mode值改成"a"即可

  • "a"模式下,若文件不存在会创建文件,若文件存在,则会再原文件内容的后面追加新内容
  • 文件追加,依旧要进行flush()操作

16.异常处理

异常:即便 Python 程序的语法是正确的,在运行它的时候,也有可能发生错误。运行期检测到的错误被称为异常。也就是我们常说的BUG

异常的捕获

如果程序有异常会有两种情况:

  1. 程序遇到异常终止运行
  2. 对BUG进行提醒,程序继续运行

通常情况遇到BUG时都是第一种情况,但如果我们对异常进行捕获,就会出现第二种情况

捕获异常的作用:提前假设某处会出现异常,提前做好准备,当程序出现异常时,就可以提前做好准备

# 语法:
try:
    可能会出现异常的代码
except:
    出现异常后执行的代码

示例:

a = [1,2,3]
try:
    print(f"列表的第一个元素:{a(0)}")
except:
    print("列表使用[]来进行下标访问!")
    print(f"列表的第一个元素:{a[0]}")
# 输出结果:
# 列表使用[]来进行下标访问!
# 列表的第一个元素:1

上述代码我们可知:因为事先对try里面的代码进行处理了,try里面的代码出现异常时,try里面的代码没有被执行,而是直接去执行except里面的代码了,这就是异常的捕获

除了这种捕获异常外,我们还可以捕获指定的异常

捕获指定的异常

# 语法:
try:
    可能出现异常的代码
except 异常类型 as e:
    出现异常时执行的代码
try:
    print(a)
except NameError as e:
    print("变量未定义!")
    print(e)

# 输出结果:
# 变量未定义!
# name 'a' is not defined

上述代码也只能变量未定义这个指定的异常,如果出现了别的异常,程序依旧会终止运行

捕获多个异常

捕获除了可以捕获指定的异常,还可以捕获多个异常

# 语法
try:
    可能出现异常的代码
except (异常1,异常2,...) as e:
	出现异常时执行的代码

示例:

b = [1,2,3]
try:
    print(b[5])
    print(a)
except (NameError,IndexError) as e:
    print("变量未定义 或者 下标索引错误")
    print(e)

捕获全部的异常

捕获全部的异常的异常方法有两个:

# 方法1:
try:
    可能出现异常的代码
except:
    出现异常时执行的代码
# 方法2:
try:
    可能出现异常的代码
except Exception as e:
    出现异常时执行的代码

Exception 是所有异常类的父类

else和finally

else 是程序没出现时执行的代码

示例1:

a = [1,2,3]
try:
    print(a[0])
except:
    print("出现异常了")
else:
    print("没有出现异常")
# 输出结果:
# 1
# 没有出现异常

示例2:

a = [1,2,3]
try:
    print(a[5])
except:
    print("出现异常了")
else:
    print("没有出现异常")
# 输出结果:
# 出现异常了

finally 里面的语句不管程序有没有异常都会执行

示例1(出有异常的情况):

a = [1,2,3]
try:
    print(a[5])
except:
    print("出现异常了")
else:
    print("没有出现异常")
finally:
    print("finally 里的语句一定会被执行")
# 输出结果:
# 出现异常了
# finally 里的语句一定会被执行

示例2(无异常的情况):

a = [1,2,3]
try:
    print(a[1])
except:
    print("出现异常了")
else:
    print("没有出现异常")
finally:
    print("finally 里的语句一定会被执行")
# 输出结果:
# 2
# 没有出现异常
# finally 里的语句一定会被执行

else和finally再捕获异常时可以写也可以不写

异常的传递性

异常是具有传递性的,这句话有点抽象,看下面这段代码:

def func1():
    a = [1,2,3]
    print(a[10])
def func2():
    func1()

try:
    func2()
except Exception as e:
    print(e)
# 输出结果:
# list index out of range

这里程序出现异常了,虽然是func2()里出的问题,但func2()里面是调用的func1()函数,func1()中的打印下标索引越界了.但依旧被捕获到了.
异常从func1函数传递到了func2,然后被捕获到了,这就是异常的传递性

17.结语

这篇文章也是写了好久,因为是复习用的,有些地方其实讲的不那么仔细,如果有意见也可以提出,后面我也会不断对本文进行改进的
如果有需要,后面也可以单独写文章对某些知识点做更细致的讲解
文章比较长,可能有些地方写的不是很好,还请见谅!
感谢你的观看! 希望这篇文章能帮到你!
在这里插入图片描述

Guess you like

Origin blog.csdn.net/m0_63463510/article/details/127856534