这里写目录标题
运算符相关
#
表示单行注释,''' '''
或者""" """
表示区间注释,在三引号之间的所有内容被注释- 在python中除法不会自动取整,所以需要
//
来表示整除a//b:a整除b
- 可以直接使用
**
来表示幂函数a**b:a的b次方
"name"+","+"age"
python中的+号可以直接进行字符串相加- python是一个严格缩进的编程语言,缩进的目的相当于c中的{}
python逻辑运算符 and or not
操作符 | 名称 | 示例 |
---|---|---|
and | 与 | (3 > 2) and (3 < 5) |
or | 或 | (1 > 3) or (9 < 2) |
not | 非 | not (2 > 1) |
python的位运算符
操作符 | 名称 | 示例 |
---|---|---|
~ | 按位取反 | ~4 |
& | 按位与 | 4 & 5 |
| | 按位或 | 4 | 5 |
^ | 按位异或 | 4 ^ 5 |
<< | 左移 | 4 << 2 |
>> | 右移 | 4 >> 2 |
三元运算符
x, y = 4, 5 #python赋值的时候不需要定义变量类型
if x < y:
small = x
else:
small = y
print(small) # 4
x, y = 4, 5
small = x if x < y else y #这个相当于c中的x<y?x:y
print(small) # 4
其他运算符存在不存在,是不是,返回值是bool类型
操作符 | 名称 | 示例 |
---|---|---|
in | 存在 | 'A' in ['A', 'B', 'C'] |
not in | 不存在 | 'h' not in ['A', 'B', 'C'] |
is | 是 | "hello" is "hello" |
not is | 不是 | "hello" is not "hello" |
#存在不存在
letters = ['A', 'B', 'C']
if 'A' in letters: #返回值类型是bool类型
print('A' + ' exists') # A exists
if 'h' not in letters:
print('h' + ' not 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
#比较的两个变量均指向可变类型
a = ["hello"]
b = ["hello"]
print(a is b, a == b) # False True
print(a is not b, a != b) # True False
注意:
- is,is not对比的是两个变量的内存地址
- ==,!=对比的是两个变量的值
- 比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和==,!=是完全等价的
- 对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的
运算符的优先级
运算符 | 描述 |
---|---|
** | 指数(最高优先级) |
~± | 按位翻转,一元加号和减号 |
* / % // | 乘,除,取模和取整除) |
+ - | 加法减法 |
>> << | 右移,左移运算符 |
& | 位‘AND’ |
^| | 位运算符 |
<=<>>= | 比较运算符 |
<>==!= | 等于运算符 |
=%=/=//=-=+=*=**= | 赋值运算符 |
is is not | 身份运算符 |
in not in | 成员运算符 |
not and or | 逻辑运算符 |
变量和赋值
x,y=1,2
可以使用这样的方法进行赋值
数据类型和转换
类型 | 名称 | 示例 |
---|---|---|
int | 整型 <class 'int'> | -876, 10 |
float | 浮点型<class 'float'> | 3.149, 11.11 |
bool | 布尔型<class 'bool'> | True, False |
python里面万物皆对象,整型也不例外,只要是对象,就有相应的属性和方法
# 通过print()可以看出a的值,以及类(class)是int
a = 1031
print(a,type(a))
#1021 <class 'int'>
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
- 转换为整型
int('a')
转换为字符型str(1)
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
print()函数
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
- 将对象以字符串表示的方式格式化输出到流文件对象file里。其中所有非关键字参数都按
str()
方式进行转换为字符串输出; - 关键字参数
sep
是实现分隔符,比如多个参数输出时想要输出中间的分隔字符; - 关键字参数
end
是输出结束时的字符,默认是换行符\n
; - 关键字参数
file
是定义流输出的文件,可以是标准的系统输出sys.stdout
,也可以重定义为别的文件; - 关键字参数
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设置的参数&结尾,不会默认换行
print(item,end='&')
item
值与'another string'
两个值之间用sep
设置的参数&
分割。由于end
参数没有设置,因此默认是输出解释后换行,即end
参数的默认值为\n
。
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
input()函数
- 在对变量进行赋值时,python会自动判断存储数据的类型,不需要我们进行操作,但是input不是这样
- 使用input()函数进行输入时,无论输入的值是int、float还是string,input函数的返回值都是sting类型
- 所以input()返回的函数值无法直接进行算是运算,就算是可以直接进行算数运算,也是字符串之间的运算
input()函数涉及的强制类型转换
- 如果需要使用input输入的数据进行算术运算是,要先用强制类型转换。如:
a=int(input())
带提示的input()函数及常见问题
variable=input(prompt)
,可以自带提示,不需要再单独写一行输入提示
name=input('请输入你的名字:')
#请输入你的名字 alex
print(name)
#alex
在print()函数中可以直接插入变量一起输出:print('你的年龄是:',age,'岁')
,但是在input中不可以,因为input(prompt)是直接以字符串形式输出提示性prompt语言,不能像print()函数一样将值赋给变量并输出。所以我们需要将输出的变量转换为string型,使用字符串连接的+
号去输出
input('请输入'+str(name)+'同学的学号')
#请输入alex同学的学号
利用input()一次性输入多个变量值
- 利用split()函数进行输入
a,b,c=input("以空格隔开:").split()
#以空格隔开:1 2 3
print(a,b,c)
#1 2 3
d,e,f=input("以逗号隔开:").split(",")
#以逗号隔开:1,2,3
print(d,e,f)
#1,2,3
- 但是这样输入的值仍然是字符串类型,多次输出返回的是一个list,list没办法直接做转换,所以需要另一个函数map()来做转换。
**map()函数将传入的函数一次作用到序列的每个元素,并把结果作为新的list返回。
def =map(int,input("以逗号隔开:").split(","))
#以逗号隔开:1,2,3
printt(type(d))
#<class 'int'>
package 和import
b = dir(int)
内置的 dir() 函数能够返回由对象所定义的名称列表。如果这一对象是一个模块,则该列表会包括函数内所定义的函数、类与变量。该函数接受参数。 如果参数是模块名称,函数将返回这一指定模块的名称列表。 如果没有提供参数,函数将返回当前模块的名称列表。
有时候我们想保留浮点型的小数点后 n
位。可以用 decimal
包里的 Decimal
对象和 getcontext()
方法来实现。
import decimal #导入decimal这个包
from decimal import Decimal #要用到这个包里的Decimal这个对象
a = decimal.getcontext()
print(a)
#`getcontext()` 显示了 `Decimal` 对象的默认精度值是 28 位 (`prec=28`)
# 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 = 4
c = Decimal(1) / Decimal(3)
print(c)
# 0.3333
Python 里面有很多用途广泛的包 (package),用什么你就引进 (import) 什么。包也是对象,也可以用上面提到的dir(decimal)
来看其属性和方法。
条件语句
if 语句
if expression:
不需要括号,需要打冒号if expression: else:
assert 关键字
assert
这个关键字我们称之为”断言”,当这个关键词后边的条件为False时,程序自动崩溃,并抛出AssertionError
的异常
my_list = ['lsgogroup']
my_list.pop(0)
assert len(my_list) > 0#my_list的长度不大于0,所以条件为False
# AssertionError
循环语句
while循环
while 布尔表达式:body
和if一样,这里不需要括号,也不需要花括号,但是需要打冒号。
while - else
while 布尔表达式:
else:
当while
循环整除执行完成的情况下,执行else,如果while循环中执行了跳出循环的语句,比如break
,将不执行else
代码块的内容。
count = 0
while count < 5: #只有count==5,正常执行完循环的时候,才会执行else语句
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
count = 0
while count < 5:
print("%d is less than 5" % count)
count = 6
break #执行力break,所以不会执行else后面的语句
else:
print("%d is not less than 5" % count)
# 0 is less than 5
for 循环
for
循环时迭代循环,在python中相当于一个通用的迭代器,可以遍历任何有序序列。
- 类似c++中的
for(auto &x:v) #用x去迭代容器v中的每一个元素
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
#字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据。
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
for - else 循环
当for
循环整除执行完成的情况下,执行else
,如果for
循环中执行了跳出循环的语句,比如break
,将不执行else
代码块的内容。与while - else
一样。
range() 函数
range([start,]stop[,step=1])
- 这个
BIF(Built-in functions)
有三个参数,其中用中括号括起来的两个表示这两个参数是可选的。 step=1
表示第三个参数的默认值是1range
这个BIF的作用是生成一个从start
参数的值开始到stop
参数的值结束的数字序列,该序列包含start
的值,但不包含stop
的值。
for i in range(2, 9): # 不包含9
print(i)
# 2
# 3
# 4
# 5
# 6
# 7
# 8
for i in range(1, 10, 2):#步长为2
print(i)
# 1
# 3
# 5
# 7
# 9
enumerate() 函数
enumerate(sequence,[start=0])
- 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')]
enumerate()
与 for 循环的结合使用。
for i, a in enumerate(A)
do something with a
用 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!
#索引值从2开始
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!
break 语句和 continue语句
break
语句跳出当前所在层的循环continue
语句终止本轮循环并开始下一轮循环
pass 语句
pass
语句的意思是“不做任何事情”,如果在需要语句的地方不写任何语句,那么解释器会提示出错,而pass
语句就是用来解决这个问题的。
def a_func():
# SyntaxError: unexpected EOF while parsing
```python
def a_func():
pass
```
pass
是空语句,不做任何操作,只起到占位的作用,其作用是为了保持程序结构的完整性。尽管pass
语句不做任何操作,但如果暂时不确定要在一个位置放上什么样的代码,可以先放置一个pass
语句,让代码可以正常运行。
推导式
列表推导式list[]
list=[ expr for value in collection if condition ]
# 运算表达式 如果条件为真对collection中的每一个值value进行操作
x = [-4, -2, 0, 2, 4]
y = [a * 2 for a in x] #a中的每一个值都*2
print(y)
# [-8, -4, 0, 4, 8]
x = [i ** 2 for i in range(1, 10)] #区间1-10,每一个数平方
print(x)
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
x = [(i, i ** 2) for i in range(6)] #生成0-5,每个数平方
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)
#输出100以内的3的倍数,并且跳过偶数
# [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)]
元组推导式tuple()
元组是一种序列,就像列表一样。元组和列表之间的主要区别是元组不能像列表那样改变元素的值,可以简单地理解为“只读列表”。 元组使用小括号 -
()
,而列表使用方括号 -[]
- 列表通常用来存储相同类型的数据(列表中也可以存储不用的数据类型);而元组在实际开发中,通常用来存储不同类型的数据。
- 元组(Tuple)与列表相似,不同之处在于元组的元素不能修改;
- 元组表示多个元素组成的序列;用于存储一串信息,不同数据之间用逗号隔开;
- 元组的索引从0开始;
tuple=[ expr for value in collection if condition ]
# 运算表达式 如果条件为真对collection中的每一个值value进行操作
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)
字典推导式dict{}
在 Python 中,字典 是一系列键 — 值对 。每个键 都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何 Python 对象用作字典中的值。
- list是有序的对象集合
- dict是无序的对象集合
字典用{}定义,字典使用键值对存储数据,键值对之间使用
,
分隔,键key
是索引,值value
是数据,键和值之间使用:
分隔,键必须是唯一的(因为我们必须通过键来找到数据,值可以取任何数据类型,但键只能使用字符串,数字或元组,字典是一个无序的数据集和,使用print函数输出字典时, 通常输出的顺序和定义的顺序是不一致的
{ 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}
集合推导式set
-
集合不同于列表或元组,集合中的每一个元素不能出现多次,并且是无序存储的。
-
由于集合中的元素不能出现多次,这使得集合在很大程度上能够高效地从列表或元组中删除重复值,并执行取并集、交集等常见的的数学操作。
s = {1,2,4,5}
print(type(s)) #<class 'set'>
s1 = {}
print(type(s1)) ##空字典定义
#<class 'dict'> #类型为字典
s1 = set([])
print(type(s1)) ###空集合定义
#<class 'set'> #类型为集合
{ 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}
异常处理
异常就是运行期检测到的错误。计算机语言针对可能出现的错误定义了异常类型,某种错误引发对应的异常时,异常处理程序将被启动,从而恢复程序的正常运行。
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异常体系中的部分关系如下所示:
Python标准警告总结
- Warning:警告的基类
- DeprecationWarning:关于被弃用的特征的警告
- FutureWarning:关于构造将来语义会有改变的警告
- UserWarning:用户代码生成的警告
- PendingDeprecationWarning:关于特性将会被废弃的警告
- RuntimeWarning:可疑的运行时行为(runtime behavior)的警告
- SyntaxWarning:可疑语法的警告
- ImportWarning:用于在导入模块过程中触发的警告
- UnicodeWarning:与Unicode相关的警告
- BytesWarning:与字节或字节码相关的警告
- ResourceWarning:与资源使用相关的警告
try - except 语句
try:
检测范围
except Exception[as reason]:
出现异常后的处理代码
try语句按照如下方式工作
- 首先,执行
try
子句,(在关键字try和关键字except之间的语句) - 如果没有异常,忽略
except
子句,try
子句执行后结束 - 如果在执行try子句的过程中发生了异常,那么
try
子句余下的部分将被忽略,如果异常的类型和except
之后的名称相符,那么对应的except
子句将会被执行。最后执行try-excep
t语句之后的代码 - 如果一个异常没有与任何的
except
匹配,那么这个异常将会传递给上层的try
中
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'
- 一个
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'
- 一个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'
try-except-finally 语句
try:
检测范围
except Exception[as reason]:
出现异常后的处理代码
finally:
无论如何都会被执行的代码
-
不管
try
子句里面有没有发生异常,finally
子句都会执行。 -
如果一个异常在
try
子句里被抛出,而又没有任何的except
把它截住,那么这个异常会在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'
try-except-else 语句
- 如果在
try
子句执行时没有发生异常,python
将执行else语句后的语句
try:
检测范围
except(Exception1[, Exception2[,...ExceptionN]]]):
发生以上多个异常中的一个,执行这块代码
else:
如果没有异常执行这块代码
try:
fh = open("testfile.txt", "w")
fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
print("Error: 没有找到文件或读取文件失败")
else:
print("内容写入文件成功")
fh.close()
# 内容写入文件成功
注意:else
语句的存在必须以except
语句的存在为前提,在没有except
语句的try
语句中使用else
语句,会引发语法错误。
raise 语句
- python使用raise语句抛出一个指定的异常
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
# An exception flew by!