打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python版 编程语言入门经典100例 python编程入门基础
userphoto

2023.11.10 甘肃

关注

本文主要内容:变量、运算符、数据类型、位运算、条件语句、循环语句、异常处理。

一、python入门

1.1 简介

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

1.2 变量、运算符与数据类型

1.2.1 注释

在python中,#表示注释,作用于整行。

#这是一行注释
  • 1.

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

'''
这是
多行
注释
'''
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

 1.2.2 运算符

算数运算符:

print(1 1) # 2 print(2 - 1) # 1 print(3 * 4) # 12 print(3 / 4) # 0.75 print(3 // 4) # 0 print(3 % 4) # 3 print(2 ** 3) # 8
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

 比较运算符:

print(2 > 1)  # True
print(2 >= 4)  # False
print(1 < 2)  # True
print(5 <= 2)  # False
print(3 == 4)  # False
print(3 != 5)  # True
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

 逻辑运算符

print((3 > 2) and (3 < 5)) # True print((1 > 3) or (9 < 2)) # False print(not (2 > 1)) # False
  • 1.
  • 2.
  • 3.

 位运算符

print(bin(4))  # 0b100
print(bin(5))  # 0b101
print(bin(~4), ~4)  # -0b101 -5
print(bin(4 & 5), 4 & 5)  # 0b100 4
print(bin(4 | 5), 4 | 5)  # 0b101 5
print(bin(4 ^ 5), 4 ^ 5)  # 0b1 1
print(bin(4 << 2), 4 << 2)  # 0b10000 16
print(bin(4 >> 2), 4 >> 2)  # 0b1 1
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

 三元运算符

# 没有三元运算符这样写 x, y = 4, 5 if x < y: small = x else: small = y print(small) # 4
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
# 有三元运算符这样写
x, y = 4, 5
small = x if x < y else y
print(small)  # 4
  • 1.
  • 2.
  • 3.
  • 4.

 其他运算符

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
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
a = 'hello'
b = 'hello'
print(a is b, a == b)  # True True
print(a is not b, a != b)  # False False

a = ['hello']
b = ['hello']
print(a is b, a == b)  # False True
print(a is not b, a != b)  # True False
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

注意:

  • is,is not 对比的是两个变量的内存地址;
  • ==,!=对比的是两个变量的值;
  • 比较两个变量,指向的地址是不可变的类型(str等),那么is,is not和==,!=是完全等价的
  • 比较两个变量,指向的地址是可变的类型(list、dict、tuple等),两者是有区别的。

运算符的优先级

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

 1.3 变量和赋值

  • 在使用变量之前,需要对其进行复制
  • 变量名可以包含字母数字下划线、但不能以数字开头
  • 区分大小写

1.4 数据类型与转换

# 通过print()可以查看a的值和类型
a = 1031
print(a, type(a))
# 1031 <class 'int'>
  • 1.
  • 2.
  • 3.
  • 4.
# 将一个整数转换为二进制并返回其长度 a = 1031 print(bin(a)) print(a.bit_length())
  • 1.
  • 2.
  • 3.
  • 4.

浮点型

print(1, type(1))
# 1 <class 'int'>

print(1., type(1.))
# 1.0 <class 'float'>

a = 0.00000023
b = 2.3e-7
print(a)  # 2.3e-07
print(b)  # 2.3e-07
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

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

import decimal from decimal import Decimal 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保留四位,使用getcontext().prec来调整精度 decimal.getcontext().prec = 4 c = Decimal(1) / Decimal(3) print(c) # 0.3333
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

布尔型

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

print(True   True) #2
print(True   False) #1
print(False   False) #0
  • 1.
  • 2.
  • 3.

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

  • 基本类型:整型、浮点型、布尔型
  • 容器类型:字符串、元组、列表、字典和集合
# bool作用于基本变量类型:x只要不是整型0、浮点型0.0,bool(x)就是true,其余都是false print(type(0), bool(0), bool(1)) # <class 'int'> False True print(type(10.31), bool(0.00), bool(10.31)) # <class 'float'> False True print(type(True), bool(False), bool(True)) # <class 'bool'> False True
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
# bool作用于容器类型变量:x只要不是空的变量,bool(x)就是true,其余就是false
print(type(''), bool(''), bool('python'))
# <class 'str'> False True

print(type(()), bool(()), bool((10,)))
# <class 'tuple'> False True

print(type([]), bool([]), bool([1, 2]))
# <class 'list'> False True

print(type({}), bool({}), bool({'a': 1, 'b': 2}))
# <class 'dict'> False True

print(type(set()), bool(set()), bool({1, 2}))
# <class 'set'> False True
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

小结:确定bool(x)是true还是false,就看x是否为空,空的话就是false,非空就是true。对于数值变量0为空,容器变量里面没有元素就是空。

获取类型信息

type(object)

print(isinstance(1, int)) # True print(isinstance(5.2, float)) # True print(isinstance(True, bool)) # True print(isinstance('5.2', str)) # True
  • 1.
  • 2.
  • 3.
  • 4.

类型转换

  • 转换为整型 int(x, base=10)
  • 转换为字符型str(object=' ')
  • 转换为浮点型float(x)
print(int('520'))  # 520
print(int(520.52))  # 520
print(float('520.52'))  # 520.52
print(float(520))  # 520.0
print(str(10   10))  # 20
print(str(10.1   5.2))  # 15.3
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

1.5 print()函数

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
  • 1.
  • 将对象以字符串表示的方式格式化输出到流文件file里,其中所有非关键字参数都按照str()方式进行转换为字符串输出;
  • 关键字参数sep是实现分隔符,比如多个参数输出时想要输出中间的分割字符;
  • 关键字参数end是输出结束时的字符,默认是换行符\n;
  • 关键字参数file是定义流输出的文件,可以说标准的系统输出sys.stdout,也可以重定义为别的文件;
  • 关键字参数flush是立即把内容输出到流文件,不做缓存。
# 没有参数时,每次输出后都会换行。
shoplist = ['apple', 'mango', 'carrot', 'banana']
print('This is printed without 'end' and 'step'.')
for item in shoplist:
    print(item)

    # This is printed without 'end'and 'sep'.
    # apple
    # mango
    # carrot
    # banana
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
# 每次输出都用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
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
# 将seq设置为&
shoplist = ['apple', 'mango', 'carrot', 'banana']
print('This is printed with 'sep='&''.')
for item in shoplist:
    print(item, 'another string', sep='&')

# This is printed with 'sep='&''.
# apple&another string
# mango&another string
# carrot&another string
# banana&another string
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

2. 位运算

2.1 原码、反码和补码

二进制有三种不同的表示形式:原码反码和补码,计算机内部使用补码来表示。

原码:其实就是二进制表示,第一位是符号位

00 00 00 11 -> 3

10 00 00 11 -> -3

反码:正数的原码就是反码,负数的反码是符号位不变,其余位取反

00 00 00 11 -> 3

11 11 11 00 -> -3

补码:正数的原码就是补码,负数的补码就是反码 1 

00 00 00 11 -> 3

11 11 11 01 -> -3

符号位:最高位为符号位,0表示正数,1表示负数。在位运算中,符号也参加运算

2.2 按位运算

  • 按位非操作 ~
  • 按位与操作 &
  • 按位或操作 |
  • 按位异或操作(不同为1) ^
  • 按位左移操作<< (num<<i 将num的二进制向左移动i位所得的值)
  • 按位右移操作>> (num>>i 将num的二进制向右移动i位所得的值)

2.3 利用位运算实现快速计算

利用<<,>>快速计算2的倍数的问题

 使用^快速交换两个整数。

 通过a&(-a)快速获取a的最后一位为1的整数

 2.4 利用位运算实现整数集合

元素与集合的操作

 集合之间的操作:

 注意:整数在内存中是以补码的形式存在的,输出自然也是按照补码输出。

3 条件语句

3.1 if 语句

if 2 > 1 and not 2 > 3: print('Correct Judgement!') # Correct Judgement!
  • 1.
  • 2.
  • 3.
  • 4.

3.2 if - else 语句

temp = input('猜一猜小姐姐想的是哪个数字?')
guess = int(temp) # input 函数将接收的任何数据类型都默认为 str。
if guess == 666:
    print('你太了解小姐姐的心思了!')
    print('哼,猜对也没有奖励!')
else:
    print('猜错了,小姐姐现在心里想的是666!')
print('游戏结束,不玩儿啦!')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
# Python 使用缩进而不是大括号来标记代码块边界,因此要特别注意else的悬挂问题。 hi = 6 if hi > 2: if hi > 7: print('好棒!好棒!') else: print('切~') # 无输出
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

3.3 if - elif - else

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('输入错误!')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

3.4 assert 关键词

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

my_list = ['lsgogroup'] my_list.pop(0) assert len(my_list) > 0 # AssertionError
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
# 在进行单元测试时,可以用来在程序中置入检查点,只有条件为 True 才能让程序正常工作。
assert 3 > 7

# AssertionError
  • 1.
  • 2.
  • 3.
  • 4.

4. 循环语句

4.1 while 循环

count = 0 while count < 3: temp = input('猜一猜小姐姐想的是哪个数字?') guess = int(temp) if guess > 8: print('大了,大了') else: if guess == 8: print('你太了解小姐姐的心思了!') print('哼,猜对也没有奖励!') count = 3 else: print('小了,小了') count = count 1 print('游戏结束,不玩儿啦!')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

4.2 while - else 循环

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

count = 0
while count < 5:
    print('%d is  less than 5' % count)
    count = count   1
else:
    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
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

4.3 for 循环

for i in 'ILoveLSGO': print(i, end=' ') # 不换行输出 # I L o v e L S G O
  • 1.
  • 2.
  • 3.
  • 4.
member = ['张三', '李四', '刘德华', '刘六', '周润发']
for each in member:
    print(each)

# 张三
# 李四
# 刘德华
# 刘六
# 周润发

for i in range(len(member)):
    print(member[i])

# 张三
# 李四
# 刘德华
# 刘六
# 周润发
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
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
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

for key in dic.keys():
    print(key, end=' ')

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

4.4 for - 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 是一个质数
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

 4.5 range() 函数

这个BIF(built-in functions 内置函数)有三个参数,其中用中括号括起来的表示这两个参数是可以省略的;step表示第三个参数的默认值是1;该函数的作用是生成一个从start参数的值开始到stop参数的值结束的数字序列,该序列包含start的值,但不包括stop的值。

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

# 1
# 3
# 5
# 7
# 9
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

4.6 enumerate() 函数

sequence是一个序列,迭代器或其他支持迭代的对象;start是下标的起始位置;返回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')]
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

 enumerate()与for循环的结合使用

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!
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

4.7 break 语句

跳出当前所在层的循环。

4.8 continue语句

结束本轮循环并开始下一轮循环。

4.9 pass语句

不做任何事。主要作用是为了保持程序结构的完整性。

4.10 推导式

x = [-4, -2, 0, 2, 4] y = [a * 2 for a in x] print(y) # [-8, -4, 0, 4, 8]
  • 1.
  • 2.
  • 3.
  • 4.
x = [i ** 2 for i in range(1, 10)]
print(x)
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
  • 1.
  • 2.
  • 3.
x = [(i, i ** 2) for i in range(6)] print(x) # [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
  • 1.
  • 2.
  • 3.
  • 4.
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]
  • 1.
  • 2.
  • 3.
  • 4.
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)]
  • 1.
  • 2.
  • 3.
  • 4.
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] = 10
print(x)
# [[10, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
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)]
  • 1.
  • 2.
  • 3.
  • 4.

元组推导式:

a = (x for x in range(10))
print(a)

# <generator object <genexpr> at 0x0000025BE511CC48>

print(tuple(a))

# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

 字典推导式:

b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0} print(b) # {0: True, 3: False, 6: True, 9: False}
  • 1.
  • 2.
  • 3.

 集合推导式:

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.
  • 2.
  • 3.

 其他:

e = (i for i in range(10)) print(e) # <generator object <genexpr> at 0x0000007A0B8D01B0> print(next(e)) # 0 print(next(e)) # 1 for each in e: print(each, end=' ') # 2 3 4 5 6 7 8 9
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
s = sum([i for i in range(101)])
print(s)  # 5050
s = sum((i for i in range(101)))
print(s)  # 5050
  • 1.
  • 2.
  • 3.
  • 4.

5. 异常处理

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

5.1 python标准异常

  • BaseException:所有异常的 基类
  • Exception:常规异常的 基类
  • StandardError:所有的内建标准异常的基类
  • ArithmeticError:所有数值计算异常的基类
  • FloatingPointError:浮点计算异常
  • OverflowError:数值运算超出最大限制
  • ZeroDivisionError:除数为零
  • AssertionError:断言语句(assert)失败
  • AttributeError:尝试访问未知的对象属性
  • EOFError:没有内建输入,到达EOF标记
  • EnvironmentError:操作系统异常的基类
  • IOError:输入/输出操作失败
  • OSError:操作系统产生的异常(例如打开一个不存在的文件)
  • WindowsError:系统调用失败
  • ImportError:导入模块失败的时候
  • KeyboardInterrupt:用户中断执行
  • LookupError:无效数据查询的基类
  • IndexError:索引超出序列的范围
  • KeyError:字典中查找一个不存在的关键字
  • MemoryError:内存溢出(可通过删除对象释放内存)
  • NameError:尝试访问一个不存在的变量
  • UnboundLocalError:访问未初始化的本地变量
  • ReferenceError:弱引用试图访问已经垃圾回收了的对象
  • RuntimeError:一般的运行时异常
  • NotImplementedError:尚未实现的方法
  • SyntaxError:语法错误导致的异常
  • IndentationError:缩进错误导致的异常
  • TabError:Tab和空格混用
  • SystemError:一般的解释器系统异常
  • TypeError:不同类型间的无效操作
  • ValueError:传入无效的参数
  • UnicodeError:Unicode相关的异常
  • UnicodeDecodeError:Unicode解码时的异常
  • UnicodeEncodeError:Unicode编码错误导致的异常
  • UnicodeTranslateError:Unicode转换错误导致的异常

异常体系内部有层次关系,python异常体系中的部分关系如下所示:

5.2 python标准警告

  • Warning:警告的基类
  • DeprecationWarning:关于被弃用的特征的警告
  • FutureWarning:关于构造将来语义会有改变的警告
  • UserWarning:用户代码生成的警告
  • PendingDeprecationWarning:关于特性将会被废弃的警告
  • RuntimeWarning:可疑的运行时行为(runtime behavior)的警告
  • SyntaxWarning:可疑语法的警告
  • ImportWarning:用于在导入模块过程中触发的警告
  • UnicodeWarning:与Unicode相关的警告
  • BytesWarning:与字节或字节码相关的警告
  • ResourceWarning:与资源使用相关的警告

5.3 try - expect 语句

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

  • 首先,执行try子句。(在关键字try和关键字except之间的语句)
  • 如果没有异常发生,忽略except子句,try子句执行后结束。
  • 如果在执行try子句的过程中发生了异常,那么try子句余下的部分将被忽略。如果异常的类型和except之后的名称相符,那么对应的except子句将被执行。最后执行try - except语句之后的代码。
  • 如果一个异常没有与任何的except匹配,那么这个异常将会传递给上层的try中。
try: f = open('test.txt') print(f.read()) f.close() except OSError: print('打开文件出错') # 打开文件出错
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
try:
    f = open('test.txt')
    print(f.read())
    f.close()
except OSError as error:
    print('打开文件出错\n原因是:'   str(error))

# 打开文件出错
# 原因是:[Errno 2] No such file or directory: 'test.txt'
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
try: int('abc') s = 1 '1' f = open('test.txt') print(f.read()) f.close() except OSError as error: print('打开文件出错\n原因是:' str(error)) except TypeError as error: print('类型出错\n原因是:' str(error)) except ValueError as error: print('数值出错\n原因是:' str(error)) # 数值出错 # 原因是:invalid literal for int() with base 10: 'abc'
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
dict1 = {'a': 1, 'b': 2, 'v': 22}
try:
    x = dict1['y']
except LookupError:
    print('查询错误')
except KeyError:
    print('键错误')
else:
    print(x)

# 查询错误
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
# 要注意错误的优先级 dict1 = {'a': 1, 'b': 2, 'v': 22} try: x = dict1['y'] except KeyError: print('键错误') except LookupError: print('查询错误') else: print(x) # 键错误
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
# 一个 except 子句可以同时处理多个异常,这些异常将被放在一个括号里成为一个元组。
try:
    s = 1   '1'
    int('abc')
    f = open('test.txt')
    print(f.read())
    f.close()
except (OSError, TypeError, ValueError) as error:
    print('出错了!\n原因是:'   str(error))

# 出错了!
# 原因是:unsupported operand type(s) for  : 'int' and 'str'
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

5.4 try - expect - finally 语句

try:检测范围;expect expcetion[as reason]:出现异常后的处理代码finally:无论如何都会被执行的代码。不管try语句里面有没有异常,finally子句都会执行。

def divide(x, y): try: result = x / y print('result is', result) except ZeroDivisionError: print('division by zero!') finally: print('executing finally clause') divide(2, 1) # result is 2.0 # executing finally clause divide(2, 0) # division by zero! # executing finally clause divide('2', '1') # executing finally clause # TypeError: unsupported operand type(s) for /: 'str' and 'str'
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

5.5 try - except - else 语句

如果try子句执行时没有发生异常,python执行else语句后的语句。

使用except而不带任何的异常,这不是一个很好的方式,我们不能通过该程序识别出具体的异常信息,因为它捕获所有的异常。

try:检测范围;except(exception1[,exception2[,...exceptionN]]]):发生以上多个异常中的一个,执行这块代码;else:如果没有异常执行这块代码。

try:
    fh = open('testfile.txt', 'w')
    fh.write('这是一个测试文件,用于测试异常!!')
except IOError:
    print('Error: 没有找到文件或读取文件失败')
else:
    print('内容写入文件成功')
    fh.close()

# 内容写入文件成功
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

 5.6 raise 语句

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

try: raise NameError('HiThere') except NameError: print('An exception flew by!') # An exception flew by!
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
Python编程入门——基础语法详解(经典)
Python流程控制-if语句
万字长文丨大白话带你由浅入深Python编程语言
Python循环语句代码逐行详解:while、for、break和continue
Python入门(5)——分支与循环
python语法基础
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服