python 学习笔记(一)

注释

在 Python 中,# 表示注释,作用于整行。
‘’’ ‘’’'或者 “”" “”" 表示区间注释,在三引号之间的所有内容被注释

运算符

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

Print 函数

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

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

利用位运算实现快速计算

1.通过 <<,>> 快速计算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

2.通过 ^ 快速交换两个整数。 通过 ^ 快速交换两个整数

a ^= b
b ^= a
a ^= b

示意图
3.python 的Bin输出
Python中bin一个负数(十进制表示),输出的是它的原码的二进制表示加上个负号,巨坑。
Python中的整型是补码形式存储的。
Python中整型是不限制长度的不会超范围溢出。
所以为了获得负数(十进制表示)的补码,需要手动将其和十六进制数0xffffffff进行按位与操作,再交给bin()进行输出,得到的才是负数的补码表示。

条件语句

Python入门(上)
简介

变量、运算符与数据类型

  1. 注释
  2. 运算符
  3. 变量和赋值
  4. 数据类型与转换
  5. print()函数

位运算

  1. 原码、反码和补码
  2. 按位运算
  3. 利用位运算实现快速计算
  4. 利用位运算实现整数集合

条件语句

  1. if 语句
  2. if - else 语句
  3. if - elif - else 语句
  4. assert 关键词

循环语句

  1. while 循环
  2. while - else 循环
  3. for 循环
  4. for - else 循环
  5. range() 函数
  6. enumerate()函数
  7. break 语句
  8. continue 语句
  9. pass 语句
  10. 推导式

异常处理

  1. Python 标准异常总结
  2. Python 标准警告总结
  3. try - except 语句
  4. try - except - finally 语句
  5. try - except - else 语句
  6. raise语句

简介
Python 是一种通用编程语言,其在科学计算和机器学习领域具有广泛的应用。如果我们打算利用 Python 来执行机器学习,那么对 Python 有一些基本的了解就是至关重要的。本 Python 入门系列体验就是为这样的初学者精心准备的。

天池官方为大家准备钉钉学习交流群,在学习过程中,大家有任何教程内容或者平台使用问题都可以在群内提出,扫码即可加入:

Image
本实验包括以下内容:

变量、运算符与数据类型
注释
运算符
变量和赋值
数据类型与转换
print() 函数
位运算
原码、反码和补码
按位非操作 ~
按位与操作 &
按位或操作 |
按位异或操作 ^
按位左移操作 <<
按位右移操作 >>
利用位运算实现快速计算
利用位运算实现整数集合
条件语句
if 语句
if - else 语句
if - elif - else 语句
assert 关键词
循环语句
while 循环
while - else 循环
for 循环
for - else 循环
range() 函数
enumerate()函数
break 语句
continue 语句
pass 语句
推导式
异常处理
Python 标准异常总结
Python 标准警告总结
try - except 语句
try - except - finally 语句
try - except - else 语句
raise语句
变量、运算符与数据类型

  1. 注释
    在 Python 中,# 表示注释,作用于整行。
    【例子】单行注释

1

这是一个注释

2
print(“Hello world”)
3

4

Hello world

Hello world
‘’’ ‘’’ 或者 “”" “”" 表示区间注释,在三引号之间的所有内容被注释
【例子】多行注释

1
‘’’
2
这是多行注释,用三个单引号
3
这是多行注释,用三个单引号
4
这是多行注释,用三个单引号
5
‘’’
6
print(“Hello china”)
7

Hello china

8

9
“”"
10
这是多行注释,用三个双引号
11
这是多行注释,用三个双引号
12
这是多行注释,用三个双引号
13
“”"
14
print(“hello china”)
15

hello china

Hello china

hello china
【我是测试题1】请在下方代码块中打印(print)出 hello+你的姓名
如:print(“hello 老表”)

1

写下你的答案

2

2. 运算符
算术运算符

操作符 名称 示例

  • 加 1 + 1
  • 减 2 - 1
  • 乘 3 * 4
    / 除 3 / 4
    // 整除(地板除) 3 // 4
    % 取余 3 % 4
    ** 幂 2 ** 3
    【例子】

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

1

12

0.75

0

3

8
比较运算符

操作符 名称 示例

大于 2 > 1
= 大于等于 2 >= 4
< 小于 1 < 2
<= 小于等于 5 <= 2
== 等于 3 == 4
!= 不等于 3 != 5
【例子】

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

False

True

False

False

True
逻辑运算符

操作符 名称 示例
and 与 (3 > 2) and (3 < 5)
or 或 (1 > 3) or (9 < 2)
not 非 not (2 > 1)
【例子】

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

False

False
位运算符

操作符 名称 示例
按位取反 ~4
& 按位与 4 & 5
按位或
^ 按位异或 4 ^ 5
<< 左移 4 << 2

右移 4 >> 2
【例子】有关二进制的运算,参见“位运算”部分的讲解。

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

0b101

-0b101 -5

0b100 4

0b101 5

0b1 1

0b10000 16

0b1 1
三元运算符

【例子】

1
x, y = 4, 5
2
if x < y:
3
small = x
4
else:
5
small = y
6

7
print(small) # 4
4
有了这个三元操作符的条件表达式,你可以使用一条语句来完成以上的条件判断和赋值操作。

【例子】

1
x, y = 4, 5
2
small = x if x < y else y
3
print(small) # 4
4
其他运算符

操作符 名称 示例
in 存在 ‘A’ in [‘A’, ‘B’, ‘C’]
not in 不存在 ‘h’ not in [‘A’, ‘B’, ‘C’]
is 是 “hello” is “hello”
not is 不是 “hello” is not “hello”
【例子】

1
letters = [‘A’, ‘B’, ‘C’]
2
if ‘A’ in letters:
3
print(‘A’ + ’ exists’)
4
if ‘h’ not in letters:
5
print(‘h’ + ’ not exists’)
6

7

A exists

8

h not exists

A exists

h not exists
【例子】比较的两个变量均指向不可变类型。

1
a = “hello”
2
b = “hello”
3
print(a is b, a == b) # True True
4
print(a is not b, a != b) # False False
True True

False False
【例子】比较的两个变量均指向可变类型。

1
a = [“hello”]
2
b = [“hello”]
3
print(a is b, a == b) # False True
4
print(a is not b, a != b) # True False
False True

True False
注意:

is, is not 对比的是两个变量的内存地址
==, != 对比的是两个变量的值
比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。
对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的。
运算符的优先级

运算符 描述
** 指数(最高优先级)
~± 按位翻转,一元加号和减号

  • / % // 乘,除,取模和取整除)
    • 加法减法

<< 右移,左移运算符
& 位‘AND’
^| 位运算符
<=<>>= 比较运算符
<>!= 等于运算符
=%=/=//=-=+
*= 赋值运算符
is is not 身份运算符
in not in 成员运算符
not and or 逻辑运算符
【例子】

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

0.1111111111111111

0

-12.5

True
【我是测试题2】下面这段代码的运行结果是什么?

1

运行一下结果就出来了

2
a = “hello”
3
b = “hello”
4
print(a is b, a == b)
3. 变量和赋值
在使用变量之前,需要对其先赋值。
变量名可以包括字母、数字、下划线、但变量名不能以数字开头。
Python 变量名是大小写敏感的,foo != Foo。
【例子】

1
teacher = “老马的程序人生”
2
print(teacher) # 老马的程序人生
老马的程序人生
【例子】

1
first = 2
2
second = 3
3
third = first + second
4
print(third) # 5
5
【例子】

1
myTeacher = “老马的程序人生”
2
yourTeacher = “小马的程序人生”
3
ourTeacher = myTeacher + ‘,’ + yourTeacher
4
print(ourTeacher) # 老马的程序人生,小马的程序人生
老马的程序人生,小马的程序人生
【我是测试题3】运行下面一段代码看看结果是什么?

1

运行一下就好啦

2
set_1 = {“欢迎”, “学习”,“Python”}
3
print(set_1.pop())
4. 数据类型与转换
类型 名称 示例
int 整型 <class ‘int’> -876, 10
float 浮点型<class ‘float’> 3.149, 11.11
bool 布尔型<class ‘bool’> True, False
整型

【例子】通过 print() 可看出 a 的值,以及类 (class) 是int。

1
a = 1031
2
print(a, type(a))
3

1031 <class ‘int’>

1031 <class ‘int’>
Python 里面万物皆对象(object),整型也不例外,只要是对象,就有相应的属性 (attributes) 和方法(methods)。

【例子】

1
b = dir(int)
2
print(b)
3

4

[‘abs’, ‘add’, ‘and’, ‘bool’, ‘ceil’, ‘class’,

5

delattr’, ‘dir’, ‘divmod’, ‘doc’, ‘eq’,

6

float’, ‘floor’, ‘floordiv’, ‘format’, ‘ge’,

7

getattribute’, ‘getnewargs’, ‘gt’, ‘hash’,

8

index’, ‘init’, ‘init_subclass’, ‘int’, ‘invert’,

9

le’, ‘lshift’, ‘lt’, ‘mod’, ‘mul’, ‘ne’,

10

neg’, ‘new’, ‘or’, ‘pos’, ‘pow’, ‘radd’,

11

rand’, ‘rdivmod’, ‘reduce’, ‘reduce_ex’, ‘repr’,

12

rfloordiv’, ‘rlshift’, ‘rmod’, ‘rmul’, ‘ror’,

13

round’, ‘rpow’, ‘rrshift’, ‘rshift’, ‘rsub’,

14

rtruediv’, ‘rxor’, ‘setattr’, ‘sizeof’, ‘str’,

15

sub’, ‘subclasshook’, ‘truediv’, ‘trunc’, ‘xor’,

16

‘bit_length’, ‘conjugate’, ‘denominator’, ‘from_bytes’, ‘imag’,

17

‘numerator’, ‘real’, ‘to_bytes’]

[‘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()的例子。

【例子】找到一个整数的二进制表示,再返回其长度。

1
a = 1031
2
print(bin(a)) # 0b10000000111
3
print(a.bit_length()) # 11
0b10000000111

11
浮点型

【例子】

1
print(1, type(1))
2

1 <class ‘int’>

3

4
print(1., type(1.))
5

1.0 <class ‘float’>

6

7
a = 0.00000023
8
b = 2.3e-7
9
print(a) # 2.3e-07
10
print(b) # 2.3e-07
1 <class ‘int’>

1.0 <class ‘float’>

2.3e-07

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

1
import decimal
2
from decimal import Decimal
Python 里面有很多用途广泛的包 (package),用什么你就引进 (import) 什么。包也是对象,也可以用上面提到的dir(decimal) 来看其属性和方法。

【例子】getcontext() 显示了 Decimal 对象的默认精度值是 28 位 (prec=28)。

1
a = decimal.getcontext()
2
print(a)
3

4

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,

5

capitals=1, clamp=0, flags=[],

6

traps=[InvalidOperation, DivisionByZero, Overflow])

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
1
b = Decimal(1) / Decimal(3)
2
print(b)
3

4

0.3333333333333333333333333333

0.3333333333333333333333333333
【例子】使 1/3 保留 4 位,用 getcontext().prec 来调整精度。

1
decimal.getcontext().prec = 4
2
c = Decimal(1) / Decimal(3)
3
print©
4

5

0.3333

0.3333
布尔型

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

【例子】

1
print(True + True) # 2
2
print(True + False) # 1
3
print(True * False) # 0
2

1

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

基本类型:整型、浮点型、布尔型
容器类型:字符串、元组、列表、字典和集合
【例子】bool 作用在基本类型变量:X 只要不是整型 0、浮点型 0.0,bool(X) 就是 True,其余就是 False。

1
print(type(0), bool(0), bool(1))
2

<class ‘int’> False True

3

4
print(type(10.31), bool(0.00), bool(10.31))
5

<class ‘float’> False True

6

7
print(type(True), bool(False), bool(True))
8

<class ‘bool’> False True

<class ‘int’> False True

<class ‘float’> False True

<class ‘bool’> False True
【例子】bool 作用在容器类型变量:X 只要不是空的变量,bool(X) 就是 True,其余就是 False。

1
print(type(’’), bool(’’), bool(‘python’))
2

<class ‘str’> False True

3

4
print(type(()), bool(()), bool((10,)))
5

<class ‘tuple’> False True

6

7
print(type([]), bool([]), bool([1, 2]))
8

<class ‘list’> False True

9

10
print(type({}), bool({}), bool({‘a’: 1, ‘b’: 2}))
11

<class ‘dict’> False True

12

13
print(type(set()), bool(set()), bool({1, 2}))
14

<class ‘set’> False True

<class ‘str’> False True

<class ‘tuple’> False True

<class ‘list’> False True

<class ‘dict’> False True

<class ‘set’> False True
确定bool(X) 的值是 True 还是 False,就看 X 是不是空,空的话就是 False,不空的话就是 True。

对于数值变量,0, 0.0 都可认为是空的。
对于容器变量,里面没元素就是空的。
获取类型信息

获取类型信息 type(object)
【例子】

1
print(isinstance(1, int)) # True
2
print(isinstance(5.2, float)) # True
3
print(isinstance(True, bool)) # True
4
print(isinstance(‘5.2’, str)) # True
True

True

True

True
注:

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

类型转换

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

1
print(int(‘520’)) # 520
2
print(int(520.52)) # 520
3
print(float(‘520.52’)) # 520.52
4
print(float(520)) # 520.0
5
print(str(10 + 10)) # 20
6
print(str(10.1 + 5.2)) # 15.3
520

520

520.52

520.0

20

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

1
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
2
print(“This is printed without 'end’and ‘sep’.”)
3
for item in shoplist:
4
print(item)
5

6

This is printed without 'end’and ‘sep’.

7

apple

8

mango

9

carrot

10

banana

This is printed without 'end’and ‘sep’.

apple

mango

carrot

banana
【例子】每次输出结束都用end设置的参数&结尾,并没有默认换行。

1
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
2
print(“This is printed with ‘end=’&’’.”)
3
for item in shoplist:
4
print(item, end=’&’)
5
print(‘hello world’)
6

7

This is printed with ‘end=’&’’.

8

apple&mango&carrot&banana&hello world

This is printed with ‘end=’&’’.

apple&mango&carrot&banana&hello world
【例子】item值与’another string’两个值之间用sep设置的参数&分割。由于end参数没有设置,因此默认是输出解释后换行,即end参数的默认值为\n。

1
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
2
print(“This is printed with ‘sep=’&’’.”)
3
for item in shoplist:
4
print(item, ‘another string’, sep=’&’)
5

6

This is printed with ‘sep=’&’’.

7

apple&another string

8

mango&another string

9

carrot&another string

10

banana&another string

This is printed with ‘sep=’&’’.

apple&another string

mango&another string

carrot&another string

banana&another string
位运算

  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表示负数。在位运算中符号位也参与运算。

  1. 按位运算
    按位非操作 ~
    ~ 1 = 0
    ~ 0 = 1
    ~ 把num的补码中的 0 和 1 全部取反(0 变为 1,1 变为 0)有符号整数的符号位在 ~ 运算中同样会取反。

00 00 01 01 -> 5
~

11 11 10 10 -> -6

11 11 10 11 -> -5
~

00 00 01 00 -> 4
按位与操作 &
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
只有两个对应位都为 1 时才为 1

00 00 01 01 -> 5
&
00 00 01 10 -> 6

00 00 01 00 -> 4
按位或操作 |
1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0
只要两个对应位中有一个 1 时就为 1

00 00 01 01 -> 5
|
00 00 01 10 -> 6

00 00 01 11 -> 7
按位异或操作 ^
1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
只有两个对应位不同时才为 1

00 00 01 01 -> 5
^
00 00 01 10 -> 6

00 00 00 11 -> 3
异或操作的性质:满足交换律和结合律

A: 00 00 11 00
B: 00 00 01 11

A^B: 00 00 10 11
B^A: 00 00 10 11

A^A: 00 00 00 00
A^0: 00 00 11 00

ABA: = AAB = B = 00 00 01 11
按位左移操作 <<
num << i 将num的二进制表示向左移动i位所得的值。

00 00 10 11 -> 11
11 << 3

01 01 10 00 -> 88
按位右移操作 >>
num >> i 将num的二进制表示向右移动i位所得的值。

00 00 10 11 -> 11
11 >> 2

00 00 00 10 -> 2
3. 利用位运算实现快速计算
通过 <<,>> 快速计算2的倍数问题。

n << 1 -> 计算 n2
n >> 1 -> 计算 n/2,负奇数的运算不可用
n << m -> 计算 n
(2^m),即乘以 2 的 m 次方
n >> m -> 计算 n/(2^m),即除以 2 的 m 次方
1 << n -> 2^n
通过 ^ 快速交换两个整数。 通过 ^ 快速交换两个整数。

a ^= b
b ^= a
a ^= b
通过 a & (-a) 快速获取a的最后为 1 位置的整数。

00 00 01 01 -> 5
&
11 11 10 11 -> -5

00 00 00 01 -> 1

00 00 11 10 -> 14
&
11 11 00 10 -> -14

00 00 00 10 -> 2
4. 利用位运算实现整数集合
一个数的二进制表示可以看作是一个集合(0 表示不在集合中,1 表示在集合中)。

比如集合 {1, 3, 4, 8},可以表示成 01 00 01 10 10 而对应的位运算也就可以看作是对集合进行的操作。

元素与集合的操作:

a | (1<<i) -> 把 i 插入到集合中
a & ~(1<<i) -> 把 i 从集合中删除
a & (1<<i) -> 判断 i 是否属于该集合(零不属于,非零属于)
集合之间的操作:

a 补 -> ~a
a 交 b -> a & b
a 并 b -> a | b
a 差 b -> a & (~b)
注意:整数在内存中是以补码的形式存在的,输出自然也是按照补码输出。

【例子】C#语言输出负数。

1
class Program
2
{
3
static void Main(string[] args)
4
{
5
string s1 = Convert.ToString(-3, 2);
6
Console.WriteLine(s1);
7
// 11111111111111111111111111111101
8

9
string s2 = Convert.ToString(-3, 16);
10
Console.WriteLine(s2);
11
// fffffffd
12
}
13
}
【例子】 Python 的bin() 输出。

1
print(bin(3)) # 0b11
2
print(bin(-3)) # -0b11
3

4
print(bin(-3 & 0xffffffff))
5

0b11111111111111111111111111111101

6

7
print(bin(0xfffffffd))
8

0b11111111111111111111111111111101

9

10
print(0xfffffffd) # 4294967293
0b11

-0b11

0b11111111111111111111111111111101

0b11111111111111111111111111111101

4294967293
是不是很颠覆认知,我们从结果可以看出:

Python中bin一个负数(十进制表示),输出的是它的原码的二进制表示加上个负号,巨坑。
Python中的整型是补码形式存储的。
Python中整型是不限制长度的不会超范围溢出。
所以为了获得负数(十进制表示)的补码,需要手动将其和十六进制数0xffffffff进行按位与操作,再交给bin()进行输出,得到的才是负数的补码表示。

条件语句

  1. if 语句
if expression:
    expr_true_suite

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

if expression:
    expr_true_suite
else:
    expr_false_suite

a.Python 提供与 if 搭配使用的 else,如果 if 语句的条件表达式结果布尔值为假,那么程序将执行 else 语句后的代码。
b.if语句支持嵌套,即在一个if语句中嵌入另一个if语句,从而构成不同层次的选择结构。
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,用来检查多个表达式是否为真,并在为真时执行特定代码块中的代码
4. assert 关键词
assert这个关键词我们称之为“断言”,当这个关键词后边的条件为 False 时,程序自动崩溃并抛出AssertionError的异常。

循环语句

Python入门(上)
简介

变量、运算符与数据类型

  1. 注释
  2. 运算符
  3. 变量和赋值
  4. 数据类型与转换
  5. print()函数

位运算

  1. 原码、反码和补码
  2. 按位运算
  3. 利用位运算实现快速计算
  4. 利用位运算实现整数集合

条件语句

  1. if 语句
  2. if - else 语句
  3. if - elif - else 语句
  4. assert 关键词

循环语句

  1. while 循环
  2. while - else 循环
  3. for 循环
  4. for - else 循环
  5. range() 函数
  6. enumerate()函数
  7. break 语句
  8. continue 语句
  9. pass 语句
  10. 推导式

异常处理

  1. Python 标准异常总结
  2. Python 标准警告总结
  3. try - except 语句
  4. try - except - finally 语句
  5. try - except - else 语句
  6. raise语句

简介
Python 是一种通用编程语言,其在科学计算和机器学习领域具有广泛的应用。如果我们打算利用 Python 来执行机器学习,那么对 Python 有一些基本的了解就是至关重要的。本 Python 入门系列体验就是为这样的初学者精心准备的。

天池官方为大家准备钉钉学习交流群,在学习过程中,大家有任何教程内容或者平台使用问题都可以在群内提出,扫码即可加入:

Image
本实验包括以下内容:

变量、运算符与数据类型
注释
运算符
变量和赋值
数据类型与转换
print() 函数
位运算
原码、反码和补码
按位非操作 ~
按位与操作 &
按位或操作 |
按位异或操作 ^
按位左移操作 <<
按位右移操作 >>
利用位运算实现快速计算
利用位运算实现整数集合
条件语句
if 语句
if - else 语句
if - elif - else 语句
assert 关键词
循环语句
while 循环
while - else 循环
for 循环
for - else 循环
range() 函数
enumerate()函数
break 语句
continue 语句
pass 语句
推导式
异常处理
Python 标准异常总结
Python 标准警告总结
try - except 语句
try - except - finally 语句
try - except - else 语句
raise语句
变量、运算符与数据类型

  1. 注释
    在 Python 中,# 表示注释,作用于整行。
    【例子】单行注释

1

这是一个注释

2
print(“Hello world”)
3

4

Hello world

Hello world
‘’’ ‘’’ 或者 “”" “”" 表示区间注释,在三引号之间的所有内容被注释
【例子】多行注释

1
‘’’
2
这是多行注释,用三个单引号
3
这是多行注释,用三个单引号
4
这是多行注释,用三个单引号
5
‘’’
6
print(“Hello china”)
7

Hello china

8

9
“”"
10
这是多行注释,用三个双引号
11
这是多行注释,用三个双引号
12
这是多行注释,用三个双引号
13
“”"
14
print(“hello china”)
15

hello china

Hello china

hello china
【我是测试题1】请在下方代码块中打印(print)出 hello+你的姓名
如:print(“hello 老表”)

1

写下你的答案

2

2. 运算符
算术运算符

操作符 名称 示例

  • 加 1 + 1
  • 减 2 - 1
  • 乘 3 * 4
    / 除 3 / 4
    // 整除(地板除) 3 // 4
    % 取余 3 % 4
    ** 幂 2 ** 3
    【例子】

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

1

12

0.75

0

3

8
比较运算符

操作符 名称 示例

大于 2 > 1
= 大于等于 2 >= 4
< 小于 1 < 2
<= 小于等于 5 <= 2
== 等于 3 == 4
!= 不等于 3 != 5
【例子】

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

False

True

False

False

True
逻辑运算符

操作符 名称 示例
and 与 (3 > 2) and (3 < 5)
or 或 (1 > 3) or (9 < 2)
not 非 not (2 > 1)
【例子】

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

False

False
位运算符

操作符 名称 示例
按位取反 ~4
& 按位与 4 & 5
按位或
^ 按位异或 4 ^ 5
<< 左移 4 << 2

右移 4 >> 2
【例子】有关二进制的运算,参见“位运算”部分的讲解。

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

0b101

-0b101 -5

0b100 4

0b101 5

0b1 1

0b10000 16

0b1 1
三元运算符

【例子】

1
x, y = 4, 5
2
if x < y:
3
small = x
4
else:
5
small = y
6

7
print(small) # 4
4
有了这个三元操作符的条件表达式,你可以使用一条语句来完成以上的条件判断和赋值操作。

【例子】

1
x, y = 4, 5
2
small = x if x < y else y
3
print(small) # 4
4
其他运算符

操作符 名称 示例
in 存在 ‘A’ in [‘A’, ‘B’, ‘C’]
not in 不存在 ‘h’ not in [‘A’, ‘B’, ‘C’]
is 是 “hello” is “hello”
not is 不是 “hello” is not “hello”
【例子】

1
letters = [‘A’, ‘B’, ‘C’]
2
if ‘A’ in letters:
3
print(‘A’ + ’ exists’)
4
if ‘h’ not in letters:
5
print(‘h’ + ’ not exists’)
6

7

A exists

8

h not exists

A exists

h not exists
【例子】比较的两个变量均指向不可变类型。

1
a = “hello”
2
b = “hello”
3
print(a is b, a == b) # True True
4
print(a is not b, a != b) # False False
True True

False False
【例子】比较的两个变量均指向可变类型。

1
a = [“hello”]
2
b = [“hello”]
3
print(a is b, a == b) # False True
4
print(a is not b, a != b) # True False
False True

True False
注意:

is, is not 对比的是两个变量的内存地址
==, != 对比的是两个变量的值
比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。
对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的。
运算符的优先级

运算符 描述
** 指数(最高优先级)
~± 按位翻转,一元加号和减号

  • / % // 乘,除,取模和取整除)
    • 加法减法

<< 右移,左移运算符
& 位‘AND’
^| 位运算符
<=<>>= 比较运算符
<>!= 等于运算符
=%=/=//=-=+
*= 赋值运算符
is is not 身份运算符
in not in 成员运算符
not and or 逻辑运算符
【例子】

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

0.1111111111111111

0

-12.5

True
【我是测试题2】下面这段代码的运行结果是什么?

1

运行一下结果就出来了

2
a = “hello”
3
b = “hello”
4
print(a is b, a == b)
3. 变量和赋值
在使用变量之前,需要对其先赋值。
变量名可以包括字母、数字、下划线、但变量名不能以数字开头。
Python 变量名是大小写敏感的,foo != Foo。
【例子】

1
teacher = “老马的程序人生”
2
print(teacher) # 老马的程序人生
老马的程序人生
【例子】

1
first = 2
2
second = 3
3
third = first + second
4
print(third) # 5
5
【例子】

1
myTeacher = “老马的程序人生”
2
yourTeacher = “小马的程序人生”
3
ourTeacher = myTeacher + ‘,’ + yourTeacher
4
print(ourTeacher) # 老马的程序人生,小马的程序人生
老马的程序人生,小马的程序人生
【我是测试题3】运行下面一段代码看看结果是什么?

1

运行一下就好啦

2
set_1 = {“欢迎”, “学习”,“Python”}
3
print(set_1.pop())
4. 数据类型与转换
类型 名称 示例
int 整型 <class ‘int’> -876, 10
float 浮点型<class ‘float’> 3.149, 11.11
bool 布尔型<class ‘bool’> True, False
整型

【例子】通过 print() 可看出 a 的值,以及类 (class) 是int。

1
a = 1031
2
print(a, type(a))
3

1031 <class ‘int’>

1031 <class ‘int’>
Python 里面万物皆对象(object),整型也不例外,只要是对象,就有相应的属性 (attributes) 和方法(methods)。

【例子】

1
b = dir(int)
2
print(b)
3

4

[‘abs’, ‘add’, ‘and’, ‘bool’, ‘ceil’, ‘class’,

5

delattr’, ‘dir’, ‘divmod’, ‘doc’, ‘eq’,

6

float’, ‘floor’, ‘floordiv’, ‘format’, ‘ge’,

7

getattribute’, ‘getnewargs’, ‘gt’, ‘hash’,

8

index’, ‘init’, ‘init_subclass’, ‘int’, ‘invert’,

9

le’, ‘lshift’, ‘lt’, ‘mod’, ‘mul’, ‘ne’,

10

neg’, ‘new’, ‘or’, ‘pos’, ‘pow’, ‘radd’,

11

rand’, ‘rdivmod’, ‘reduce’, ‘reduce_ex’, ‘repr’,

12

rfloordiv’, ‘rlshift’, ‘rmod’, ‘rmul’, ‘ror’,

13

round’, ‘rpow’, ‘rrshift’, ‘rshift’, ‘rsub’,

14

rtruediv’, ‘rxor’, ‘setattr’, ‘sizeof’, ‘str’,

15

sub’, ‘subclasshook’, ‘truediv’, ‘trunc’, ‘xor’,

16

‘bit_length’, ‘conjugate’, ‘denominator’, ‘from_bytes’, ‘imag’,

17

‘numerator’, ‘real’, ‘to_bytes’]

[‘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()的例子。

【例子】找到一个整数的二进制表示,再返回其长度。

1
a = 1031
2
print(bin(a)) # 0b10000000111
3
print(a.bit_length()) # 11
0b10000000111

11
浮点型

【例子】

1
print(1, type(1))
2

1 <class ‘int’>

3

4
print(1., type(1.))
5

1.0 <class ‘float’>

6

7
a = 0.00000023
8
b = 2.3e-7
9
print(a) # 2.3e-07
10
print(b) # 2.3e-07
1 <class ‘int’>

1.0 <class ‘float’>

2.3e-07

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

1
import decimal
2
from decimal import Decimal
Python 里面有很多用途广泛的包 (package),用什么你就引进 (import) 什么。包也是对象,也可以用上面提到的dir(decimal) 来看其属性和方法。

【例子】getcontext() 显示了 Decimal 对象的默认精度值是 28 位 (prec=28)。

1
a = decimal.getcontext()
2
print(a)
3

4

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,

5

capitals=1, clamp=0, flags=[],

6

traps=[InvalidOperation, DivisionByZero, Overflow])

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
1
b = Decimal(1) / Decimal(3)
2
print(b)
3

4

0.3333333333333333333333333333

0.3333333333333333333333333333
【例子】使 1/3 保留 4 位,用 getcontext().prec 来调整精度。

1
decimal.getcontext().prec = 4
2
c = Decimal(1) / Decimal(3)
3
print©
4

5

0.3333

0.3333
布尔型

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

【例子】

1
print(True + True) # 2
2
print(True + False) # 1
3
print(True * False) # 0
2

1

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

基本类型:整型、浮点型、布尔型
容器类型:字符串、元组、列表、字典和集合
【例子】bool 作用在基本类型变量:X 只要不是整型 0、浮点型 0.0,bool(X) 就是 True,其余就是 False。

1
print(type(0), bool(0), bool(1))
2

<class ‘int’> False True

3

4
print(type(10.31), bool(0.00), bool(10.31))
5

<class ‘float’> False True

6

7
print(type(True), bool(False), bool(True))
8

<class ‘bool’> False True

<class ‘int’> False True

<class ‘float’> False True

<class ‘bool’> False True
【例子】bool 作用在容器类型变量:X 只要不是空的变量,bool(X) 就是 True,其余就是 False。

1
print(type(’’), bool(’’), bool(‘python’))
2

<class ‘str’> False True

3

4
print(type(()), bool(()), bool((10,)))
5

<class ‘tuple’> False True

6

7
print(type([]), bool([]), bool([1, 2]))
8

<class ‘list’> False True

9

10
print(type({}), bool({}), bool({‘a’: 1, ‘b’: 2}))
11

<class ‘dict’> False True

12

13
print(type(set()), bool(set()), bool({1, 2}))
14

<class ‘set’> False True

<class ‘str’> False True

<class ‘tuple’> False True

<class ‘list’> False True

<class ‘dict’> False True

<class ‘set’> False True
确定bool(X) 的值是 True 还是 False,就看 X 是不是空,空的话就是 False,不空的话就是 True。

对于数值变量,0, 0.0 都可认为是空的。
对于容器变量,里面没元素就是空的。
获取类型信息

获取类型信息 type(object)
【例子】

1
print(isinstance(1, int)) # True
2
print(isinstance(5.2, float)) # True
3
print(isinstance(True, bool)) # True
4
print(isinstance(‘5.2’, str)) # True
True

True

True

True
注:

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

类型转换

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

1
print(int(‘520’)) # 520
2
print(int(520.52)) # 520
3
print(float(‘520.52’)) # 520.52
4
print(float(520)) # 520.0
5
print(str(10 + 10)) # 20
6
print(str(10.1 + 5.2)) # 15.3
520

520

520.52

520.0

20

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

1
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
2
print(“This is printed without 'end’and ‘sep’.”)
3
for item in shoplist:
4
print(item)
5

6

This is printed without 'end’and ‘sep’.

7

apple

8

mango

9

carrot

10

banana

This is printed without 'end’and ‘sep’.

apple

mango

carrot

banana
【例子】每次输出结束都用end设置的参数&结尾,并没有默认换行。

1
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
2
print(“This is printed with ‘end=’&’’.”)
3
for item in shoplist:
4
print(item, end=’&’)
5
print(‘hello world’)
6

7

This is printed with ‘end=’&’’.

8

apple&mango&carrot&banana&hello world

This is printed with ‘end=’&’’.

apple&mango&carrot&banana&hello world
【例子】item值与’another string’两个值之间用sep设置的参数&分割。由于end参数没有设置,因此默认是输出解释后换行,即end参数的默认值为\n。

1
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
2
print(“This is printed with ‘sep=’&’’.”)
3
for item in shoplist:
4
print(item, ‘another string’, sep=’&’)
5

6

This is printed with ‘sep=’&’’.

7

apple&another string

8

mango&another string

9

carrot&another string

10

banana&another string

This is printed with ‘sep=’&’’.

apple&another string

mango&another string

carrot&another string

banana&another string
位运算

  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表示负数。在位运算中符号位也参与运算。

  1. 按位运算
    按位非操作 ~
    ~ 1 = 0
    ~ 0 = 1
    ~ 把num的补码中的 0 和 1 全部取反(0 变为 1,1 变为 0)有符号整数的符号位在 ~ 运算中同样会取反。

00 00 01 01 -> 5
~

11 11 10 10 -> -6

11 11 10 11 -> -5
~

00 00 01 00 -> 4
按位与操作 &
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
只有两个对应位都为 1 时才为 1

00 00 01 01 -> 5
&
00 00 01 10 -> 6

00 00 01 00 -> 4
按位或操作 |
1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0
只要两个对应位中有一个 1 时就为 1

00 00 01 01 -> 5
|
00 00 01 10 -> 6

00 00 01 11 -> 7
按位异或操作 ^
1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
只有两个对应位不同时才为 1

00 00 01 01 -> 5
^
00 00 01 10 -> 6

00 00 00 11 -> 3
异或操作的性质:满足交换律和结合律

A: 00 00 11 00
B: 00 00 01 11

A^B: 00 00 10 11
B^A: 00 00 10 11

A^A: 00 00 00 00
A^0: 00 00 11 00

ABA: = AAB = B = 00 00 01 11
按位左移操作 <<
num << i 将num的二进制表示向左移动i位所得的值。

00 00 10 11 -> 11
11 << 3

01 01 10 00 -> 88
按位右移操作 >>
num >> i 将num的二进制表示向右移动i位所得的值。

00 00 10 11 -> 11
11 >> 2

00 00 00 10 -> 2
3. 利用位运算实现快速计算
通过 <<,>> 快速计算2的倍数问题。

n << 1 -> 计算 n2
n >> 1 -> 计算 n/2,负奇数的运算不可用
n << m -> 计算 n
(2^m),即乘以 2 的 m 次方
n >> m -> 计算 n/(2^m),即除以 2 的 m 次方
1 << n -> 2^n
通过 ^ 快速交换两个整数。 通过 ^ 快速交换两个整数。

a ^= b
b ^= a
a ^= b
通过 a & (-a) 快速获取a的最后为 1 位置的整数。

00 00 01 01 -> 5
&
11 11 10 11 -> -5

00 00 00 01 -> 1

00 00 11 10 -> 14
&
11 11 00 10 -> -14

00 00 00 10 -> 2
4. 利用位运算实现整数集合
一个数的二进制表示可以看作是一个集合(0 表示不在集合中,1 表示在集合中)。

比如集合 {1, 3, 4, 8},可以表示成 01 00 01 10 10 而对应的位运算也就可以看作是对集合进行的操作。

元素与集合的操作:

a | (1<<i) -> 把 i 插入到集合中
a & ~(1<<i) -> 把 i 从集合中删除
a & (1<<i) -> 判断 i 是否属于该集合(零不属于,非零属于)
集合之间的操作:

a 补 -> ~a
a 交 b -> a & b
a 并 b -> a | b
a 差 b -> a & (~b)
注意:整数在内存中是以补码的形式存在的,输出自然也是按照补码输出。

【例子】C#语言输出负数。

1
class Program
2
{
3
static void Main(string[] args)
4
{
5
string s1 = Convert.ToString(-3, 2);
6
Console.WriteLine(s1);
7
// 11111111111111111111111111111101
8

9
string s2 = Convert.ToString(-3, 16);
10
Console.WriteLine(s2);
11
// fffffffd
12
}
13
}
【例子】 Python 的bin() 输出。

1
print(bin(3)) # 0b11
2
print(bin(-3)) # -0b11
3

4
print(bin(-3 & 0xffffffff))
5

0b11111111111111111111111111111101

6

7
print(bin(0xfffffffd))
8

0b11111111111111111111111111111101

9

10
print(0xfffffffd) # 4294967293
0b11

-0b11

0b11111111111111111111111111111101

0b11111111111111111111111111111101

4294967293
是不是很颠覆认知,我们从结果可以看出:

Python中bin一个负数(十进制表示),输出的是它的原码的二进制表示加上个负号,巨坑。
Python中的整型是补码形式存储的。
Python中整型是不限制长度的不会超范围溢出。
所以为了获得负数(十进制表示)的补码,需要手动将其和十六进制数0xffffffff进行按位与操作,再交给bin()进行输出,得到的才是负数的补码表示。

条件语句

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

1
if 2 > 1 and not 2 > 3:
2
print(‘Correct Judgement!’)
3

4

Correct Judgement!

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

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

你太了解小姐姐的心思了!

哼,猜对也没有奖励!

游戏结束,不玩儿啦!
if语句支持嵌套,即在一个if语句中嵌入另一个if语句,从而构成不同层次的选择结构。

【例子】Python 使用缩进而不是大括号来标记代码块边界,因此要特别注意else的悬挂问题。

1
hi = 6
2
if hi > 2:
3
if hi > 7:
4
print(‘好棒!好棒!’)
5
else:
6
print(‘切~’)
7

8

无输出

【例子】

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

你太了解小姐姐的心思了!

哼,猜对也没有奖励!

游戏结束,不玩儿啦!
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,用来检查多个表达式是否为真,并在为真时执行特定代码块中的代码。
【例子】

1
temp = input(‘请输入成绩:’)
2
source = int(temp)
3
if 100 >= source >= 90:
4
print(‘A’)
5
elif 90 > source >= 80:
6
print(‘B’)
7
elif 80 > source >= 60:
8
print(‘C’)
9
elif 60 > source >= 0:
10
print(‘D’)
11
else:
12
print(‘输入错误!’)
请输入成绩:99

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

1
my_list = [‘lsgogroup’]
2
my_list.pop(0)
3
assert len(my_list) > 0
4

5

AssertionError

【例子】在进行单元测试时,可以用来在程序中置入检查点,只有条件为 True 才能让程序正常工作。

1
assert 3 > 7
2

3

AssertionError

循环语句

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

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

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

while 布尔表达式:
    代码块
else:
    代码块

当while循环正常执行完的情况下,执行else输出,如果while循环中执行了跳出循环的语句,比如 break,将不执行else代码块的内容。
3. for 循环
for循环是迭代循环,在Python中相当于一个通用的序列迭代器,可以遍历任何有序序列,如str、list、tuple等,也可以遍历任何可迭代对象,如dict。

for 迭代变量 in 可迭代对象:
    代码块

每次循环,迭代变量被设置为可迭代对象的当前元素,提供给代码块使用。
4. for - else 循环

for 迭代变量 in 可迭代对象:
    代码块
else:
    代码块

当for循环正常执行完的情况下,执行else输出,如果for循环中执行了跳出循环的语句,比如 break,将不执行else代码块的内容,与while - else语句一样。
5. range() 函数

range([start,] stop[, step=1])

这个BIF(Built-in functions)有三个参数,其中用中括号括起来的两个表示这两个参数是可选的。
step=1 表示第三个参数的默认值是1。
range 这个BIF的作用是生成一个从start参数的值开始到stop参数的值结束的数字序列,该序列包含start的值但不包含stop的值.
6. enumerate()函数

enumerate(sequence, [start=0])

sequence:一个序列、迭代器或其他支持迭代对象。
start:下标起始位置。返回 enumerate(枚举) 对象。
7.break和continue。
break :终止循环。循环终止(跳出循环)
continue:结束此次循环,循环继续。
Python入门(上)
简介

变量、运算符与数据类型

  1. 注释
  2. 运算符
  3. 变量和赋值
  4. 数据类型与转换
  5. print()函数

位运算

  1. 原码、反码和补码
  2. 按位运算
  3. 利用位运算实现快速计算
  4. 利用位运算实现整数集合

条件语句

  1. if 语句
  2. if - else 语句
  3. if - elif - else 语句
  4. assert 关键词

循环语句

  1. while 循环
  2. while - else 循环
  3. for 循环
  4. for - else 循环
  5. range() 函数
  6. enumerate()函数
  7. break 语句
  8. continue 语句
  9. pass 语句
  10. 推导式

异常处理

  1. Python 标准异常总结
  2. Python 标准警告总结
  3. try - except 语句
  4. try - except - finally 语句
  5. try - except - else 语句
  6. raise语句

简介
Python 是一种通用编程语言,其在科学计算和机器学习领域具有广泛的应用。如果我们打算利用 Python 来执行机器学习,那么对 Python 有一些基本的了解就是至关重要的。本 Python 入门系列体验就是为这样的初学者精心准备的。

天池官方为大家准备钉钉学习交流群,在学习过程中,大家有任何教程内容或者平台使用问题都可以在群内提出,扫码即可加入:

Image
本实验包括以下内容:

变量、运算符与数据类型
注释
运算符
变量和赋值
数据类型与转换
print() 函数
位运算
原码、反码和补码
按位非操作 ~
按位与操作 &
按位或操作 |
按位异或操作 ^
按位左移操作 <<
按位右移操作 >>
利用位运算实现快速计算
利用位运算实现整数集合
条件语句
if 语句
if - else 语句
if - elif - else 语句
assert 关键词
循环语句
while 循环
while - else 循环
for 循环
for - else 循环
range() 函数
enumerate()函数
break 语句
continue 语句
pass 语句
推导式
异常处理
Python 标准异常总结
Python 标准警告总结
try - except 语句
try - except - finally 语句
try - except - else 语句
raise语句
变量、运算符与数据类型

  1. 注释
    在 Python 中,# 表示注释,作用于整行。
    【例子】单行注释

1

这是一个注释

2
print(“Hello world”)
3

4

Hello world

Hello world
‘’’ ‘’’ 或者 “”" “”" 表示区间注释,在三引号之间的所有内容被注释
【例子】多行注释

1
‘’’
2
这是多行注释,用三个单引号
3
这是多行注释,用三个单引号
4
这是多行注释,用三个单引号
5
‘’’
6
print(“Hello china”)
7

Hello china

8

9
“”"
10
这是多行注释,用三个双引号
11
这是多行注释,用三个双引号
12
这是多行注释,用三个双引号
13
“”"
14
print(“hello china”)
15

hello china

Hello china

hello china
【我是测试题1】请在下方代码块中打印(print)出 hello+你的姓名
如:print(“hello 老表”)

1

写下你的答案

2

2. 运算符
算术运算符

操作符 名称 示例

  • 加 1 + 1
  • 减 2 - 1
  • 乘 3 * 4
    / 除 3 / 4
    // 整除(地板除) 3 // 4
    % 取余 3 % 4
    ** 幂 2 ** 3
    【例子】

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

1

12

0.75

0

3

8
比较运算符

操作符 名称 示例

大于 2 > 1
= 大于等于 2 >= 4
< 小于 1 < 2
<= 小于等于 5 <= 2
== 等于 3 == 4
!= 不等于 3 != 5
【例子】

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

False

True

False

False

True
逻辑运算符

操作符 名称 示例
and 与 (3 > 2) and (3 < 5)
or 或 (1 > 3) or (9 < 2)
not 非 not (2 > 1)
【例子】

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

False

False
位运算符

操作符 名称 示例
按位取反 ~4
& 按位与 4 & 5
按位或
^ 按位异或 4 ^ 5
<< 左移 4 << 2

右移 4 >> 2
【例子】有关二进制的运算,参见“位运算”部分的讲解。

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

0b101

-0b101 -5

0b100 4

0b101 5

0b1 1

0b10000 16

0b1 1
三元运算符

【例子】

1
x, y = 4, 5
2
if x < y:
3
small = x
4
else:
5
small = y
6

7
print(small) # 4
4
有了这个三元操作符的条件表达式,你可以使用一条语句来完成以上的条件判断和赋值操作。

【例子】

1
x, y = 4, 5
2
small = x if x < y else y
3
print(small) # 4
4
其他运算符

操作符 名称 示例
in 存在 ‘A’ in [‘A’, ‘B’, ‘C’]
not in 不存在 ‘h’ not in [‘A’, ‘B’, ‘C’]
is 是 “hello” is “hello”
not is 不是 “hello” is not “hello”
【例子】

1
letters = [‘A’, ‘B’, ‘C’]
2
if ‘A’ in letters:
3
print(‘A’ + ’ exists’)
4
if ‘h’ not in letters:
5
print(‘h’ + ’ not exists’)
6

7

A exists

8

h not exists

A exists

h not exists
【例子】比较的两个变量均指向不可变类型。

1
a = “hello”
2
b = “hello”
3
print(a is b, a == b) # True True
4
print(a is not b, a != b) # False False
True True

False False
【例子】比较的两个变量均指向可变类型。

1
a = [“hello”]
2
b = [“hello”]
3
print(a is b, a == b) # False True
4
print(a is not b, a != b) # True False
False True

True False
注意:

is, is not 对比的是两个变量的内存地址
==, != 对比的是两个变量的值
比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。
对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的。
运算符的优先级

运算符 描述
** 指数(最高优先级)
~± 按位翻转,一元加号和减号

  • / % // 乘,除,取模和取整除)
    • 加法减法

<< 右移,左移运算符
& 位‘AND’
^| 位运算符
<=<>>= 比较运算符
<>!= 等于运算符
=%=/=//=-=+
*= 赋值运算符
is is not 身份运算符
in not in 成员运算符
not and or 逻辑运算符
【例子】

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

0.1111111111111111

0

-12.5

True
【我是测试题2】下面这段代码的运行结果是什么?

1

运行一下结果就出来了

2
a = “hello”
3
b = “hello”
4
print(a is b, a == b)
3. 变量和赋值
在使用变量之前,需要对其先赋值。
变量名可以包括字母、数字、下划线、但变量名不能以数字开头。
Python 变量名是大小写敏感的,foo != Foo。
【例子】

1
teacher = “老马的程序人生”
2
print(teacher) # 老马的程序人生
老马的程序人生
【例子】

1
first = 2
2
second = 3
3
third = first + second
4
print(third) # 5
5
【例子】

1
myTeacher = “老马的程序人生”
2
yourTeacher = “小马的程序人生”
3
ourTeacher = myTeacher + ‘,’ + yourTeacher
4
print(ourTeacher) # 老马的程序人生,小马的程序人生
老马的程序人生,小马的程序人生
【我是测试题3】运行下面一段代码看看结果是什么?

1

运行一下就好啦

2
set_1 = {“欢迎”, “学习”,“Python”}
3
print(set_1.pop())
4. 数据类型与转换
类型 名称 示例
int 整型 <class ‘int’> -876, 10
float 浮点型<class ‘float’> 3.149, 11.11
bool 布尔型<class ‘bool’> True, False
整型

【例子】通过 print() 可看出 a 的值,以及类 (class) 是int。

1
a = 1031
2
print(a, type(a))
3

1031 <class ‘int’>

1031 <class ‘int’>
Python 里面万物皆对象(object),整型也不例外,只要是对象,就有相应的属性 (attributes) 和方法(methods)。

【例子】

1
b = dir(int)
2
print(b)
3

4

[‘abs’, ‘add’, ‘and’, ‘bool’, ‘ceil’, ‘class’,

5

delattr’, ‘dir’, ‘divmod’, ‘doc’, ‘eq’,

6

float’, ‘floor’, ‘floordiv’, ‘format’, ‘ge’,

7

getattribute’, ‘getnewargs’, ‘gt’, ‘hash’,

8

index’, ‘init’, ‘init_subclass’, ‘int’, ‘invert’,

9

le’, ‘lshift’, ‘lt’, ‘mod’, ‘mul’, ‘ne’,

10

neg’, ‘new’, ‘or’, ‘pos’, ‘pow’, ‘radd’,

11

rand’, ‘rdivmod’, ‘reduce’, ‘reduce_ex’, ‘repr’,

12

rfloordiv’, ‘rlshift’, ‘rmod’, ‘rmul’, ‘ror’,

13

round’, ‘rpow’, ‘rrshift’, ‘rshift’, ‘rsub’,

14

rtruediv’, ‘rxor’, ‘setattr’, ‘sizeof’, ‘str’,

15

sub’, ‘subclasshook’, ‘truediv’, ‘trunc’, ‘xor’,

16

‘bit_length’, ‘conjugate’, ‘denominator’, ‘from_bytes’, ‘imag’,

17

‘numerator’, ‘real’, ‘to_bytes’]

[‘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()的例子。

【例子】找到一个整数的二进制表示,再返回其长度。

1
a = 1031
2
print(bin(a)) # 0b10000000111
3
print(a.bit_length()) # 11
0b10000000111

11
浮点型

【例子】

1
print(1, type(1))
2

1 <class ‘int’>

3

4
print(1., type(1.))
5

1.0 <class ‘float’>

6

7
a = 0.00000023
8
b = 2.3e-7
9
print(a) # 2.3e-07
10
print(b) # 2.3e-07
1 <class ‘int’>

1.0 <class ‘float’>

2.3e-07

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

1
import decimal
2
from decimal import Decimal
Python 里面有很多用途广泛的包 (package),用什么你就引进 (import) 什么。包也是对象,也可以用上面提到的dir(decimal) 来看其属性和方法。

【例子】getcontext() 显示了 Decimal 对象的默认精度值是 28 位 (prec=28)。

1
a = decimal.getcontext()
2
print(a)
3

4

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,

5

capitals=1, clamp=0, flags=[],

6

traps=[InvalidOperation, DivisionByZero, Overflow])

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
1
b = Decimal(1) / Decimal(3)
2
print(b)
3

4

0.3333333333333333333333333333

0.3333333333333333333333333333
【例子】使 1/3 保留 4 位,用 getcontext().prec 来调整精度。

1
decimal.getcontext().prec = 4
2
c = Decimal(1) / Decimal(3)
3
print©
4

5

0.3333

0.3333
布尔型

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

【例子】

1
print(True + True) # 2
2
print(True + False) # 1
3
print(True * False) # 0
2

1

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

基本类型:整型、浮点型、布尔型
容器类型:字符串、元组、列表、字典和集合
【例子】bool 作用在基本类型变量:X 只要不是整型 0、浮点型 0.0,bool(X) 就是 True,其余就是 False。

1
print(type(0), bool(0), bool(1))
2

<class ‘int’> False True

3

4
print(type(10.31), bool(0.00), bool(10.31))
5

<class ‘float’> False True

6

7
print(type(True), bool(False), bool(True))
8

<class ‘bool’> False True

<class ‘int’> False True

<class ‘float’> False True

<class ‘bool’> False True
【例子】bool 作用在容器类型变量:X 只要不是空的变量,bool(X) 就是 True,其余就是 False。

1
print(type(’’), bool(’’), bool(‘python’))
2

<class ‘str’> False True

3

4
print(type(()), bool(()), bool((10,)))
5

<class ‘tuple’> False True

6

7
print(type([]), bool([]), bool([1, 2]))
8

<class ‘list’> False True

9

10
print(type({}), bool({}), bool({‘a’: 1, ‘b’: 2}))
11

<class ‘dict’> False True

12

13
print(type(set()), bool(set()), bool({1, 2}))
14

<class ‘set’> False True

<class ‘str’> False True

<class ‘tuple’> False True

<class ‘list’> False True

<class ‘dict’> False True

<class ‘set’> False True
确定bool(X) 的值是 True 还是 False,就看 X 是不是空,空的话就是 False,不空的话就是 True。

对于数值变量,0, 0.0 都可认为是空的。
对于容器变量,里面没元素就是空的。
获取类型信息

获取类型信息 type(object)
【例子】

1
print(isinstance(1, int)) # True
2
print(isinstance(5.2, float)) # True
3
print(isinstance(True, bool)) # True
4
print(isinstance(‘5.2’, str)) # True
True

True

True

True
注:

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

类型转换

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

1
print(int(‘520’)) # 520
2
print(int(520.52)) # 520
3
print(float(‘520.52’)) # 520.52
4
print(float(520)) # 520.0
5
print(str(10 + 10)) # 20
6
print(str(10.1 + 5.2)) # 15.3
520

520

520.52

520.0

20

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

1
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
2
print(“This is printed without 'end’and ‘sep’.”)
3
for item in shoplist:
4
print(item)
5

6

This is printed without 'end’and ‘sep’.

7

apple

8

mango

9

carrot

10

banana

This is printed without 'end’and ‘sep’.

apple

mango

carrot

banana
【例子】每次输出结束都用end设置的参数&结尾,并没有默认换行。

1
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
2
print(“This is printed with ‘end=’&’’.”)
3
for item in shoplist:
4
print(item, end=’&’)
5
print(‘hello world’)
6

7

This is printed with ‘end=’&’’.

8

apple&mango&carrot&banana&hello world

This is printed with ‘end=’&’’.

apple&mango&carrot&banana&hello world
【例子】item值与’another string’两个值之间用sep设置的参数&分割。由于end参数没有设置,因此默认是输出解释后换行,即end参数的默认值为\n。

1
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
2
print(“This is printed with ‘sep=’&’’.”)
3
for item in shoplist:
4
print(item, ‘another string’, sep=’&’)
5

6

This is printed with ‘sep=’&’’.

7

apple&another string

8

mango&another string

9

carrot&another string

10

banana&another string

This is printed with ‘sep=’&’’.

apple&another string

mango&another string

carrot&another string

banana&another string
位运算

  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表示负数。在位运算中符号位也参与运算。

  1. 按位运算
    按位非操作 ~
    ~ 1 = 0
    ~ 0 = 1
    ~ 把num的补码中的 0 和 1 全部取反(0 变为 1,1 变为 0)有符号整数的符号位在 ~ 运算中同样会取反。

00 00 01 01 -> 5
~

11 11 10 10 -> -6

11 11 10 11 -> -5
~

00 00 01 00 -> 4
按位与操作 &
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
只有两个对应位都为 1 时才为 1

00 00 01 01 -> 5
&
00 00 01 10 -> 6

00 00 01 00 -> 4
按位或操作 |
1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0
只要两个对应位中有一个 1 时就为 1

00 00 01 01 -> 5
|
00 00 01 10 -> 6

00 00 01 11 -> 7
按位异或操作 ^
1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
只有两个对应位不同时才为 1

00 00 01 01 -> 5
^
00 00 01 10 -> 6

00 00 00 11 -> 3
异或操作的性质:满足交换律和结合律

A: 00 00 11 00
B: 00 00 01 11

A^B: 00 00 10 11
B^A: 00 00 10 11

A^A: 00 00 00 00
A^0: 00 00 11 00

ABA: = AAB = B = 00 00 01 11
按位左移操作 <<
num << i 将num的二进制表示向左移动i位所得的值。

00 00 10 11 -> 11
11 << 3

01 01 10 00 -> 88
按位右移操作 >>
num >> i 将num的二进制表示向右移动i位所得的值。

00 00 10 11 -> 11
11 >> 2

00 00 00 10 -> 2
3. 利用位运算实现快速计算
通过 <<,>> 快速计算2的倍数问题。

n << 1 -> 计算 n2
n >> 1 -> 计算 n/2,负奇数的运算不可用
n << m -> 计算 n
(2^m),即乘以 2 的 m 次方
n >> m -> 计算 n/(2^m),即除以 2 的 m 次方
1 << n -> 2^n
通过 ^ 快速交换两个整数。 通过 ^ 快速交换两个整数。

a ^= b
b ^= a
a ^= b
通过 a & (-a) 快速获取a的最后为 1 位置的整数。

00 00 01 01 -> 5
&
11 11 10 11 -> -5

00 00 00 01 -> 1

00 00 11 10 -> 14
&
11 11 00 10 -> -14

00 00 00 10 -> 2
4. 利用位运算实现整数集合
一个数的二进制表示可以看作是一个集合(0 表示不在集合中,1 表示在集合中)。

比如集合 {1, 3, 4, 8},可以表示成 01 00 01 10 10 而对应的位运算也就可以看作是对集合进行的操作。

元素与集合的操作:

a | (1<<i) -> 把 i 插入到集合中
a & ~(1<<i) -> 把 i 从集合中删除
a & (1<<i) -> 判断 i 是否属于该集合(零不属于,非零属于)
集合之间的操作:

a 补 -> ~a
a 交 b -> a & b
a 并 b -> a | b
a 差 b -> a & (~b)
注意:整数在内存中是以补码的形式存在的,输出自然也是按照补码输出。

【例子】C#语言输出负数。

1
class Program
2
{
3
static void Main(string[] args)
4
{
5
string s1 = Convert.ToString(-3, 2);
6
Console.WriteLine(s1);
7
// 11111111111111111111111111111101
8

9
string s2 = Convert.ToString(-3, 16);
10
Console.WriteLine(s2);
11
// fffffffd
12
}
13
}
【例子】 Python 的bin() 输出。

1
print(bin(3)) # 0b11
2
print(bin(-3)) # -0b11
3

4
print(bin(-3 & 0xffffffff))
5

0b11111111111111111111111111111101

6

7
print(bin(0xfffffffd))
8

0b11111111111111111111111111111101

9

10
print(0xfffffffd) # 4294967293
0b11

-0b11

0b11111111111111111111111111111101

0b11111111111111111111111111111101

4294967293
是不是很颠覆认知,我们从结果可以看出:

Python中bin一个负数(十进制表示),输出的是它的原码的二进制表示加上个负号,巨坑。
Python中的整型是补码形式存储的。
Python中整型是不限制长度的不会超范围溢出。
所以为了获得负数(十进制表示)的补码,需要手动将其和十六进制数0xffffffff进行按位与操作,再交给bin()进行输出,得到的才是负数的补码表示。

条件语句

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

1
if 2 > 1 and not 2 > 3:
2
print(‘Correct Judgement!’)
3

4

Correct Judgement!

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

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

你太了解小姐姐的心思了!

哼,猜对也没有奖励!

游戏结束,不玩儿啦!
if语句支持嵌套,即在一个if语句中嵌入另一个if语句,从而构成不同层次的选择结构。

【例子】Python 使用缩进而不是大括号来标记代码块边界,因此要特别注意else的悬挂问题。

1
hi = 6
2
if hi > 2:
3
if hi > 7:
4
print(‘好棒!好棒!’)
5
else:
6
print(‘切~’)
7

8

无输出

【例子】

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

你太了解小姐姐的心思了!

哼,猜对也没有奖励!

游戏结束,不玩儿啦!
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,用来检查多个表达式是否为真,并在为真时执行特定代码块中的代码。
【例子】

1
temp = input(‘请输入成绩:’)
2
source = int(temp)
3
if 100 >= source >= 90:
4
print(‘A’)
5
elif 90 > source >= 80:
6
print(‘B’)
7
elif 80 > source >= 60:
8
print(‘C’)
9
elif 60 > source >= 0:
10
print(‘D’)
11
else:
12
print(‘输入错误!’)
请输入成绩:99

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

1
my_list = [‘lsgogroup’]
2
my_list.pop(0)
3
assert len(my_list) > 0
4

5

AssertionError

【例子】在进行单元测试时,可以用来在程序中置入检查点,只有条件为 True 才能让程序正常工作。

1
assert 3 > 7
2

3

AssertionError

循环语句

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

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

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

【例子】

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

你太了解小姐姐的心思了!

哼,猜对也没有奖励!

游戏结束,不玩儿啦!
【例子】布尔表达式返回0,循环终止。

1
string = ‘abcd’
2
while string:
3
print(string)
4
string = string[1:]
5

6

abcd

7

bcd

8

cd

9

d

abcd

bcd

cd

d
2. while - else 循环
while 布尔表达式:
代码块
else:
代码块
当while循环正常执行完的情况下,执行else输出,如果while循环中执行了跳出循环的语句,比如 break,将不执行else代码块的内容。

【例子】

print("%d is not 

1
count = 0
2
while count < 5:
3
print("%d is less than 5" % count)
4
count = count + 1
5
else:
6
print("%d is not less than 5" % count)
7

8

0 is less than 5

9

1 is less than 5

10

2 is less than 5

11

3 is less than 5

12

4 is less than 5

13

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
【例子】

1
count = 0
2
while count < 5:
3
print("%d is less than 5" % count)
4
count = 6
5
break
6
else:
7
print("%d is not less than 5" % count)
8

9

0 is less than 5

0 is less than 5
3. for 循环
for循环是迭代循环,在Python中相当于一个通用的序列迭代器,可以遍历任何有序序列,如str、list、tuple等,也可以遍历任何可迭代对象,如dict。

for 迭代变量 in 可迭代对象:
代码块
每次循环,迭代变量被设置为可迭代对象的当前元素,提供给代码块使用。

【例子】

1
for i in ‘ILoveLSGO’:
2
print(i, end=’ ') # 不换行输出
3

4

I L o v e L S G O

I L o v e L S G O
【例子】

1
member = [‘张三’, ‘李四’, ‘刘德华’, ‘刘六’, ‘周润发’]
2
for each in member:
3
print(each)
4

5

张三

6

李四

7

刘德华

8

刘六

9

周润发

10

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

14

张三

15

李四

16

刘德华

17

刘六

18

周润发

张三

李四

刘德华

刘六

周润发

张三

李四

刘德华

刘六

周润发
【例子】

1
dic = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
2

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

6

a:1 b:2 c:3 d:4

a:1 b:2 c:3 d:4
【例子】

1
dic = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
2

3
for key in dic.keys():
4
print(key, end=’ ')
5

6

a b c d

a b c d
【例子】

1
dic = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
2

3
for value in dic.values():
4
print(value, end=’ ')
5

6

1 2 3 4

1 2 3 4
4. for - else 循环
for 迭代变量 in 可迭代对象:
代码块
else:
代码块
当for循环正常执行完的情况下,执行else输出,如果for循环中执行了跳出循环的语句,比如 break,将不执行else代码块的内容,与while - else语句一样。

【例子】

1
for num in range(10, 20): # 迭代 10 到 20 之间的数字
2
for i in range(2, num): # 根据因子迭代
3
if num % i == 0: # 确定第一个因子
4
j = num / i # 计算第二个因子
5
print(’%d 等于 %d * %d’ % (num, i, j))
6
break # 跳出当前循环
7
else: # 循环的 else 部分
8
print(num, ‘是一个质数’)
9

10

10 等于 2 * 5

11

11 是一个质数

12

12 等于 2 * 6

13

13 是一个质数

14

14 等于 2 * 7

15

15 等于 3 * 5

16

16 等于 2 * 8

17

17 是一个质数

18

18 等于 2 * 9

19

19 是一个质数

10 等于 2 * 5

11 是一个质数

12 等于 2 * 6

13 是一个质数

14 等于 2 * 7

15 等于 3 * 5

16 等于 2 * 8

17 是一个质数

18 等于 2 * 9

19 是一个质数
5. range() 函数
range([start,] stop[, step=1])
这个BIF(Built-in functions)有三个参数,其中用中括号括起来的两个表示这两个参数是可选的。
step=1 表示第三个参数的默认值是1。
range 这个BIF的作用是生成一个从start参数的值开始到stop参数的值结束的数字序列,该序列包含start的值但不包含stop的值。
【例子】

1
for i in range(2, 9): # 不包含9
2
print(i)
3

4

2

5

3

6

4

7

5

8

6

9

7

10

8

2

3

4

5

6

7

8
【例子】

1
for i in range(1, 10, 2):
2
print(i)
3

4

1

5

3

6

5

7

7

8

9

1

3

5

7

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

1
seasons = [‘Spring’, ‘Summer’, ‘Fall’, ‘Winter’]
2
lst = list(enumerate(seasons))
3
print(lst)
4

[(0, ‘Spring’), (1, ‘Summer’), (2, ‘Fall’), (3, ‘Winter’)]

5
lst = list(enumerate(seasons, start=1)) # 下标从 1 开始
6
print(lst)
7

[(1, ‘Spring’), (2, ‘Summer’), (3, ‘Fall’), (4, ‘Winter’)]

[(0, ‘Spring’), (1, ‘Summer’), (2, ‘Fall’), (3, ‘Winter’)]

[(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。

【例子】

1
languages = [‘Python’, ‘R’, ‘Matlab’, ‘C++’]
2
for language in languages:
3
print(‘I love’, language)
4
print(‘Done!’)
5

I love Python

6

I love R

7

I love Matlab

8

I love C++

9

Done!

10

11

12
for i, language in enumerate(languages, 2):
13
print(i, ‘I love’, language)
14
print(‘Done!’)
15

2 I love Python

16

3 I love R

17

4 I love Matlab

18

5 I love C++

19

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!
7. break 语句
break语句可以跳出当前所在层的循环。

【例子】

1
import random
2
secret = random.randint(1, 10) #[1,10]之间的随机数
3

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

你太了解小姐姐的心思了!

哼,猜对也没有奖励!

游戏结束,不玩儿啦!
8. continue 语句
continue终止本轮循环并开始下一轮循环。
9.pass 语句
pass是空语句,不做任何操作,只起到占位的作用,其作用是为了保持程序结构的完整性。尽管pass语句不做任何操作,但如果暂时不确定要在一个位置放上什么样的代码,可以先放置一个pass语句,让代码可以正常运行。

异常处理

  1. try - except 语句
try:
    检测范围
except Exception[as reason]:
    出现异常后的处理代码
try 语句按照如下方式工作:

首先,执行try子句(在关键字try和关键字except之间的语句)
如果没有异常发生,忽略except子句,try子句执行后结束。
如果在执行try子句的过程中发生了异常,那么try子句余下的部分将被忽略。如果异常的类型和except之后的名称相符,那么对应的except子句将被执行。最后执行try - except语句之后的代码。
如果一个异常没有与任何的except匹配,那么这个异常将会传递给上层的try中。
一个try语句可能包含多个except子句,分别来处理不同的特定的异常。最多只有一个分支会被执行。
try-except-else语句尝试查询不在dict中的键值对,从而引发了异常。这一异常准确地说应属于KeyError,但由于KeyError是LookupError的子类,且将LookupError置于KeyError之前,因此程序优先执行该except代码块。所以,使用多个except代码块时,必须坚持对其规范排序,要从最具针对性的异常到最通用的异常。
2. try - except - finally 语句¶

try: 检测范围 
except Exception[as reason]: 出现异常后的处理代码 
finally: 无论如何都会被执行的代码

不管try子句里面有没有发生异常,finally子句都会执行。
Python入门(上)
简介

变量、运算符与数据类型

  1. 注释
  2. 运算符
  3. 变量和赋值
  4. 数据类型与转换
  5. print()函数

位运算

  1. 原码、反码和补码
  2. 按位运算
  3. 利用位运算实现快速计算
  4. 利用位运算实现整数集合

条件语句

  1. if 语句
  2. if - else 语句
  3. if - elif - else 语句
  4. assert 关键词

循环语句

  1. while 循环
  2. while - else 循环
  3. for 循环
  4. for - else 循环
  5. range() 函数
  6. enumerate()函数
  7. break 语句
  8. continue 语句
  9. pass 语句
  10. 推导式

异常处理

  1. Python 标准异常总结
  2. Python 标准警告总结
  3. try - except 语句
  4. try - except - finally 语句
  5. try - except - else 语句
  6. raise语句

简介
Python 是一种通用编程语言,其在科学计算和机器学习领域具有广泛的应用。如果我们打算利用 Python 来执行机器学习,那么对 Python 有一些基本的了解就是至关重要的。本 Python 入门系列体验就是为这样的初学者精心准备的。

天池官方为大家准备钉钉学习交流群,在学习过程中,大家有任何教程内容或者平台使用问题都可以在群内提出,扫码即可加入:

Image
本实验包括以下内容:

变量、运算符与数据类型
注释
运算符
变量和赋值
数据类型与转换
print() 函数
位运算
原码、反码和补码
按位非操作 ~
按位与操作 &
按位或操作 |
按位异或操作 ^
按位左移操作 <<
按位右移操作 >>
利用位运算实现快速计算
利用位运算实现整数集合
条件语句
if 语句
if - else 语句
if - elif - else 语句
assert 关键词
循环语句
while 循环
while - else 循环
for 循环
for - else 循环
range() 函数
enumerate()函数
break 语句
continue 语句
pass 语句
推导式
异常处理
Python 标准异常总结
Python 标准警告总结
try - except 语句
try - except - finally 语句
try - except - else 语句
raise语句
变量、运算符与数据类型

  1. 注释
    在 Python 中,# 表示注释,作用于整行。
    【例子】单行注释

1

这是一个注释

2
print(“Hello world”)
3

4

Hello world

Hello world
‘’’ ‘’’ 或者 “”" “”" 表示区间注释,在三引号之间的所有内容被注释
【例子】多行注释

1
‘’’
2
这是多行注释,用三个单引号
3
这是多行注释,用三个单引号
4
这是多行注释,用三个单引号
5
‘’’
6
print(“Hello china”)
7

Hello china

8

9
“”"
10
这是多行注释,用三个双引号
11
这是多行注释,用三个双引号
12
这是多行注释,用三个双引号
13
“”"
14
print(“hello china”)
15

hello china

Hello china

hello china
【我是测试题1】请在下方代码块中打印(print)出 hello+你的姓名
如:print(“hello 老表”)

1

写下你的答案

2

2. 运算符
算术运算符

操作符 名称 示例

  • 加 1 + 1
  • 减 2 - 1
  • 乘 3 * 4
    / 除 3 / 4
    // 整除(地板除) 3 // 4
    % 取余 3 % 4
    ** 幂 2 ** 3
    【例子】

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

1

12

0.75

0

3

8
比较运算符

操作符 名称 示例

大于 2 > 1
= 大于等于 2 >= 4
< 小于 1 < 2
<= 小于等于 5 <= 2
== 等于 3 == 4
!= 不等于 3 != 5
【例子】

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

False

True

False

False

True
逻辑运算符

操作符 名称 示例
and 与 (3 > 2) and (3 < 5)
or 或 (1 > 3) or (9 < 2)
not 非 not (2 > 1)
【例子】

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

False

False
位运算符

操作符 名称 示例
按位取反 ~4
& 按位与 4 & 5
按位或
^ 按位异或 4 ^ 5
<< 左移 4 << 2

右移 4 >> 2
【例子】有关二进制的运算,参见“位运算”部分的讲解。

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

0b101

-0b101 -5

0b100 4

0b101 5

0b1 1

0b10000 16

0b1 1
三元运算符

【例子】

1
x, y = 4, 5
2
if x < y:
3
small = x
4
else:
5
small = y
6

7
print(small) # 4
4
有了这个三元操作符的条件表达式,你可以使用一条语句来完成以上的条件判断和赋值操作。

【例子】

1
x, y = 4, 5
2
small = x if x < y else y
3
print(small) # 4
4
其他运算符

操作符 名称 示例
in 存在 ‘A’ in [‘A’, ‘B’, ‘C’]
not in 不存在 ‘h’ not in [‘A’, ‘B’, ‘C’]
is 是 “hello” is “hello”
not is 不是 “hello” is not “hello”
【例子】

1
letters = [‘A’, ‘B’, ‘C’]
2
if ‘A’ in letters:
3
print(‘A’ + ’ exists’)
4
if ‘h’ not in letters:
5
print(‘h’ + ’ not exists’)
6

7

A exists

8

h not exists

A exists

h not exists
【例子】比较的两个变量均指向不可变类型。

1
a = “hello”
2
b = “hello”
3
print(a is b, a == b) # True True
4
print(a is not b, a != b) # False False
True True

False False
【例子】比较的两个变量均指向可变类型。

1
a = [“hello”]
2
b = [“hello”]
3
print(a is b, a == b) # False True
4
print(a is not b, a != b) # True False
False True

True False
注意:

is, is not 对比的是两个变量的内存地址
==, != 对比的是两个变量的值
比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。
对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的。
运算符的优先级

运算符 描述
** 指数(最高优先级)
~± 按位翻转,一元加号和减号

  • / % // 乘,除,取模和取整除)
    • 加法减法

<< 右移,左移运算符
& 位‘AND’
^| 位运算符
<=<>>= 比较运算符
<>!= 等于运算符
=%=/=//=-=+
*= 赋值运算符
is is not 身份运算符
in not in 成员运算符
not and or 逻辑运算符
【例子】

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

0.1111111111111111

0

-12.5

True
【我是测试题2】下面这段代码的运行结果是什么?

1

运行一下结果就出来了

2
a = “hello”
3
b = “hello”
4
print(a is b, a == b)
3. 变量和赋值
在使用变量之前,需要对其先赋值。
变量名可以包括字母、数字、下划线、但变量名不能以数字开头。
Python 变量名是大小写敏感的,foo != Foo。
【例子】

1
teacher = “老马的程序人生”
2
print(teacher) # 老马的程序人生
老马的程序人生
【例子】

1
first = 2
2
second = 3
3
third = first + second
4
print(third) # 5
5
【例子】

1
myTeacher = “老马的程序人生”
2
yourTeacher = “小马的程序人生”
3
ourTeacher = myTeacher + ‘,’ + yourTeacher
4
print(ourTeacher) # 老马的程序人生,小马的程序人生
老马的程序人生,小马的程序人生
【我是测试题3】运行下面一段代码看看结果是什么?

1

运行一下就好啦

2
set_1 = {“欢迎”, “学习”,“Python”}
3
print(set_1.pop())
4. 数据类型与转换
类型 名称 示例
int 整型 <class ‘int’> -876, 10
float 浮点型<class ‘float’> 3.149, 11.11
bool 布尔型<class ‘bool’> True, False
整型

【例子】通过 print() 可看出 a 的值,以及类 (class) 是int。

1
a = 1031
2
print(a, type(a))
3

1031 <class ‘int’>

1031 <class ‘int’>
Python 里面万物皆对象(object),整型也不例外,只要是对象,就有相应的属性 (attributes) 和方法(methods)。

【例子】

1
b = dir(int)
2
print(b)
3

4

[‘abs’, ‘add’, ‘and’, ‘bool’, ‘ceil’, ‘class’,

5

delattr’, ‘dir’, ‘divmod’, ‘doc’, ‘eq’,

6

float’, ‘floor’, ‘floordiv’, ‘format’, ‘ge’,

7

getattribute’, ‘getnewargs’, ‘gt’, ‘hash’,

8

index’, ‘init’, ‘init_subclass’, ‘int’, ‘invert’,

9

le’, ‘lshift’, ‘lt’, ‘mod’, ‘mul’, ‘ne’,

10

neg’, ‘new’, ‘or’, ‘pos’, ‘pow’, ‘radd’,

11

rand’, ‘rdivmod’, ‘reduce’, ‘reduce_ex’, ‘repr’,

12

rfloordiv’, ‘rlshift’, ‘rmod’, ‘rmul’, ‘ror’,

13

round’, ‘rpow’, ‘rrshift’, ‘rshift’, ‘rsub’,

14

rtruediv’, ‘rxor’, ‘setattr’, ‘sizeof’, ‘str’,

15

sub’, ‘subclasshook’, ‘truediv’, ‘trunc’, ‘xor’,

16

‘bit_length’, ‘conjugate’, ‘denominator’, ‘from_bytes’, ‘imag’,

17

‘numerator’, ‘real’, ‘to_bytes’]

[‘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()的例子。

【例子】找到一个整数的二进制表示,再返回其长度。

1
a = 1031
2
print(bin(a)) # 0b10000000111
3
print(a.bit_length()) # 11
0b10000000111

11
浮点型

【例子】

1
print(1, type(1))
2

1 <class ‘int’>

3

4
print(1., type(1.))
5

1.0 <class ‘float’>

6

7
a = 0.00000023
8
b = 2.3e-7
9
print(a) # 2.3e-07
10
print(b) # 2.3e-07
1 <class ‘int’>

1.0 <class ‘float’>

2.3e-07

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

1
import decimal
2
from decimal import Decimal
Python 里面有很多用途广泛的包 (package),用什么你就引进 (import) 什么。包也是对象,也可以用上面提到的dir(decimal) 来看其属性和方法。

【例子】getcontext() 显示了 Decimal 对象的默认精度值是 28 位 (prec=28)。

1
a = decimal.getcontext()
2
print(a)
3

4

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,

5

capitals=1, clamp=0, flags=[],

6

traps=[InvalidOperation, DivisionByZero, Overflow])

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
1
b = Decimal(1) / Decimal(3)
2
print(b)
3

4

0.3333333333333333333333333333

0.3333333333333333333333333333
【例子】使 1/3 保留 4 位,用 getcontext().prec 来调整精度。

1
decimal.getcontext().prec = 4
2
c = Decimal(1) / Decimal(3)
3
print©
4

5

0.3333

0.3333
布尔型

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

【例子】

1
print(True + True) # 2
2
print(True + False) # 1
3
print(True * False) # 0
2

1

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

基本类型:整型、浮点型、布尔型
容器类型:字符串、元组、列表、字典和集合
【例子】bool 作用在基本类型变量:X 只要不是整型 0、浮点型 0.0,bool(X) 就是 True,其余就是 False。

1
print(type(0), bool(0), bool(1))
2

<class ‘int’> False True

3

4
print(type(10.31), bool(0.00), bool(10.31))
5

<class ‘float’> False True

6

7
print(type(True), bool(False), bool(True))
8

<class ‘bool’> False True

<class ‘int’> False True

<class ‘float’> False True

<class ‘bool’> False True
【例子】bool 作用在容器类型变量:X 只要不是空的变量,bool(X) 就是 True,其余就是 False。

1
print(type(’’), bool(’’), bool(‘python’))
2

<class ‘str’> False True

3

4
print(type(()), bool(()), bool((10,)))
5

<class ‘tuple’> False True

6

7
print(type([]), bool([]), bool([1, 2]))
8

<class ‘list’> False True

9

10
print(type({}), bool({}), bool({‘a’: 1, ‘b’: 2}))
11

<class ‘dict’> False True

12

13
print(type(set()), bool(set()), bool({1, 2}))
14

<class ‘set’> False True

<class ‘str’> False True

<class ‘tuple’> False True

<class ‘list’> False True

<class ‘dict’> False True

<class ‘set’> False True
确定bool(X) 的值是 True 还是 False,就看 X 是不是空,空的话就是 False,不空的话就是 True。

对于数值变量,0, 0.0 都可认为是空的。
对于容器变量,里面没元素就是空的。
获取类型信息

获取类型信息 type(object)
【例子】

1
print(isinstance(1, int)) # True
2
print(isinstance(5.2, float)) # True
3
print(isinstance(True, bool)) # True
4
print(isinstance(‘5.2’, str)) # True
True

True

True

True
注:

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

类型转换

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

1
print(int(‘520’)) # 520
2
print(int(520.52)) # 520
3
print(float(‘520.52’)) # 520.52
4
print(float(520)) # 520.0
5
print(str(10 + 10)) # 20
6
print(str(10.1 + 5.2)) # 15.3
520

520

520.52

520.0

20

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

1
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
2
print(“This is printed without 'end’and ‘sep’.”)
3
for item in shoplist:
4
print(item)
5

6

This is printed without 'end’and ‘sep’.

7

apple

8

mango

9

carrot

10

banana

This is printed without 'end’and ‘sep’.

apple

mango

carrot

banana
【例子】每次输出结束都用end设置的参数&结尾,并没有默认换行。

1
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
2
print(“This is printed with ‘end=’&’’.”)
3
for item in shoplist:
4
print(item, end=’&’)
5
print(‘hello world’)
6

7

This is printed with ‘end=’&’’.

8

apple&mango&carrot&banana&hello world

This is printed with ‘end=’&’’.

apple&mango&carrot&banana&hello world
【例子】item值与’another string’两个值之间用sep设置的参数&分割。由于end参数没有设置,因此默认是输出解释后换行,即end参数的默认值为\n。

1
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
2
print(“This is printed with ‘sep=’&’’.”)
3
for item in shoplist:
4
print(item, ‘another string’, sep=’&’)
5

6

This is printed with ‘sep=’&’’.

7

apple&another string

8

mango&another string

9

carrot&another string

10

banana&another string

This is printed with ‘sep=’&’’.

apple&another string

mango&another string

carrot&another string

banana&another string
位运算

  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表示负数。在位运算中符号位也参与运算。

  1. 按位运算
    按位非操作 ~
    ~ 1 = 0
    ~ 0 = 1
    ~ 把num的补码中的 0 和 1 全部取反(0 变为 1,1 变为 0)有符号整数的符号位在 ~ 运算中同样会取反。

00 00 01 01 -> 5
~

11 11 10 10 -> -6

11 11 10 11 -> -5
~

00 00 01 00 -> 4
按位与操作 &
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
只有两个对应位都为 1 时才为 1

00 00 01 01 -> 5
&
00 00 01 10 -> 6

00 00 01 00 -> 4
按位或操作 |
1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0
只要两个对应位中有一个 1 时就为 1

00 00 01 01 -> 5
|
00 00 01 10 -> 6

00 00 01 11 -> 7
按位异或操作 ^
1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
只有两个对应位不同时才为 1

00 00 01 01 -> 5
^
00 00 01 10 -> 6

00 00 00 11 -> 3
异或操作的性质:满足交换律和结合律

A: 00 00 11 00
B: 00 00 01 11

A^B: 00 00 10 11
B^A: 00 00 10 11

A^A: 00 00 00 00
A^0: 00 00 11 00

ABA: = AAB = B = 00 00 01 11
按位左移操作 <<
num << i 将num的二进制表示向左移动i位所得的值。

00 00 10 11 -> 11
11 << 3

01 01 10 00 -> 88
按位右移操作 >>
num >> i 将num的二进制表示向右移动i位所得的值。

00 00 10 11 -> 11
11 >> 2

00 00 00 10 -> 2
3. 利用位运算实现快速计算
通过 <<,>> 快速计算2的倍数问题。

n << 1 -> 计算 n2
n >> 1 -> 计算 n/2,负奇数的运算不可用
n << m -> 计算 n
(2^m),即乘以 2 的 m 次方
n >> m -> 计算 n/(2^m),即除以 2 的 m 次方
1 << n -> 2^n
通过 ^ 快速交换两个整数。 通过 ^ 快速交换两个整数。

a ^= b
b ^= a
a ^= b
通过 a & (-a) 快速获取a的最后为 1 位置的整数。

00 00 01 01 -> 5
&
11 11 10 11 -> -5

00 00 00 01 -> 1

00 00 11 10 -> 14
&
11 11 00 10 -> -14

00 00 00 10 -> 2
4. 利用位运算实现整数集合
一个数的二进制表示可以看作是一个集合(0 表示不在集合中,1 表示在集合中)。

比如集合 {1, 3, 4, 8},可以表示成 01 00 01 10 10 而对应的位运算也就可以看作是对集合进行的操作。

元素与集合的操作:

a | (1<<i) -> 把 i 插入到集合中
a & ~(1<<i) -> 把 i 从集合中删除
a & (1<<i) -> 判断 i 是否属于该集合(零不属于,非零属于)
集合之间的操作:

a 补 -> ~a
a 交 b -> a & b
a 并 b -> a | b
a 差 b -> a & (~b)
注意:整数在内存中是以补码的形式存在的,输出自然也是按照补码输出。

【例子】C#语言输出负数。

1
class Program
2
{
3
static void Main(string[] args)
4
{
5
string s1 = Convert.ToString(-3, 2);
6
Console.WriteLine(s1);
7
// 11111111111111111111111111111101
8

9
string s2 = Convert.ToString(-3, 16);
10
Console.WriteLine(s2);
11
// fffffffd
12
}
13
}
【例子】 Python 的bin() 输出。

1
print(bin(3)) # 0b11
2
print(bin(-3)) # -0b11
3

4
print(bin(-3 & 0xffffffff))
5

0b11111111111111111111111111111101

6

7
print(bin(0xfffffffd))
8

0b11111111111111111111111111111101

9

10
print(0xfffffffd) # 4294967293
0b11

-0b11

0b11111111111111111111111111111101

0b11111111111111111111111111111101

4294967293
是不是很颠覆认知,我们从结果可以看出:

Python中bin一个负数(十进制表示),输出的是它的原码的二进制表示加上个负号,巨坑。
Python中的整型是补码形式存储的。
Python中整型是不限制长度的不会超范围溢出。
所以为了获得负数(十进制表示)的补码,需要手动将其和十六进制数0xffffffff进行按位与操作,再交给bin()进行输出,得到的才是负数的补码表示。

条件语句

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

1
if 2 > 1 and not 2 > 3:
2
print(‘Correct Judgement!’)
3

4

Correct Judgement!

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

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

你太了解小姐姐的心思了!

哼,猜对也没有奖励!

游戏结束,不玩儿啦!
if语句支持嵌套,即在一个if语句中嵌入另一个if语句,从而构成不同层次的选择结构。

【例子】Python 使用缩进而不是大括号来标记代码块边界,因此要特别注意else的悬挂问题。

1
hi = 6
2
if hi > 2:
3
if hi > 7:
4
print(‘好棒!好棒!’)
5
else:
6
print(‘切~’)
7

8

无输出

【例子】

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

你太了解小姐姐的心思了!

哼,猜对也没有奖励!

游戏结束,不玩儿啦!
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,用来检查多个表达式是否为真,并在为真时执行特定代码块中的代码。
【例子】

1
temp = input(‘请输入成绩:’)
2
source = int(temp)
3
if 100 >= source >= 90:
4
print(‘A’)
5
elif 90 > source >= 80:
6
print(‘B’)
7
elif 80 > source >= 60:
8
print(‘C’)
9
elif 60 > source >= 0:
10
print(‘D’)
11
else:
12
print(‘输入错误!’)
请输入成绩:99

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

1
my_list = [‘lsgogroup’]
2
my_list.pop(0)
3
assert len(my_list) > 0
4

5

AssertionError

【例子】在进行单元测试时,可以用来在程序中置入检查点,只有条件为 True 才能让程序正常工作。

1
assert 3 > 7
2

3

AssertionError

循环语句

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

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

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

【例子】

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

你太了解小姐姐的心思了!

哼,猜对也没有奖励!

游戏结束,不玩儿啦!
【例子】布尔表达式返回0,循环终止。

1
string = ‘abcd’
2
while string:
3
print(string)
4
string = string[1:]
5

6

abcd

7

bcd

8

cd

9

d

abcd

bcd

cd

d
2. while - else 循环
while 布尔表达式:
代码块
else:
代码块
当while循环正常执行完的情况下,执行else输出,如果while循环中执行了跳出循环的语句,比如 break,将不执行else代码块的内容。

【例子】

print("%d is not 

1
count = 0
2
while count < 5:
3
print("%d is less than 5" % count)
4
count = count + 1
5
else:
6
print("%d is not less than 5" % count)
7

8

0 is less than 5

9

1 is less than 5

10

2 is less than 5

11

3 is less than 5

12

4 is less than 5

13

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
【例子】

1
count = 0
2
while count < 5:
3
print("%d is less than 5" % count)
4
count = 6
5
break
6
else:
7
print("%d is not less than 5" % count)
8

9

0 is less than 5

0 is less than 5
3. for 循环
for循环是迭代循环,在Python中相当于一个通用的序列迭代器,可以遍历任何有序序列,如str、list、tuple等,也可以遍历任何可迭代对象,如dict。

for 迭代变量 in 可迭代对象:
代码块
每次循环,迭代变量被设置为可迭代对象的当前元素,提供给代码块使用。

【例子】

1
for i in ‘ILoveLSGO’:
2
print(i, end=’ ') # 不换行输出
3

4

I L o v e L S G O

I L o v e L S G O
【例子】

1
member = [‘张三’, ‘李四’, ‘刘德华’, ‘刘六’, ‘周润发’]
2
for each in member:
3
print(each)
4

5

张三

6

李四

7

刘德华

8

刘六

9

周润发

10

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

14

张三

15

李四

16

刘德华

17

刘六

18

周润发

张三

李四

刘德华

刘六

周润发

张三

李四

刘德华

刘六

周润发
【例子】

1
dic = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
2

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

6

a:1 b:2 c:3 d:4

a:1 b:2 c:3 d:4
【例子】

1
dic = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
2

3
for key in dic.keys():
4
print(key, end=’ ')
5

6

a b c d

a b c d
【例子】

1
dic = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
2

3
for value in dic.values():
4
print(value, end=’ ')
5

6

1 2 3 4

1 2 3 4
4. for - else 循环
for 迭代变量 in 可迭代对象:
代码块
else:
代码块
当for循环正常执行完的情况下,执行else输出,如果for循环中执行了跳出循环的语句,比如 break,将不执行else代码块的内容,与while - else语句一样。

【例子】

1
for num in range(10, 20): # 迭代 10 到 20 之间的数字
2
for i in range(2, num): # 根据因子迭代
3
if num % i == 0: # 确定第一个因子
4
j = num / i # 计算第二个因子
5
print(’%d 等于 %d * %d’ % (num, i, j))
6
break # 跳出当前循环
7
else: # 循环的 else 部分
8
print(num, ‘是一个质数’)
9

10

10 等于 2 * 5

11

11 是一个质数

12

12 等于 2 * 6

13

13 是一个质数

14

14 等于 2 * 7

15

15 等于 3 * 5

16

16 等于 2 * 8

17

17 是一个质数

18

18 等于 2 * 9

19

19 是一个质数

10 等于 2 * 5

11 是一个质数

12 等于 2 * 6

13 是一个质数

14 等于 2 * 7

15 等于 3 * 5

16 等于 2 * 8

17 是一个质数

18 等于 2 * 9

19 是一个质数
5. range() 函数
range([start,] stop[, step=1])
这个BIF(Built-in functions)有三个参数,其中用中括号括起来的两个表示这两个参数是可选的。
step=1 表示第三个参数的默认值是1。
range 这个BIF的作用是生成一个从start参数的值开始到stop参数的值结束的数字序列,该序列包含start的值但不包含stop的值。
【例子】

1
for i in range(2, 9): # 不包含9
2
print(i)
3

4

2

5

3

6

4

7

5

8

6

9

7

10

8

2

3

4

5

6

7

8
【例子】

1
for i in range(1, 10, 2):
2
print(i)
3

4

1

5

3

6

5

7

7

8

9

1

3

5

7

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

1
seasons = [‘Spring’, ‘Summer’, ‘Fall’, ‘Winter’]
2
lst = list(enumerate(seasons))
3
print(lst)
4

[(0, ‘Spring’), (1, ‘Summer’), (2, ‘Fall’), (3, ‘Winter’)]

5
lst = list(enumerate(seasons, start=1)) # 下标从 1 开始
6
print(lst)
7

[(1, ‘Spring’), (2, ‘Summer’), (3, ‘Fall’), (4, ‘Winter’)]

[(0, ‘Spring’), (1, ‘Summer’), (2, ‘Fall’), (3, ‘Winter’)]

[(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。

【例子】

1
languages = [‘Python’, ‘R’, ‘Matlab’, ‘C++’]
2
for language in languages:
3
print(‘I love’, language)
4
print(‘Done!’)
5

I love Python

6

I love R

7

I love Matlab

8

I love C++

9

Done!

10

11

12
for i, language in enumerate(languages, 2):
13
print(i, ‘I love’, language)
14
print(‘Done!’)
15

2 I love Python

16

3 I love R

17

4 I love Matlab

18

5 I love C++

19

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!
7. break 语句
break语句可以跳出当前所在层的循环。

【例子】

1
import random
2
secret = random.randint(1, 10) #[1,10]之间的随机数
3

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

你太了解小姐姐的心思了!

哼,猜对也没有奖励!

游戏结束,不玩儿啦!
8. continue 语句
continue终止本轮循环并开始下一轮循环。

【例子】

1
for i in range(10):
2
if i % 2 != 0:
3
print(i)
4
continue
5
i += 2
6
print(i)
7

8

2

9

1

10

4

11

3

12

6

13

5

14

8

15

7

16

10

17

9

2

1

4

3

6

5

8

7

10

9
9. pass 语句
pass 语句的意思是“不做任何事”,如果你在需要有语句的地方不写任何语句,那么解释器会提示出错,而 pass 语句就是用来解决这些问题的。

【例子】

1
def a_func():
2

3

SyntaxError: unexpected EOF while parsing

【例子】

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

  1. 推导式
    列表推导式

[ expr for value in collection [if condition] ]
【例子】

1
x = [-4, -2, 0, 2, 4]
2
y = [a * 2 for a in x]
3
print(y)
4

[-8, -4, 0, 4, 8]

[-8, -4, 0, 4, 8]
【例子】

1
x = [i ** 2 for i in range(1, 10)]
2
print(x)
3

[1, 4, 9, 16, 25, 36, 49, 64, 81]

[1, 4, 9, 16, 25, 36, 49, 64, 81]
【例子】

1
x = [(i, i ** 2) for i in range(6)]
2
print(x)
3

4

[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
【例子】

1
x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0]
2
print(x)
3

4

[3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99]

[3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99]
【例子】

1
a = [(i, j) for i in range(0, 3) for j in range(0, 3)]
2
print(a)
3

4

[(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)]
【例子】

1
x = [[i, j] for i in range(0, 3) for j in range(0, 3)]
2
print(x)
3

[[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

4

5
x[0][0] = 10
6
print(x)
7

[[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]]
【例子】

1
a = [(i, j) for i in range(0, 3) if i < 1 for j in range(0, 3) if j > 1]
2
print(a)
3

4

[(0, 2)]

[(0, 2)]
元组推导式

( expr for value in collection [if condition] )
【例子】

1
a = (x for x in range(10))
2
print(a)
3

4

<generator object at 0x0000025BE511CC48>

5

6
print(tuple(a))
7

8

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

<generator object at 0x0000014CEC2E28B8>

(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
字典推导式

{ key_expr: value_expr for value in collection [if condition] }
【例子】

1
b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0}
2
print(b)
3

{0: True, 3: False, 6: True, 9: False}

{0: True, 3: False, 6: True, 9: False}
集合推导式

{ expr for value in collection [if condition] }
【例子】

1
c = {i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}
2
print©
3

{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.
【例子】

1
e = (i for i in range(10))
2
print(e)
3

<generator object at 0x0000007A0B8D01B0>

4

5
print(next(e)) # 0
6
print(next(e)) # 1
7

8
for each in e:
9
print(each, end=’ ')
10

11

2 3 4 5 6 7 8 9

<generator object at 0x0000014CEC389C78>

0

1

2 3 4 5 6 7 8 9
【例子】

1
s = sum([i for i in range(101)])
2
print(s) # 5050
3
s = sum((i for i in range(101)))
4
print(s) # 5050
5050

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

  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异常体系中的部分关系如下所示:

Image

  1. Python标准警告总结
    Warning:警告的基类
    DeprecationWarning:关于被弃用的特征的警告
    FutureWarning:关于构造将来语义会有改变的警告
    UserWarning:用户代码生成的警告
    PendingDeprecationWarning:关于特性将会被废弃的警告
    RuntimeWarning:可疑的运行时行为(runtime behavior)的警告
    SyntaxWarning:可疑语法的警告
    ImportWarning:用于在导入模块过程中触发的警告
    UnicodeWarning:与Unicode相关的警告
    BytesWarning:与字节或字节码相关的警告
    ResourceWarning:与资源使用相关的警告
  2. try - except 语句
    try:
    检测范围
    except Exception[as reason]:
    出现异常后的处理代码
    try 语句按照如下方式工作:

首先,执行try子句(在关键字try和关键字except之间的语句)
如果没有异常发生,忽略except子句,try子句执行后结束。
如果在执行try子句的过程中发生了异常,那么try子句余下的部分将被忽略。如果异常的类型和except之后的名称相符,那么对应的except子句将被执行。最后执行try - except语句之后的代码。
如果一个异常没有与任何的except匹配,那么这个异常将会传递给上层的try中。

  1. try - except - finally 语句
    try: 检测范围 except Exception[as reason]: 出现异常后的处理代码 finally: 无论如何都会被执行的代码

不管try子句里面有没有发生异常,finally子句都会执行。

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

try:
    检测范围
except:
    出现异常后的处理代码
else:
    如果没有异常执行这块代码

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

try: 检测范围 except(Exception1[, Exception2[,…ExceptionN]]]): 发生以上多个异常中的一个,执行这块代码 else: 如果没有异常执行这块代码
6. raise语句
Python 使用raise语句抛出一个指定的异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值