因为我自己有一些Python的基础,所以这部分学习内容的笔记只记录一些比较重要的,或者我不太熟悉的内容。
文章目录
1、变量、运算符与数据类型
Python 里面万物皆对象,dir方法可以查看变量的属性和方法(只能看到名字)。
print(dir(int))
结果:
[‘abs’, ‘add’, ‘and’, ‘bool’, ‘ceil’, ‘class’, ‘delattr’, ‘dir’, ‘divmod’, ‘doc’, ‘eq’, ‘float’, ‘floor’, ‘floordiv’, ‘format’, ‘ge’, ‘getattribute’, ‘getnewargs’, ‘getstate’, ‘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_count’, ‘bit_length’, ‘conjugate’, ‘denominator’, ‘from_bytes’, ‘imag’, ‘numerator’, ‘real’, ‘to_bytes’]
2、位运算
原码、反码和补码
整型变量的原码:变量的二进制数,加上最高位的符号位(0正1负)
反码:正数的反码为原码,负数的反码为原码除符号位按位取反
补码:正数的补码为原码,负数的补码为反码+1
位运算
利用位运算可以进行一些快速计算
# 交换两个数
a ^= b
b ^= a
a ^= b
# 计算2的幂
1 << n # 2^n
m << n # m×2^n
3、条件语句
assert
关键词:称为“断言”,如果assert
后面条件语句的结果为False,则抛出AssertionError
异常
assert 1 == 0
Traceback (most recent call last):
File “xxxx/main.py”, line 1, in
assert 1 == 0
^^^^^^
AssertionError
4、循环语句
while-else循环
else后面的代码块会在循环正常结束时被执行,而如果中途break了循环,则else后面的代码自动忽略。
i = 0
while i < 3:
print("{0} is less than 3.".format(i))
i = i + 1
else:
print("{0} is not less than 3.".format(i))
0 is less than 3.
1 is less than 3.
2 is less than 3.
3 is not less than 3.
for-else循环
跟while-else一样,代码略
range() 函数
range([start,] stop[, step=1])
range的区间为左闭右开,有的时候start参数可以省略,step代表步长,默认值为1
for i in range(2, 20, 3):
print(i, end=' ')
2 5 8 11 14 17
enumerate()函数
enumerate()函数把一个支持迭代的对象的每个元素进行“编号”
enumerate(sequence, [start=0])
sequence:一个序列、迭代器或其他支持迭代的对象
start:下标起始位置
返回 enumerate(枚举) 对象
a = ['张三', '李四', '王五']
for i, name in enumerate(a, 3):
print(i, name)
3 张三
4 李四
5 王五
推导式
集合、列表、元组和字典可以用推导式来“生成”。
以下为推导式的语法:
expr for value in collection [if condition]
expr - 生成序列的元素的类型
collection - 可迭代的对象
最终生成什么类型取决于推导式最外层的括号类型(字典除外)
例1:生成小于20的奇数列表
# 生成小于20的所有奇数组成的列表
odd = [i for i in range(20) if (i & 1)]
print(odd)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
例2:生成一些符合特定条件的二维坐标
# 顶点为(0,0)且在第一象限,边长为3的正方形内部的整数坐标点构成的元组
points = ((x, y) for x in range(3) if x > 0 for y in range(3) if y > 0)
print(tuple(points))
((1, 1), (1, 2), (2, 1), (2, 2))
例3:生成一个列表的集合以去除重复元素
nums = [1, 5, 2, 6, 4, 4, 3, 2, 1, 7, 5, 5, 1, 1]
uni_nums = {x for x in nums}
print(uni_nums)
{1, 2, 3, 4, 5, 6, 7}
例4:生成一个字典
# 直接用教程里的例子了
b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)
{0: True, 3: False, 6: True, 9: False}
5、异常处理
Python的异常处理和Java大同小异,只有关键字有些不同。
Python使用raise
关键字抛出异常。
raise NameError("Error occurred!")
Traceback (most recent call last):
File “xxx\main.py”, line 1, in
raise NameError(“Error occurred!”)
NameError: Error occurred!
Python的try-except-finally
语句对应Java的try-catch-finally
语句,并且也可以添加else
代码块,具体语法如下:
try:
检测范围
except Exception[as reason]:
出现异常后的处理代码
else:
没有出现异常执行的代码
finally:
无论如何都会执行的代码
举个例子:
try:
path = "content.txt"
f = open(path)
except OSError as error:
print("打开文件错误!原因是{}".format(error))
else:
print("打开文件成功了!")
f.close()
finally:
print("代码执行完毕!")
如果该脚本目录下存在content.txt
,那么执行代码就会输出
打开文件成功了!
代码执行完毕!
如果不存在content.txt
,那么就会输出
打开文件错误!原因是[Errno 2] No such file or directory: ‘content.txt’
代码执行完毕!