0%

[DSU&阿里云天池] Python训练营 Task 1

[TOC]
今天参加了由阿里云天池开展的 Python 训练营,借这个机会回顾一下 Python 的基础知识,并深入一些以前没有注意到的点。本文为 task 1。

变量、运算符与数据类型

注释

单行注释

# 表示其后面的整行内容为注释,后面的所有文字会被忽略。

1
2
3
# 这是一个注释
print('Hello Word!') # '#'也可以放在一条代码的后面
Hello Word!

多行注释

使用 ''' ''''""" """ 表示多行注释,在三个引号内的内容为注释。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
'''
这是多行注释,用三个单引号
这是多行注释,用三个单引号
这是多行注释,用三个单引号
'''
print('Hello China')
# Hello China

"""
这是多行注释,用三个双引号
这是多行注释,用三个双引号
这是多行注释,用三个双引号
"""
print('Hello China')
# Hello China

运算符

算术运算符

算术运算符有 +(加),-(减),*(乘),/(除),//(除取整),%(除取余)和 **(幂次)。

1
2
3
4
5
6
7
print(1 + 2) # 3
print(4 - 3) # 1
print(5 * 6) # 30
print(7 / 8) # 0.875
print(9 // 10) # 0,因为 9 不够 1 个 10
print(1 % 2) # 1,因为 1 除以 2 余 1
print(3 ** 4) # 81,因为 3 的 4 次幂是 81

相除取整和相除取余在涉及到负数的时候变得复杂,详情请见这里

赋值运算符

赋值运算符为算术运算符后面加个 =,在进行运算以后将新值赋给原变量,即为原地操作(in-place)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
a = 1
b = 2

a = a + b # 现在 a 的值为 3
a += b # 新的值被原地赋给了 a

c = 3
c += 1 # 4
c -= 2 # 2
c *= 3 # 6
c /= 4 # 1.5

d = 4
d **= 2 # 16
d //= 3 # 5
d %= 4 = 1

比较运算符

比较运算符有 >(大于),<(小于),>=(大于等于),<=(小于等于),==(等于)和 !=(不等于),返回 TrueFalse

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

逻辑运算符

逻辑运算符有 and(和、与),or(或)和 not(非)。

1
2
3
4
print(True) # True
print(True and False) # False
print(True or False) # True
print(not True) # False

只有 and 两边同时为真才返回 True, 取余情况返回 False;只有 or 两边同时为假才返回 False,取余情况返回 Truenot 返回与原判断结果相反的结果。

其它操作符

is(是),in(存在)

1
2
1 in [1, 2, 3] # true
'd' in 'abc' # False

is== 的区别

  • is, is not 对比的是两个变量的内存地址
  • ==, != 对比的是两个变量的值
  • 比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。
  • 对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的。
    1
    2
    3
    4
    5
    6
    7
    a, b = 'abc', 'abc'
    print(a is b, a == b) # True True
    print(a is not b, a != b) # False False

    a, b = ['abc'], ['abc']
    print(a is b, a == b) # False True
    print(a is not b, a != b) # True False

    运算符的优先级

    不同运算符的优先度不同,优先级从高到低为:
    ** > *, /, %, // > +- > & > >, >=, <, <= > ==, != > =, +=, -=, *=, /=, %=, //= > is, not is > in, not in > and, or, not

    变量与赋值

  1. 在使用变量之前,需要对其先赋值。
  2. 变量名可以包括字母、数字、下划线、但变量名不能以数字开头。
  3. Python 变量名是大小写敏感的,foo != Foo。
  4. 同一行可以赋值多个变量,如 a, b = 1, 2ab 分别赋予了 1 和 2。
    1
    2
    3
    a, b = 1, 2
    c = a + b
    print(c) # 3

    数据类型与转换

    常见的数据类型有:str(字符),int(整型),float(浮点型)和 bool(布尔型)。布尔变量只能是 TrueFalse。除了直接给变量赋予 TrueFalse 也可以用 bool(X) 让 Python 自行判断,X 可以是一个值(整型,浮点型或布尔型)也可以是一个容器(字符串,列表,元组,集合或字典),判断依据是:
  5. 对于数值,0 为 False,非 0 为 True
  6. 对于容器,空容器为 False,非空容器为 True
    1
    2
    3
    4
    5
    6
    7
    8
    9
    print(bool(False), bool(True)) # False, True
    print(bool(0), bool(1)) # False, True
    print(bool(0.0), bool(1.5)) # False, True

    print(bool(''), bool('abc')) # False, True
    print(bool([]), bool([1, 2])) # False, True
    print(bool(()), bool((1, 2))) # False, True
    print(bool({}), bool({1, 2})) # False, True
    print(bool({}), bool({'a':1})) # False, True

获取类型信息

  • type(X):返回 X 的类型信息
  • isinstance(var, type):返回 var 是不是 type
    1
    2
    3
    4
    5
    print(type(1)) # <class 'int'>
    print(type([1, 2])) # <class 'list'>

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

常用的变量为 sepend

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 修改 sep 变量
print('apple', 'banana') # sep = ' '
# apple banana
print('apple', 'banana', sep='&') # apple 和 banana 之间用 & 分隔
# apple&banana

# 修改 end 变量
fruits = ['apple', 'banana']
print("This is printed with default end")
for item in fruits:
print(item)
# This is printed with default end
# apple
# fruit

print("This is printed with 'end='&''")
for item in fruits:
print(item, end='&')
# This is printed with 'end='&''
apple&banana&

条件语句

if 语句

1
2
if expression:
exp_true_action

如果 expression 为真,则执行 exp_true_action;否则不会执行。expression 可为多重条件判断。

1
2
3
if 2 > 1 and not 2 > 3:
print('Correct!')
# Correct!

if-else 语句

1
2
3
4
if expression:
exp_true_action
else:
exp_false_action

如果 expression 为真,则执行 exp_true_action;否则执行 exp_false_action

1
2
3
4
5
6
color = 'red'
if color == 'blue':
print('Color is blue.')
else:
print('Color is not blue.')
# Color is not blue.

if-elif-else 语句

1
2
3
4
5
6
7
8
9
10
if expression1:
exp1_true_action
elif expression2:
exp2_true_action
.
.
elif expressionN:
expN_true_action
else:
exp_false_action

分别判断哪一个 expression 为真,哪个为真就执行哪个动作;全为假则执行 exp_false_action

1
2
3
4
5
6
7
8
number = 5
if number < 3:
print('Number is smaller than 3.')
elif number < 7:
print('Number is between 3 and 7.')
else:
print('Number is greater than 7.')
# Number is between 3 and 7.

assert 语句

1
assert expression, text

如果 expression 为假,则中断程序运行,抛出 AssertionError 异常,异常信息为 text

循环语句

while 循环

1
2
while expression:
action

如果 expression 为真,则执行 action,然后再判断 expression 是否为真,若还为真则再执行 action,再判断 expression 是否为真,…,直到 expression 为假,循环结束。

1
2
3
4
5
6
i = 0
while i < 2:
print(i)
i += 1
# 0
# 1

while-else 循环

while 循环正常执行完的情况下,执行 else 输出,如果 while 循环中执行了跳出循环的语句,比如 break,将不执行 else 代码块的内容。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
count = 0
while count <5:
print(f'{count} is less than 5')
count += 1
else:
print(f'{count} is not less than 5')
# count is less than 5
# count is less than 5
# count is less than 5
# count is less than 5
# count is less than 5
# count is not less than 5
count = 0
while count < 5:
print(f'{count} is less than 5')
count = 6
break
else:
print(f'count is not less than 5')
# 0 is less than 5

for 循环

1
2
for 迭代变量 in 迭代器:
action

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

1
2
3
4
5
for s in 'abc':
print(s)
# a
# b
# c

for-else 循环

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for i in range(2):
print(i)
else:
print('done')
# 0
# 1
# done
for i in range(2):
if i % 2 == 1:
break
print(i)
else:
print('done')
# 0

range 函数

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

range 这个内置函数的作用是生成一个从 start 参数的值开始到 stop参数的值结束的数字序列,该序列包含 start 的值但不包含 stop 的值。

1
2
3
4
for i in range(1, 5, 2):
print(i)
# 1
# 3

enumerate 函数

1
enumerate(sequence, [start=0])

返回枚举对象,可与 for 循环连用。

1
2
3
4
5
6
7
8
9
10
letters = ['a', 'b', 'c', 'd']
lst = list(enumerate(letters))
print(lst)
# [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
for idx, letter in enumerate(letters, 1):
print(idx, letter)
# 1 a
# 2 b
# 3 c
# 4 d

break 语句

break 语句可以跳出当前所在层的循环,例子见上。

continue 语句

continue 终止本轮循环并开始下一轮循环。

1
2
3
4
5
for i in range(3):
if not i % 2:
continue
print(i)
# 1

pass 语句

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

1
2
3
4
5
6
7
for i in range(3):
if not i % 2:
pass
print(i)
# 0
# 1
# 2

解析式

列表解析式

1
[expr for val in iterable [if condition]]

返回一个根据解析式条件创建的列表。

1
2
[i for i in range(5) if i % 2 == 1]
# [1 ,3]

字典解析式

类似列表解析式,只是变量为键值对。

1
2
{i:j for i, j in enumerate('abcde')}
# {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}

集合解析式

类似列表解析式。

1
2
{i for i in range(5) if i % 2 == 1}
# {1, 3}

生成式

类似列表解析式,只是返回一个迭代器对象。

1
2
(i for i in range(3) if i % 2 == 1)
# <generator object <genexpr> at 0x7fc3aad2b2d0>

iternext

iter 将一个可迭代对象转换为一个迭代器,可以使用 next 进行遍历。遍历结束以后若继续迭代,则抛出 StopIteration 异常。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
iterator = iter(list(range(3)))
print(iterator)
<list_iterator object at 0x7fc3aa756990>
next(iterator)
# 0
next(iterator)
# 1
next(iterator)
# 2
next(iterator)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-74-4ce711c44abc> in <module>
----> 1 next(iterator)

StopIteration:

异常处理

Python 常用标准异常

  • AssertionError:Assertion 的条件为 False
  • AttributeError:尝试访问未知的对象属性
  • IndexError:索引超出序列的范围
  • KeyError:字典中查找一个不存在的关键字
  • NameError:尝试访问一个不存在的变量
  • TypeError:不同类型间的无效操作
  • ValueError:传入无效的参数

    try-except 语句

    1
    2
    3
    4
    try:
    expression
    except Exception[ as reason]:
    action
    try 语句按照如下方式工作:
  • 首先,执行 try 子句(在关键字 try 和关键字 except 之间的语句)
  • 如果没有异常发生,忽略 except 子句,try 子句执行后结束。
  • 如果在执行 try 子句的过程中发生了异常,那么 try 子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符,那么对应的 except 子句将被执行。最后执行try - except 语句之后的代码。
  • 如果一个异常没有与任何的 except 匹配,那么这个异常将会传递给上层的 try 中。
  • 一个 try 语句可能包含多个 except 子句,分别来处理不同的特定的异常。最多只有一个分支会被执行。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    try:
    int("abc")
    s = 1 + '1'
    f = open('test.txt')
    print(f.read())
    f.close()
    except OSError as error:
    print('打开文件出错\n原因是:' + str(error))
    except TypeError as error:
    print('类型出错\n原因是:' + str(error))
    except ValueError as error:
    print('数值出错\n原因是:' + str(error))

    # 数值出错
    # 原因是:invalid literal for int() with base 10: 'abc'

    try-except-finally 语句

    1
    2
    3
    4
    5
    6
    try:
    检测范围
    except Exception[as reason]:
    出现异常后的处理代码
    finally:
    无论如何都会被执行的代码
    不管try子句里面有没有发生异常,finally子句都会执行。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    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 Traceback (most recent call last)
    <ipython-input-79-16805cf48925> in <module>
    15 # division by zero!
    16 # executing finally clause
    ---> 17 divide("2", "1")
    18 # executing finally clause
    19 # TypeError: unsupported operand type(s) for /: 'str' and 'str'

    <ipython-input-79-16805cf48925> in divide(x, y)
    1 def divide(x, y):
    2 try:
    ----> 3 result = x / y
    4 print("result is", result)
    5 except ZeroDivisionError:

    TypeError: unsupported operand type(s) for /: 'str' and 'str'

    try-except-else 语句

    1
    2
    3
    4
    5
    6
    try:
    检测范围
    except:
    出现异常后的处理代码
    else:
    如果没有异常执行这块代码
    如果 except语句没有执行,则继续执行 else 语句;若执行则跳过 else 语句。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    dict1 = {'a': 1, 'b': 2, 'v': 22}
    try:
    x = dict1['y']
    except KeyError:
    print('键错误')
    except LookupError:
    print('查询错误')
    else:
    print(x)
    # 键错误
    dict1 = {'a': 1, 'b': 2, 'v': 22}
    try:
    x = dict1['a']
    except KeyError:
    print('键错误')
    except LookupError:
    print('查询错误')
    else:
    print(x)
    # 1

    raise 语句

    抛出一个错误异常。
    1
    2
    3
    4
    5
    6
    7
    raise NameError()
    ---------------------------------------------------------------------------
    NameError Traceback (most recent call last)
    <ipython-input-80-1d90210dd9ab> in <module>
    ----> 1 raise NameError()

    NameError:

欢迎关注我的其它发布渠道