文章目录

  • 一 变量、运算符与数据类型
  • 1.1 注释
  • 1.2 运算符
  • 1.3 数据类型与转换
  • 1.4 print()函数
  • 二 位运算
  • 2.1 原码、反码及补码
  • 2.2 按位取反(~)
  • 2.3 按位异或
  • 三 条件语句
  • 3.1 if条件语句
  • 3.2 if-else语句
  • 3.3 if - elif - else 语句
  • 3.4 assert 关键词
  • 四 循环语句
  • 4.1 while循环语句
  • 4.2 while - else 循环
  • 4.3 for循环
  • 4.4 for - else 循环
  • 4.5 enumerate()函数
  • 4.6 break-continue-pass语句
  • 4.7 推导式
  • 五 异常处理
  • 5.1 try - except 语句
  • 5.2 try - except - finally 语句
  • 5.3 try - except - else 语句
  • 5.4 raise语句


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

1.1 注释

(1)在Python中”#“符号表示单行注释,作用于整行。
【例子】

#初识Python
print('Hello World !')#输出语句可用单引号或者双引号

输出结果:Hello World !

(2)’’’ ‘’’ 或者 “”" “”" 表示区间注释,在三引号之间的所有内容被注释。

'''我能学好Python语言'''
print('Hello World !')
"""这是我第一次接触Python语言,我对它很感兴趣!"""
print('Hello Python !')

运行结果:
Hello World !
Hello Python !

1.2 运算符

(1)算数运算符

操作符

名称

示例

+


1+1=2

-


1-1=0

*


1*1=1

/


5/2=2.5

//

整除

5//2=2

%

取余

5%2=1

**


2**3=8

【例子】

print(1 + 1)  
print(1 - 1)  
print(1 * 1)  
print(5 / 2)  
print(5 // 2)  
print(5 % 2)  
print(2 ** 3)

运行结果:
2
0
1
2.5
2
1
8
(2)比较运算符

操作符

名称

示例

>

大于

2>1

>=

大于等于

2>=4

<

小于

1<2

<=

小于等于

5<=2

==

等于

3==4

!=

不等于

3!=4

【例子】`

print(2 > 1)  # Ture
print(2 >= 4) # False
print(1 < 2)  # Ture
print(5 <= 2) # False
print(3 == 4) #False 
print(3 != 4) #Ture

运行结果:
True
False
True
False
False
True

(3)逻辑运算符

操作符

名称

示例

and


(3>2)and (3<5)

or


(1>3) or (9<2)

not


not (2>1)

[例子]

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

(4)位运算符

运算符

名称

示例

~

按位取反

~4

&

按位与

4 & 5

I

按位或

4 I 5

^

按位异或

4^5

<<

左移

4 << 2

>>

右移

4 >> 2

【示例】

#bin()函数用于二进制转换
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

(5)三元运算
举个简单例子,一看就懂
【示例】

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

有了这种三元运算,可以简化许多条件语句。
(6)其他运算符

操作符

名称

示例

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:
    print('A' + ' exists')
if 'h' not in letters:
    print('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等),则两者是有区别的。
运算符的优先级

一元运算符优于二元运算符。例如3 ** -2等价于3 ** (-2)。
先算术运算,后移位运算,最后位运算。例如 1 << 3 + 2 & 7等价于 (1 << (3 + 2)) & 7。
逻辑运算最后结合。例如3 < 4 and 4 < 5等价于(3 < 4) and (4 < 5)。

1.3 数据类型与转换

类型

名称

示例

int

整型<class ‘int’>

-876, 10

float

浮点型<class ‘float’>

3.149, 11.11

bool

布尔型<class ‘bool’>

True, False

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 = 1031
print(bin(a))  # 0b10000000111
print(a.bit_length())  # 11

运行结果:
0b10000000111
11

有时候我们想保留浮点型的小数点后 n 位。可以用 decimal 包里的 Decimal 对象和 getcontext() 方法来实现。
getcontext() 显示了 Decimal 对象的默认精度值是 28 位 (prec=28)。但是,可用getcontext().prec 来调整精度。

import decimal
from decimal import Decimal
a = decimal.getcontext()
print(a)`
b = Decimal(1) / Decimal(3)
print(b)
decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)
print(c)

运行结果:
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])

0.3333333333333333333333333333
0.3333

获取类型信息
type() 不会认为子类是一种父类类型,不考虑继承关系。
isinstance() 会认为子类是一种父类类型,考虑继承关系。
如果要判断两个类型是否相同推荐使用 isinstance()。

类型转换
转换为整型 int(x, base=10)
转换为字符串 str(object=’’)
转换为浮点型 float(x)

1.4 print()函数

rint(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

将对象以字符串表示的方式格式化输出到流文件对象file里。其中所有非关键字参数都按str()方式进行转换为字符串输出;
关键字参数sep是实现分隔符,比如多个参数输出时想要输出中间的分隔字符;
关键字参数end是输出结束时的字符,默认是换行符\n;
关键字参数file是定义流输出的文件,可以是标准的系统输出sys.stdout,也可以重定义为别的文件;
关键字参数flush是立即把内容输出到流文件,不作缓存。

二 位运算

注意:我这里介绍难理解的2种位运算,其他很容易理解的不赘述。

2.1 原码、反码及补码

正数的反码就是原码,负数的反码是符号位不变,其余位取反(对应正数按位取反),正数的补码就是原码,负数的补码是反码+1。
如下,
正数:(+5)
0000 0101 -> 5 原码
0000 0101 -> 5 反码
0000 0101 -> 5 补码
负数:(-5)
1000 0101 -> -5 原码
1111 1010 -> -5 反码
1111 1011 -> -5 补码(反码+1)

2.2 按位取反(~)

~ 把补码中的 0 和 1 全部取反(0 变为 1,1 变为 0)有符号整数的符号位在 ~ 运算中同样会取反。
【示例】
~(+5) -> (-6)
0000 0101 -> 5 补码
1111 1010 -> (取反后计算机存储的补码数据)想要转化为原码 要逆运算(负数的补码-1,再取反)
1111 1001 ->减1
1000 0110 ->取反就得到原码为(-6)
【示例】
~(-5) -> (+4)
1000 0101 -> -5 原码
1111 1010 -> -5 反码
1111 1011 -> -5 补码(反码+1)
0000 0100 ->(+4)(取反后计算机存储补码的数据)想要转化为原码 要逆运算(正数的补码=原码)

2.3 按位异或

只有两个对应位不同时才为 1,如下
00 00 01 01 -> 5
^
00 00 01 10 -> 6

00 00 00 11 -> 3
注意:在左移位运算时,左移m位,就是原始数乘以2m,同理,右移位即为除以2m

三 条件语句

3.1 if条件语句

if expression:
expr_true_suite
if 语句的 expr_true_suite 代码块只有当条件表达式 expression 结果为真时才执行,否则将继续执行紧跟在该代码块后面的语句。
单个 if 语句中的 expression 条件表达式可以通过布尔操作符 and,or和not 实现多重条件判断。

if 2 > 1 and not 2 > 3:
    print('你笑起来真好看!')

3.2 if-else语句

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

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

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

3.3 if - elif - else 语句

if expression1:
expr1_true_suite
elif expression2:
expr2_true_suite
.
.
.
elif expressionN:
exprN_true_suite
else:
expr_false_suite
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('输入错误!')

3.4 assert 关键词

assert这个关键词我们称之为“断言”,当这个关键词后边的条件为 False 时,程序自动崩溃并抛出AssertionError的异常。
【例子】在进行单元测试时,可以用来在程序中置入检查点,只有条件为 True 才能让程序正常工作。

assert 3 > 7# AssertionError

四 循环语句

4.1 while循环语句

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

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

如果布尔表达式不带有<、>、==、!=、in、not in等运算符,仅仅给出数值之类的条件,也是可以的。当while后写入一个非零整数时,视为真值,执行循环体;写入0时,视为假值,不执行循环体。也可以写入str、list或任何序列,长度非零则视为真值,执行循环体;否则视为假值,不执行循环体。

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("游戏结束,不玩儿啦!")

4.2 while - else 循环

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

4.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
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

for key, value in dic.items():
    print(key, value, sep=':', end=' ')

4.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 是一个质数

4.5 enumerate()函数

enumerate(sequence, [start=0])
sequence:一个序列、迭代器或其他支持迭代对象。
start:下标起始位置。
返回 enumerate(枚举) 对象

用 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!

运行结果:
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!

4.6 break-continue-pass语句

break语句可以跳出当前所在层的循环。
continue终止本轮循环并开始下一轮循环。
pass 语句的意思是“不做任何事”,如果你在需要有语句的地方不写任何语句,那么解释器会提示出错,而 pass 语句就是用来解决这些问题的
【示例】

for i in range(10):
    if i % 2 != 0:
        print(i)
        continue
    i += 2
    if(i==8):
    	break
    print(i)

运行结果:
2
1
4
3
6
5
【示例】

def a_func():
    pass

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

4.7 推导式

(1)列表推导式

[ 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]

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)]

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)]
(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 at 0x0000025BE511CC48>
(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}

其它
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)
# <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 at 0x0000014CEC389C78>
0
1
2 3 4 5 6 7 8 9

五 异常处理

5.1 try - except 语句

try:
检测范围
except Exception[as reason]:
出现异常后的处理代码
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 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-except-else语句尝试查询不在dict中的键值对,从而引发了异常。这一异常准确地说应属于KeyError,但由于KeyError是LookupError的子类,且将LookupError置于KeyError之前,因此程序优先执行该except代码块。所以,使用多个except代码块时,必须坚持对其规范排序,要从最具针对性的异常到最通用的异常。
【例子】

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

运行结果:键错误

5.2 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'

运行结果:
result is 2.0
executing finally clause
division by zero!
executing finally clause

5.3 try - except - else 语句

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

try:
检测范围
except:
出现异常后的处理代码
else:
如果没有异常执行这块代码
使用except而不带任何异常类型,这不是一个很好的方式,我们不能通过该程序识别出具体的异常信息,因为它捕获所有的异常。

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语句,会引发语法错误。

5.4 raise语句

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

【例子】

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

运行结果:
An exception flew by!

以上笔记来源:学习阿里云天池所得,以及自己的一些总结。若有不足请多多指教!