Python基础知识学习
参考:链接: 阿里天池.
# 这是一个注释
print("Hello world")
Hello world
'''
这是多行注释,用三个单引号
这是多行注释,用三个单引号
这是多行注释,用三个单引号
'''
print("Hello china")
"""
这是多行注释,用三个双引号
这是多行注释,用三个双引号
这是多行注释,用三个双引号
"""
print("hello china")
Hello china
hello china
print("hello philgent")
hello philgent
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
2
1
12
0.75
0
3
8
print(2 > 1) # True
print(2 >= 4) # False
print(1 < 2) # True
print(5 <= 2) # False
print(3 == 4) # False
print(3 != 5) # True
True
False
True
False
False
True
print((3 > 2) and (3 < 5)) # True
print((1 > 3) or (9 < 2)) # False
print(not (2 > 1)) # False
True
False
False
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
0b100
0b101
-0b101 -5
0b100 4
0b101 5
0b1 1
0b10000 16
0b1 1
x, y = 4, 5
if x < y:
small = x
else:
small = y
print(small) # 4
4
x, y = 4, 5
small = x if x < y else y
print(small) # 4
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
A exists
h not exists
a = "hello"
b = "hello"
print(a is b, a == b) # True True
print(a is not b, a != b) # False False
True True
False False
a = ["hello"]
b = ["hello"]
print(a is b, a == b) # False True
print(a is not b, a != b) # True False
False True
True False
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
-9
0.1111111111111111
0
-12.5
True
a = "hello"
b = "hello"
print(a is b, a == b)
True True
first = 2
second = 3
third = first + second
print(third) # 5
5
myTeacher = "老马的程序人生"
yourTeacher = "小马的程序人生"
ourTeacher = myTeacher + ',' + yourTeacher
print(ourTeacher) # 老马的程序人生,小马的程序人生
老马的程序人生,小马的程序人生
set_1 = {"欢迎", "学习","Python"}
print(set_1.pop())
Python
a = 1031
print(a, type(a))
# 1031 <class 'int'>
1031 <class 'int'>
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__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
a = 1031
print(bin(a)) # 0b10000000111
print(a.bit_length()) # 11
0b10000000111
11
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 <class 'int'>
1.0 <class 'float'>
2.3e-07
2.3e-07
保存浮点型的小数点后n位
import decimal
from decimal import Decimal
print(dir(decimal))
['BasicContext', 'Clamped', 'Context', 'ConversionSyntax', 'Decimal', 'DecimalException', 'DecimalTuple', 'DefaultContext', 'DivisionByZero', 'DivisionImpossible', 'DivisionUndefined', 'ExtendedContext', 'FloatOperation', 'HAVE_CONTEXTVAR', 'HAVE_THREADS', 'Inexact', 'InvalidContext', 'InvalidOperation', 'MAX_EMAX', 'MAX_PREC', 'MIN_EMIN', 'MIN_ETINY', 'Overflow', 'ROUND_05UP', 'ROUND_CEILING', 'ROUND_DOWN', 'ROUND_FLOOR', 'ROUND_HALF_DOWN', 'ROUND_HALF_EVEN', 'ROUND_HALF_UP', 'ROUND_UP', 'Rounded', 'Subnormal', 'Underflow', '__builtins__', '__cached__', '__doc__', '__file__', '__libmpdec_version__', '__loader__', '__name__', '__package__', '__spec__', '__version__', 'getcontext', 'localcontext', 'setcontext']
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])
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
0.3333333333333333333333333333
print(True + True) # 2
print(True + False) # 1
print(True * False) # 0
2
1
0
# 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
<class 'int'> False True
<class 'float'> False True
<class 'bool'> False True
# 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
<class 'str'> False True
<class 'tuple'> False True
<class 'list'> False True
<class 'dict'> False True
<class 'set'> False True
print(isinstance(1, int)) # True
print(isinstance(5.2, float)) # True
print(isinstance(True, bool)) # True
print(isinstance('5.2', str)) # True
# 如果要判断两个类型是否相同 则使用isinstance()
True
True
True
True
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
520
520
520.52
520.0
20
15.3
# print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
'''
将对象以字符串表示的方式格式化输出到流文件对象file里。其中所有非关键字参数都按str()方式进行转换为字符串输出;
关键字参数sep是实现分隔符,比如多个参数输出时想要输出中间的分隔字符;
关键字参数end是输出结束时的字符,默认是换行符\n;
关键字参数file是定义流输出的文件,可以是标准的系统输出sys.stdout,也可以重定义为别的文件;
关键字参数flush是立即把内容输出到流文件,不作缓存。
'''
'\n\n 将对象以字符串表示的方式格式化输出到流文件对象file里。其中所有非关键字参数都按str()方式进行转换为字符串输出;\n 关键字参数sep是实现分隔符,比如多个参数输出时想要输出中间的分隔字符;\n 关键字参数end是输出结束时的字符,默认是换行符\n;\n 关键字参数file是定义流输出的文件,可以是标准的系统输出sys.stdout,也可以重定义为别的文件;\n 关键字参数flush是立即把内容输出到流文件,不作缓存。\n\n'
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
This is printed without 'end'and 'sep'.
apple
mango
carrot
banana
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
This is printed with 'end='&''.
apple&mango&carrot&banana&hello world
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
This is printed with 'sep='&''.
apple&another string
mango&another string
carrot&another string
banana&another string
'''
通过 <<,>> 快速计算2的倍数问题。
n << 1 -> 计算 n*2
n >> 1 -> 计算 n/2,负奇数的运算不可用
n << m -> 计算 n*(2^m),即乘以 2 的 m 次方
n >> m -> 计算 n/(2^m),即除以 2 的 m 次方
1 << n -> 2^n
'''
'\n通过 <<,>> 快速计算2的倍数问题。\n\nn << 1 -> 计算 n*2\nn >> 1 -> 计算 n/2,负奇数的运算不可用\nn << m -> 计算 n*(2^m),即乘以 2 的 m 次方\nn >> m -> 计算 n/(2^m),即除以 2 的 m 次方\n1 << n -> 2^n\n\n'
# C#语言输出负数
class Program
{
static void Main(string[] args)
{
string s1 = Convert.ToString(-3, 2);
Console.WriteLine(s1);
// 11111111111111111111111111111101
string s2 = Convert.ToString(-3, 16);
Console.WriteLine(s2);
// fffffffd
}
}
File "<ipython-input-39-2311d5f298bb>", line 1
class Program
^
SyntaxError: invalid syntax
print(bin(3)) # 0b11
print(bin(-3)) # -0b11
print(bin(-3 & 0xffffffff))
# 0b11111111111111111111111111111101
print(bin(0xfffffffd))
# 0b11111111111111111111111111111101
print(0xfffffffd) # 4294967293
0b11
-0b11
0b11111111111111111111111111111101
0b11111111111111111111111111111101
4294967293
Python中bin一个负数(十进制表示),输出的是它的原码的二进制表示加上个负号,巨坑。
Python中的整型是补码形式存储的。
Python中整型是不限制长度的不会超范围溢出。
所以为了获得负数(十进制表示)的补码,需要手动将其和十六进制数0xffffffff进行按位与操作,再交给bin()进行输出,得到的才是负数的补码表示。
条件语句
if 2 > 1 and not 2 > 3:
print('Correct Judgement!')
# Correct Judgement!
Correct Judgement!
temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp) # input 函数将接收的任何数据类型都默认为 str。
if guess == 666:
print("你太了解小姐姐的心思了!")
print("哼,猜对也没有奖励!")
else:
print("猜错了,小姐姐现在心里想的是666!")
print("游戏结束,不玩儿啦!")
猜一猜小姐姐想的是哪个数字?666
你太了解小姐姐的心思了!
哼,猜对也没有奖励!
游戏结束,不玩儿啦!
hi = 6
if 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("游戏结束,不玩儿啦!")
猜一猜小姐姐想的是哪个数字?4
小了,小了
游戏结束,不玩儿啦!
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('输入错误!')
请输入成绩:69
C
# assert ----key word
# assert这个关键词我们称之为“断言”,当这个关键词后边的条件为 False 时,程序自动崩溃并抛出AssertionError的异常。
my_list = ['lsgogroup']
my_list.pop(0)
assert len(my_list) > 0
# AssertionError
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-46-1e65300fc961> in <module>
3 my_list = ['lsgogroup']
4 my_list.pop(0)
----> 5 assert len(my_list) > 0
6
7 # AssertionError
AssertionError:
# 在进行单元测试时,可以用来在程序中置入检查点,只有条件为 True 才能让程序正常工作。
assert 3 > 7
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-47-0a6554ee6108> in <module>
1 # 在进行单元测试时,可以用来在程序中置入检查点,只有条件为 True 才能让程序正常工作。
----> 2 assert 3 > 7
AssertionError:
循环语句
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
猜一猜小姐姐想的是哪个数字?4
小了,小了
猜一猜小姐姐想的是哪个数字?6
小了,小了
猜一猜小姐姐想的是哪个数字?9
大了,大了
string = 'abcd'
while string:
print(string)
string = string[1:]
abcd
bcd
cd
d
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
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 = 0
while count < 5:
print("%d is less than 5" % count)
count = 6
break # 存在break时,直接跳出while循环
else:
print("%d is not less than 5" % count)
# 0 is less than 5
0 is less than 5
"""
for 迭代变量 in 可迭代对象:
代码块
"""
for i in 'ILoveLSGO':
print(i, end=' ') # 不换行输出
# I L o v e L S G O
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
a:1 b:2 c:3 d:4
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
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 是一个质数
10 等于 2 * 5
11 是一个质数
12 等于 2 * 6
13 是一个质数
14 等于 2 * 7
15 等于 3 * 5
16 等于 2 * 8
17 是一个质数
18 等于 2 * 9
19 是一个质数
for i in range(2, 9): # 不包含9
print(i)
# 2
# 3
# 4
# 5
# 6
# 7
# 8
2
3
4
5
6
7
8
for i in range(1, 10, 2):
print(i)
# 1
# 3
# 5
# 7
# 9
1
3
5
7
9
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')]
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
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!
I love Python
I love R
I love Matlab
I love C++
Done!
2 I love Python
3 I love R
4 I love Matlab
5 I love C++
Done!
break语句可以跳出当前所在层的循环。
import random
secret = random.randint(1, 10) #[1,10]之间的随机数
while True:
temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp)
if guess > secret:
print("大了,大了")
else:
if guess == secret:
print("你太了解小姐姐的心思了!")
print("哼,猜对也没有奖励!")
break
else:
print("小了,小了")
print("游戏结束,不玩儿啦!")
猜一猜小姐姐想的是哪个数字?5
小了,小了
猜一猜小姐姐想的是哪个数字?6
小了,小了
猜一猜小姐姐想的是哪个数字?8
大了,大了
猜一猜小姐姐想的是哪个数字?7
你太了解小姐姐的心思了!
哼,猜对也没有奖励!
游戏结束,不玩儿啦!
continue终止本轮循环并开始下一轮循环。
for i in range(10):
if i % 2 != 0:
print(i)
continue
i += 2
print(i)
# 2
# 1
# 4
# 3
# 6
# 5
# 8
# 7
# 10
# 9
2
1
4
3
6
5
8
7
10
9
pass 语句的意思是“不做任何事”,如果你在需要有语句的地方不写任何语句,那么解释器会提示出错,而 pass 语句就是用来解决这些问题的。
def a_func():
# SyntaxError: unexpected EOF while parsing
File "<ipython-input-63-f1bd3e1bbfc3>", line 3
# SyntaxError: unexpected EOF while parsing
^
SyntaxError: unexpected EOF while parsing
def a_func():
pass
推导式
列表推导式
[ 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]
[-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]
[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)]
[(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)]
[(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] = 10
print(x)
# [[10, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
[[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
[[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)]
[(0, 2)]
元组推导式
( expr for value in collection [if condition] )
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)
<generator object <genexpr> at 0x7fdc2fd8b0b0>
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
字典推导式
{ key_expr: value_expr for value in collection [if condition] }
b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)
# {0: True, 3: False, 6: True, 9: False}
{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, 2, 3, 4, 5, 6}
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
<generator object <genexpr> at 0x7fdc2fd8bac0>
0
1
2 3 4 5 6 7 8 9
s = sum([i for i in range(101)])
print(s) # 5050
s = sum((i for i in range(101)))
print(s) # 5050
5050
5050
异常处理
表头 | 表头 |
---|---|
单元格 | 单元格 |
单元格 | 单元格 |
左对齐 | 右对齐 | 居中对齐 |
---|---|---|
单元格 | 单元格 | 单元格 |
单元格 | 单元格 | 单元格 |
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('打开文件出错\n原因是:' + str(error))
# 打开文件出错
# 原因是:[Errno 2] No such file or directory: 'test.txt'
打开文件出错
原因是:[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('打开文件出错\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'
dict1 = {'a': 1, 'b': 2, 'v': 22}
try:
x = dict1['y']
except LookupError:
print('查询错误')
except KeyError:
print('键错误')
else:
print(x)
# 查询错误
查询错误
dict1 = {'a': 1, 'b': 2, 'v': 22}
try:
x = dict1['y']
except KeyError:
print('键错误')
except LookupError:
print('查询错误')
else:
print(x)
# 键错误
键错误
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'
出错了!
原因是:unsupported operand type(s) for +: 'int' and 'str'
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'
result is 2.0
executing finally clause
division by zero!
executing finally clause
executing finally clause
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-83-16805cf48925> in <module>
15 # division by zero!
16 # executing finally clause
---> 17 divide("2", "1")
18 # executing finally clause
19 # TypeError: unsupported operand type(s) for /: 'str' and 'str'
<ipython-input-83-16805cf48925> in divide(x, y)
1 def divide(x, y):
2 try:
----> 3 result = x / y
4 print("result is", result)
5 except ZeroDivisionError:
TypeError: unsupported operand type(s) for /: 'str' and 'str'
try:
fh = open("testfile.txt", "w")
fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
print("Error: 没有找到文件或读取文件失败")
else:
print("内容写入文件成功")
fh.close()
# 内容写入文件成功
# else语句的存在必须以except语句的存在为前提,在没有except语句的try语句中使用else语句,会引发语法错误。
内容写入文件成功
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
# An exception flew by!
An exception flew by!