Python 是一种通用编程语言,其在科学计算和机器学习领域具有广泛的应用。

1 量、运算符与数据类型

1.1 注释

1.2 运算符

1.3 变量和赋值

1.4 数据类型与转换

1.5 print() 函数

2 条件语句

2.1 if 语句

2.2 if - else 语句

2.3 if - elif - else 语句

2.4 assert 关键词

3 循环语句

3.1 while 循环

3.2 while - else 循环

3.3 for 循环

3.4 for - else 循环

3.5 range() 函数

3.6 enumerate()函数

3.7 break 语句

3.8 continue 语句

3.9 pass 语句

3.10 推导式

4 异常处理

4.1 Python 标准异常总结

4.2 Python标准警告总结

4.3 try - except 语句

4.6 raise语句

1.量、运算符与数据类型

注释

1. 在 Python 中, # 表示注释,作用于整行。

【例子】单行注释

# 这是一个注释print("Hello world")# Hello world

1. ''' ''' 或者 """ """ 表示区间注释,在三引号之间的所有内容被注释

【例子】

多行注释

'''这是多行注释,用三个单引号这是多行注释,用三个单引号这是多行注释,用三个单引号'''print("Hello china")# Hello china"""这是多行注释,用三个双引号这是多行注释,用三个双引号这是多行注释,用三个双引号'''print("hello china")# hello china

1.2运算符

算术运算符

操作符 名称 示例+ 加 [1 + 1]- 减 [2 - 1]* 乘 [3 * 4]/ 除 [3 / 4]// 整除 [(地板除) 3 // 4]% 取余 [3 % 4]** 次方 [2 ** 3]

【例子】

print(1 + 1) # 2print(2 - 1) # 1print(3 * 4) # 12print(3 / 4) # 0.75print(3 // 4) # 0print(3 % 4) # 3print(2 ** 3) # 8

比较运算符

操作符 名称 示例> 大于 [2 > 1]>= 大于等于 [2 >= 4]< 小于 [1 < 2]<= 小于等于 [5 <= 2]== 等于 [3 == 4]!= 不等于 [3 != 5]

【例子】

print(2 > 1) # Trueprint(2 >= 4) # Falseprint(1 < 2) # Trueprint(5 <= 2) # Falseprint(3 == 4) # Falseprint(3 != 5) # True

逻辑运算符

操作符 名称 示例and 与 (3 > 2) and (3 < 5)or 或 (1 > 3) or (9 < 2)not 非 not (2 > 1)

【例子】

print((3 > 2) and (3 < 5)) # Trueprint((1 > 3) or (9 < 2)) # Falseprint(not (2 > 1)) # False

位运算符

操作符 名称 示例~ 按位取反 ~4& 按位与 4 & 5| 按位或 4 | 5^ 按位异或 4 ^ 5<< 左移 4 << 2>> 右移 4 >> 2

【例子】

print(bin(4)) # 0b100print(bin(5)) # 0b101print(bin(~4), ~4) # -0b101 -5print(bin(4 & 5), 4 & 5) # 0b100 4print(bin(4 | 5), 4 | 5) # 0b101 5print(bin(4 ^ 5), 4 ^ 5) # 0b1 1print(bin(4 << 2), 4 << 2) # 0b10000 16print(bin(4 >> 2), 4 >> 2) # 0b1 1

三元运算符

x, y = 4, 5if x < y:small = xelse:small = yprint(small) # 4

【例子】

x, y = 4, 5small = x if x < y else yprint(small) # 4

其他运算符

操作符 名称 示例in 存在 'A' in ['A', 'B', 'C']not in 不存在 'h' not in ['A', 'B', 'C']is 是 "hello" is "hello"is not 不是 "hello" is not "hello"

【例子】

letters = ['A', 'B', 'C']if 'A' in letters:print('A' + ' exists')if 'h' not in letters:print('h' + ' not exists')# A exists# h not exists

【例子】比较的两个变量均指向不可变类型。

a = "hello"b = "hello"print(a is b, a == b) # True

Trueprint(a is not b, a != b) # False False

【例子】比较的两个变量均指向可变类型。

a = ["hello"]b = ["hello"]print(a is b, a == b) # False

Trueprint(a is not b, a != b) # True False

注意:1. is, is not 对比的是两个变量的内存地址

2. ==, != 对比的是两个变量的值

3. 比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。

4. 对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的。

运算符的优先级

1.一元运算符优于二元运算符。例如 3 ** -2 等价于 3 ** (-2) 。

2.先算术运算,后移位运算,最后位运算。例如 1 << 3 + 2 & 7 等价于 (1 << (3 + 2)) & 7 。

3. 逻辑运算最后结合。例如 3 < 4 and 4 < 5 等价于 (3 < 4) and (4 < 5) 。

【例子】

print(-3 ** 2) # -9print(3 ** -2) # 0.1111111111111111print(1 << 3 + 2 & 7) # 0print(-3 * 2 + 5 / -2 - 4) # -12.5print(3 < 4 and 4 < 5) # True

1.3 变量和赋值

1. 在使用变量之前,需要对其先赋值。

2. 变量名可以包括字母、数字、下划线、但变量名不能以数字开头。

3. Python 变量名是大小写敏感的,foo != Foo。

【例子】

teacher = "我的程序人生"print(teacher) # 我的程序人生

【例子】

first = 2second = 3third = first + secondprint(third) # 5

【例子】

myTeacher = "我的程序人生"

yourTeacher = "你的程序人生"ourTeacher = myTeacher + ',' + yourTeacherprint(ourTeacher)

# 我的程序人生,你的程序人生

1.4 数据类型与转换

类型 名称 示例int 整型 -876, 10float 浮点型 3.149, 11.11bool 布尔型 True, False

整型

【例子】通过 print() 可看出 a 的值,以及类 (class) 是 int 。

a = 1031print(a, type(a))# 1031

Python 里面万物皆对象(object),整型也不例外,只要是对象,就有相应的属性 (attributes) 和方法 (methods)。

【例子】

b = dir(int)print(b)

# ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__',# '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__',# '__float__', '__floor__', '__floordiv__', '__format__', '__ge__',# '__getattribute__', '__getnewargs__', '__gt__', '__hash__',# '__index__', '__init__', '__init_subclass__', '__int__', '__invert__',# '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__',# '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__',# '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__',# '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__',# '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',# '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__',# '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__',# 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag',# 'numerator', 'real', 'to_bytes']

对它们有个大概印象就可以了,具体怎么用,需要哪些参数 (argument),还需要查文档。看个 bit_length() 的例子。

【例子】找到一个整数的二进制表示,再返回其长度。

a = 1031print(bin(a))

# 0

b10000000111print(a.bit_length()) # 11

浮点型

【例子】

print(1, type(1))# 1 print(1., type(1.))# 1.0 a = 0.00000023b = 2.3e-7print(a)

# 2.3e-07print(b)

# 2.3e-07

有时候我们想保留浮点型的小数点后 n 位。可以用 decimal 包里的 Decimal 对象和 getcontext() 方法来 实现。

import decimalfrom decimal import Decimal

Python 里面有很多用途广泛的包 (package),用什么你就引进 (import) 什么。包也是对象,也可以用上面提到 的 dir(decimal) 来看其属性和方法。

【例子】 getcontext() 显示了 Decimal 对象的默认精度值是 28 位 ( prec=28 )。

a = decimal.getcontext()print(a)# Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,# capitals=1, clamp=0, flags=[],# traps=[InvalidOperation, DivisionByZero, Overflow])

b = Decimal(1) / Decimal(3)print(b)# 0.3333333333333333333333333333

【例子】使 1/3 保留 4 位,用 getcontext().prec 来调整精度。

decimal.getcontext().

prec = 4c = Decimal(1) / Decimal(3)print(c)# 0.3333

布尔型

布尔 (boolean) 型变量只能取两个值, True 和 False 。当把布尔型变量用在数字运算中,用 1 和 0 代表 True 和 False 。

【例子】

print(True + True) # 2print(True + False) # 1print(True * False) # 0

除了直接给变量赋值 True 和 False ,还可以用 bool(X) 来创建变量,其中 X 可以是

1. 基本类型:整型、浮点型、布尔型

2. 容器类型:字符串、元组、列表、字典和集合

【例子】 bool 作用在基本类型变量:X 只要不是整型 0 、浮点型 0.0 , bool(X) 就是 True ,其余就是 False 。

print(type(0), bool(0), bool(1))# False Trueprint(type(10.31), bool(0.00), bool(10.31))# False Trueprint(type(True), bool(False), bool(True))# False True

【例子】 bool 作用在容器类型变量:X 只要不是空的变量, bool(X) 就是 True ,其余就是 False 。

print(type(''), bool(''), bool('python'))# False Trueprint(type(()), bool(()), bool((10,)))# False Trueprint(type([]), bool([]), bool([1, 2]))# False Trueprint(type({}), bool({}), bool({'a': 1, 'b': 2}))# False Trueprint(type(set()), bool(set()), bool({1, 2}))# False True

确定 bool(X) 的值是 True 还是 False ,就看 X 是不是空,空的话就是 False ,不空的话就是 True 。

1. 对于数值变量, 0 , 0.0 都可认为是空的。

2. 对于容器变量,里面没元素就是空的。

获取类型信息

1. type(object) 获取类型信息

【例子】

print(type(1)) # print(type(5.2)) # print(type(True)) # print(type('5.2')) #

1. isinstance(object, classinfo) 判断一个对象是否是一个已知的类型。

【例子】

print(isinstance(1, int)) #True

print(isinstance(5.2, float)) #True

print(isinstance(True, bool)) #True

print(isinstance('5.2', str)) #True

注:

1. type() 不会认为子类是一种父类类型,不考虑继承关系。

2. isinstance() 会认为子类是一种父类类型,考虑继承关系。

如果要判断两个类型是否相同推荐使用 isinstance()

类型转换

1. 转换为整型 int(x, base=10)

2. 转换为字符串 str(object='')

3. 转换为浮点型 float(x)

【例子】

print(int('520')) # 520print(int(520.52)) # 520print(float('520.52')) # 520.52print(float(520)) # 520.0print(str(10 + 10)) # 20print(str(10.1 + 5.2)) # 15.3

1.5 print() 函数

print(*objects, sep=' ', end=' ', file=sys.stdout, flush=False)

1. 将对象以字符串表示的方式格式化输出到流文件对象file里。其中所有非关键字参数都按 str() 方式进行转换 为字符串输出;

2. 关键字参数 sep 是实现分隔符,比如多个参数输出时想要输出中间的分隔字符;

3. 关键字参数 end 是输出结束时的字符,默认是换行符 ;

4. 关键字参数 file 是定义流输出的文件,可以是标准的系统输出 sys.stdout ,也可以重定义为别的文件;

5. 关键字参数 flush 是立即把内容输出到流文件,不作缓存。

【例子】没有参数时,每次输出后都会换行。

shoplist = ['apple', 'mango', 'carrot', 'banana'

]print("This is printed without 'end'and 'sep'.")for item in shoplist:print(item)# This is printed without 'end'and 'sep'.# apple# mango# carrot# banana

【例子】每次输出结束都用 end 设置的参数 & 结尾,并没有默认换行。

shoplist = ['apple', 'mango', 'carrot', 'banana']print("This is printed with 'end='&''.")for item in shoplist:print(item, end='&')print('hello world')# This is printed with 'end='&''

.# apple&mango&carrot&banana&hello world

【例子】 item 值与 'another string' 两个值之间用 sep 设置的参数 & 分割。由于 end 参数没有设置,因此默 认是输出解释后换行,即 end 参数的默认值为 。

2 条件语句

2.1 if 语句

if expression:expr_true_suite

1. if 语句的 expr_true_suite 代码块只有当条件表达式 expression 结果为真时才执行,否则将继续执行紧 跟在该代码块后面的语句。

2. 单个 if 语句中的 expression 条件表达式可以通过布尔操作符 and , or 和 not 实现多重条件判断。

【例子】

if 2 > 1and not 2 > 3:

print('Correct Judgement!')# Correct Judgement!

2.2 if - else 语句

if expression:expr_true_suiteelse:expr_false_suite

1. Python 提供与 if 搭配使用的 else,如果 if 语句的条件表达式结果布尔值为假,那么程序将执行 else 语句后的 代码。

【例子】

temp = input("猜一猜小姐姐想的是哪个数字?")guess = int(temp) # input 函数将接收的任何数据类型都默认为 str。if guess == 666:print("你太了解小姐姐的心思了!")print("哼,猜对也没有奖励!")else:print("猜错了,小姐姐现在心里想的是666!")print("游戏结束,不玩儿啦!")

if 语句支持嵌套,即在一个 if 语句中嵌入另一个 if 语句,从而构成不同层次的选择结构。

【例子】Python 使用缩进而不是大括号来标记代码块边界,因此要特别注意 else 的悬挂问题。

hi = 6if hi > 2:if hi > 7:print('好棒!好棒!')else:print('切~')# 无输出

【例子】

temp = input("猜一猜小姐姐想的是哪个数字?")guess = int(temp)if guess > 8:print("大了,大了")else:if guess == 8:print("你太了解小姐姐的心思了!")print("哼,猜对也没有奖励!")else:print("小了,小了")print("游戏结束,不玩儿啦!")

2.3 if - elif - else 语句

if expression1:expr1_true_suiteelif expression2:expr2_true_suiteelif expressionN:exprN_true_suiteelse:expr_false_suite

1. elif 语句即为 else if,用来检查多个表达式是否为真,并在为真时执行特定代码块中的代码

【例子】

temp = input('请输入成绩:')source = int(temp)if 100 >= source >= 90:print('A')elif 90 > source >= 80:print('B')elif 80 > source >= 60:print('C')elif 60 > source >= 0:print('D')else:print('输入错误!')

2.4 assert 关键词

1. assert 这个关键词我们称之为"断言”,当这个关键词后边的条件为 False 时,程序自动崩溃并抛 出 AssertionError 的异常。

【例子】

my_list = ['lsgogroup']my_list.pop(0)assert len(my_list) > 0# AssertionError

【例子】在进行单元测试时,可以用来在程序中置入检查点,只有条件为 True 才能让程序正常工作。

assert 3 > 7#

AssertionError

3 循环语句

3.1 while 循环

while 语句最基本的形式包括一个位于顶部的布尔表达式,一个或多个属于 while 代码块的缩进语句。

while 布尔表达式:代码块

while 循环的代码块会一直循环执行,直到布尔表达式的值为布尔假。

如果布尔表达式不带有 <、>、==、!=、in、not in 等运算符,仅仅给出数值之类的条件,也是可以的。

当 while 后写入一个非零整数时,视为真值,执行循环体;写入 0 时,视为假值,不执行循环体。也可以写 入 str、list 或任何序列,长度非零则视为真值,执行循环体;否则视为假值,不执行循环体。

【例子】

count = 0while count < 3:temp = input("猜一猜小姐姐想的是哪个数字?")guess = int(temp)if guess > 8:print("大了,大了")else:if guess == 8:print("你太了解小姐姐的心思了!")print("哼,猜对也没有奖励!")count = 3else:print("小了,小了")count = count + 1print("游戏结束,不玩儿啦!")

【例子】布尔表达式返回0,循环终止。

string = 'abcd'while string:print(string)string = string[1:]# abcd# bcd# cd# d

3.2 while - else 循环

while 布尔表达式:代码块else:代码块

当 while 循环正常执行完的情况下,执行 else 输出,如果 while 循环中执行了跳出循环的语句,比如 break ,将不执行 else 代码块的内容。

【例子】

count = 0while count < 5:print("%d is less than 5" % count)count = count + 1else:print("%d is not less than 5" % count)# 0 is less than 5# 1 is less than 5# 2 is less than 5# 3 is less than 5# 4 is less than 5# 5 is not less than 5

【例子】

count = 0while count < 5:print("%d is less than 5" % count)count = 6breakelse:print("%d is not less than 5" % count)# 0 is less than 5

3.3 for 循环

for 循环是迭代循环,在Python中相当于一个通用的序列迭代器,可以遍历任何有序序列,

如 str、list、tuple 等,也可以遍历任何可迭代对象,如 dict 。

for 迭代变量 in 可迭代对象:代码块

每次循环,迭代变量被设置为可迭代对象的当前元素,提供给代码块使用。

【例子】

for i in 'ILoveLSGO':print(i, end=' ') # 不换行输出# I L o v e L S G O

【例子】

member = ['张三', '李四', '刘德华', '刘六', '周润发']for each in member:print(each)# 张三# 李四# 刘德华# 刘六# 周润发for i in range(len(member)):print(member[i])# 张三# 李四# 刘德华# 刘六# 周润发

【例子】

dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}for key, value in dic.items():print(key, value, sep=':', end=' ')# a:1 b:2 c:3 d:4

【例子】

dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}for key in dic.keys():print(key, end=' ')# a b c d

【例子】

dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}for value in dic.values():print(value, end=' ')# 1 2 3 4

3.4 for - else 循环

for 迭代变量 in 可迭代对象:代码块else:代码块

当 for 循环正常执行完的情况下,执行 else 输出,如果 for 循环中执行了跳出循环的语句,比如 break ,将不 执行 else 代码块的内容,与 while - else 语句一样。

【例子】

for num in range(10, 20): # 迭代 10 到 20 之间的数字for i in range(2, num): # 根据因子迭代if num % i == 0: # 确定第一个因子j = num / i # 计算第二个因子print('%d 等于 %d * %d' % (num, i, j))break # 跳出当前循环else: # 循环的 else 部分print(num, '是一个质数')# 10 等于 2 * 5# 11 是一个质数# 12 等于 2 * 6# 13 是一个质数# 14 等于 2 * 7# 15 等于 3 * 5# 16 等于 2 * 8# 17 是一个质数# 18 等于 2 * 9# 19 是一个质数

3.5 range() 函数

range([start,] stop[, step=1])

1. 这个BIF(Built-in functions)有三个参数,其中用中括号括起来的两个表示这两个参数是可选的。

2. step=1 表示第三个参数的默认值是1。

3. range 这个BIF的作用是生成一个从 start 参数的值开始到 stop 参数的值结束的数字序列,该序列包 含 start 的值但不包含 stop 的值。

【例子】

for i in range(2, 9): # 不包含9print(i)# 2# 3# 4# 5# 6# 7# 8

【例子】

for i in range(1, 10, 2):print(i)# 1# 3# 5# 7# 9

3.6 enumerate()函数

enumerate(sequence, [start=0])

1. sequence:一个序列、迭代器或其他支持迭代对象。

2. start:下标起始位置。

3. 返回 enumerate(枚举) 对象

【例子】

seasons = ['Spring', 'Summer', 'Fall', 'Winter']lst = list(enumerate(seasons))print(lst)# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')

]lst = list(enumerate(seasons, start=1)) # 下标从 1 开始print(lst)# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

用 enumerate(A) 不仅返回了 A 中的元素,还顺便给该元素一个索引值 (默认从 0 开始)。此外,用 enumerate(A, j) 还可以确定索引起始值为 j 。

【例子】

languages = ['Python', 'R', 'Matlab', 'C++']for language in languages:print('I love', language)print('Done!')# I love Python# I love R# I love Matlab# I love C++# Done!for i, language in enumerate(languages, 2):print(i, 'I love', language)print('Done!')# 2 I love Python# 3 I love R# 4 I love Matlab# 5 I love C++# Done!

3.7 break 语句

break 语句可以跳出当前所在层的循环。

【例子】

import randomsecret = random.randint(1, 10) #[1,10]之间的随机数while True:temp = input("猜一猜小姐姐想的是哪个数字?")guess = int(temp)if guess > secret:print("大了,大了")else:if guess == secret:print("你太了解小姐姐的心思了!")print("哼,猜对也没有奖励!")breakelse:print("小了,小了")print("游戏结束,不玩儿啦!")

3.8 continue 语句

continue 终止本轮循环并开始下一轮循环。

【例子】

for i in range(10):if i % 2 != 0:print(i)continuei += 2print(i)# 2# 1# 4# 3# 6# 5# 8# 7# 10# 9

3.9 pass 语句

pass 语句的意思是"不做任何事”,如果你在需要有语句的地方不写任何语句,那么解释器会提示出错,而 pass 语句就是用来解决这些问题的。

【例子】

def a_func():# SyntaxError: unexpected EOF while parsing

【例子】

def a_func():pass

pass 是空语句,不做任何操作,只起到占位的作用,其作用是为了保持程序结构的完整性。尽管 pass 语句不做 任何操作,但如果暂时不确定要在一个位置放上什么样的代码,可以先放置一个 pass 语句,让代码可以正常运 行

3.10 推导式

列表推导式

[ expr for value in collection [if condition] ]

【例子】

x = [-4, -2, 0, 2, 4]y = [a * 2 for a in x]print(y)# [-8, -4, 0, 4, 8]

【例子】

x = [i ** 2

for i in range(1, 10)]print(x)# [1, 4, 9, 16, 25, 36, 49, 64, 81]

【例子】

x = [(i, i ** 2)

for i in range(6)]print(x)# [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

【例子】

x = [i for i in range(100)

if (i % 2) != 0 and (i % 3) == 0]print(x)# [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99]

【例子】

a = [(i, j) for i in range(0, 3)

for j in range(0, 3)]print(a)# [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

【例子】

x = [[i, j]

for i in range(0, 3)

for j in range(0, 3)]print(x)# [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]x[0][0] = 10print(x)# [[10, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

【例子】

a = [(i, j)

for i in range(0, 3)

if i < 1 for j in range(0, 3)

if j > 1]print(a)# [(0, 2)]

元组推导式

( expr for value in collection [if condition] )

【例子】

a = (x for x in range(10))print(a)# at 0x0000025BE511CC48>print(tuple(a))# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

字典推导式

【例子】

b = {i: i % 2 == 0 for i in range(10)

if i % 3 == 0}print(b)# {0: True, 3: False, 6: True, 9: False}

集合推导式

{ expr for value in collection [if condition] }

【例子】

c = {i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}print(c)# {1, 2, 3, 4, 5, 6}

其它

1. next(iterator[, default]) Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIteration.

【例子】

e = (i for i in range(10))print(e)# at 0x0000007A0B8D01B0>print(next(e)) # 0print(next(e)) #

1for each in e:print(each, end=' ')# 2 3 4 5 6 7 8 9

【例子】

s = sum([i for i in range(101)])print(s) # 5050s = sum((i for i in range(101)))print(s) # 5050

4 异常处理

异常就是运行期检测到的错误。计算机语言针对可能出现的错误定义了异常类型,某种错误引发对应的异常时, 异常处理程序将被启动,从而恢复程序的正常运行。

5.1 Python 标准异常总结

1. BaseException:所有异常的 基类

2. Exception:常规异常的 基类

3. SyntaxError:语法错误导致的异常

4. IndentationError:缩进错误导致的异常

5. ValueError:传入无效的参数

5.2 Python标准警告总结

1. Warning:警告的基类

2. DeprecationWarning:关于被弃用的特征的警告

3. FutureWarning:关于构造将来语义会有改变的警告

4. UserWarning:用户代码生成的警告

5. PendingDeprecationWarning:关于特性将会被废弃的警告

(这些不需要记用到百度即可)

4.3 try - except 语句

try:检测范围except Exception[as reason]:出现异常后的处理代码

try 语句按照如下方式工作:

1. 首先,执行 try 子句(在关键字 try 和关键字 except 之间的语句)

2. 如果没有异常发生,忽略 except 子句, try 子句执行后结束。

3. 如果在执行 try 子句的过程中发生了异常,那么 try 子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符,那么对应的 except 子句将被执行。最后执行 try - except 语句之后的代码。

4. 如果一个异常没有与任何的 except 匹配,那么这个异常将会传递给上层的 try 中。

【例子】

try:f = open('test.txt')print(f.read())f.close()except OSError:print('打开文件出错')# 打开文件出错

【例子】

try:f = open('test.txt')print(f.read())f.close()except OSError as error:print('打开文件出错 原因是:' + str(error))# 打开文件出错# 原因是:

[Errno 2] No such file or directory: 'test.txt'

一个 try 语句可能包含多个 except 子句,分别来处理不同的特定的异常。最多只有一个分支会被执行。

【例子】

try:int("abc")s = 1 + '1'f = open('test.txt')print(f.read())f.close()except OSError as error:print('打开文件出错 原因是:' + str(error))except TypeError as error:print('类型出错 原因是:' + str(error))except ValueError as error:print('数值出错 原因是:' + str(error))# 数值出错# 原因是:invalid literal for int() with base 10: 'abc'

【例子】

dict1 = {'a': 1, 'b': 2, 'v': 22}try:x = dict1['y']except LookupError:print('查询错误')except KeyError:print('键错误')else:print(x)# 查询错误

try-except-else 语句尝试查询不在 dict 中的键值对,从而引发了异常。这一异常准确地说应属 于 KeyError ,但由于 KeyError 是 LookupError 的子类,且将 LookupError 置于 KeyError 之前,因此程序 优先执行该 except 代码块。所以,使用多个 except 代码块时,必须坚持对其规范排序,要从最具针对性的异常 到最通用的异常。

【例子】

dict1 = {'a': 1, 'b': 2, 'v': 22}try:x = dict1['y']except KeyError:print('键错误')except LookupError:print('查询错误')else:print(x)# 键错误

【例子】一个 except 子句可以同时处理多个异常,这些异常将被放在一个括号里成为一个元组。

try:s = 1 + '1'int("abc")f = open('test.txt')print(f.read())f.close()except (OSError, TypeError, ValueError) as error:print('出错了! 原因是:' + str(error))# 出错了!# 原因是:unsupported operand type(s) for +: 'int' and 'str'

4.6 raise语句

Python 使用 raise 语句抛出一个指定的异常。

【例子】

try:raise NameError('HiThere')except NameError:print('An exception flew by!')# An exception flew by!

python必备入门代码-python基础入门这一篇就够相关推荐

  1. 零基础python必背代码-零基础入门学习python 96集全

    零基础入门学习python 96集全 第000讲 愉快的开始(视频+课件)xa0 第001讲 我和Python第一次亲密接触(视频+课件)xa0 第002讲 用Python设第一个游戏(视频+课件+源 ...

  2. python是什么软件-零基础入门Python怎么学习?老男孩python用什么软件

    在培训学习Python时,怎么才能学好Python?随着Python技术的发展,越来越多的人开始学习Python编程语言,那么零基础入门Python该怎么学习? 1.要养成良好的代码编写习惯,注重细节 ...

  3. Python从入门到实战 基础入门视频教程(讲解超细致)-黄勇-专题视频课程

    Python从入门到实战 基础入门视频教程(讲解超细致)-4123人已学习 课程介绍         Python基础入门视频教程:本课程从Python入门到纯Python项目实战.超100以上课时, ...

  4. python入门到实践-Python编程从入门到实践(基础入门)

    Python编程从入门到实践-------基础入门 1.Python中的变量 2.Python首字母大写使用title()方法,全部大写upper()方法,全部小写lower()方法 3.Python ...

  5. Python 3.X 完全零基础入门精讲 全套视频教程

    简介 零基础小白快速学程序员大爱语言――Python,易学易用易就业!!! 目标人群:熟悉电脑基本操作,编程零基础或已具备Python或其它编程语言的人群. 课程目标:绝对零基础Python3.x 入 ...

  6. python一千行入门代码-Python 有哪些一千行左右的经典练手项目?

    谢邀.据我了解,没有千行左右的「经典」练手项目.但是我可以推荐一些练手项目.这些项目来着 教你阅读Python开源项目代码 - Python之美 - 知乎专栏 : 和工作中看别人代码差不多,基本每个人 ...

  7. python装饰器功能是冒泡排序怎么做_传说中Python最难理解的点|看这完篇就够了(装饰器)...

    https://mp.weixin.qq.com/s/B6pEZLrayqzJfMtLqiAfpQ 1.什么是装饰器 网上有人是这么评价装饰器的,我觉得写的很有趣,比喻的很形象 每个人都有的内裤主要是 ...

  8. python详细安装教程-超详细Python与PyCharm安装教程,看这一篇就够了

    原标题:超详细Python与PyCharm安装教程,看这一篇就够了 学习了三天的python, 之前测试一直用课程自带的网页版玩玩, 为了学习 然后就下载了一个python和pycharm 现在分享下 ...

  9. 前端linux基础,这一篇就够了

    前端linux基础,这一篇就够了 退出当前操作 清理命令窗口 关闭命令窗口 创建文件 创建文件夹 删除文件 删除文件夹 重命名文件 发起请求(curl) 切换工作目录 查看当前完整路径 查看当前目录下 ...

  10. 零基础学python pdf-笔记《零基础入门学习Python(第2版)》PDF+课件+代码分析

    通过自学编程,感觉到基础知识很重要,越到后面越能发现这一点,光记住是不行的,还要灵活运用,要多调试代码,计算机就是一个不断练习,不断遇到问题,解决问题的工种,要根据实际的业务能想到对应的语法,实际项目 ...

最新文章

  1. mybatis的一些基础问题
  2. python使用imbalanced-learn的EditedNearestNeighbours方法进行下采样处理数据不平衡问题
  3. 经验总结--我的小程序开发和进化之路
  4. 【android】两个按钮的宽度各占屏幕的一半
  5. boost::container实现显式实例静态向量测试程序
  6. 数据库事务原理详解-数据库隔离级别
  7. 微信php翻译和天气预报整合,微信公众平台天气预报功能开发
  8. 中国凝胶密封高效空气过滤器行业市场供需与战略研究报告
  9. js 小数自动补0_JS自定义保留小数,并支持补零(四舍五入)
  10. URAL 1732. Ministry of Truth ( KMP 多模式串匹配 )
  11. PHP 获取微视无水印源地址_小红书无水印视频解析下载|小红书在线去水印|小红书视频解析API接口...
  12. 插图详解Python解决汉诺塔问题
  13. Endnote常见错误
  14. Htmlcssjs 图片轮播,加箭头
  15. 对话马丁·福勒(Martin Fowler)——第六部分:性能与过程调优
  16. 手写sql语句面试题
  17. Android开发和安全系列工具
  18. pdcp层的作用_LTE协议栈总体架构、PDCP层及RLC层概述
  19. python中multiprocessing.Manger()支持类型
  20. CISCO-路由器交换机密码恢复

热门文章

  1. 设计模式综和实战项目x-gen系列一
  2. IE代理服务器出错导致浏览器无法上网
  3. 牛客网在线编程:公共字符
  4. 项目笔记:分层模型建立
  5. JDK/JRE/JVM之间的关系
  6. [Django]我的第一个网页,报错啦~(自己实现过程中遇到问题以及解决办法)
  7. bzoj 3670 [NOI2014]动物园
  8. spring mvc综合easyui点击上面菜单栏中的菜单项问题
  9. Vijos P1335 数独验证【谜题】
  10. CCF NOI1016 计算天数