Python 自学笔记

ch2.py

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# 基础

# title()把字符串中所有单词的首字母转为大写
# istitle()检查字符串中所有单词的首字母是否为大写,且其他字母为小写
name = "roach lin"
print(name)
print(name.istitle())
name = name.title()
print(name)
print(name.istitle())
# 注意,非字母后的第一个字母将转为大写字母
# 该算法使用一种简单的与语言无关的定义,将连续的字母组合视为单词
txt = "hello b2b2b2 and 3g3g3g"
print(txt.title())
# upper()把字符串中所有小写字母转为大写
# isupper()检查字符串中所有字母是否为大写
name = name.upper()
print(name)
print(name.isupper())
# lower()把字符串中所有大写字母转为小写
# islower()检查字符串中所有字母是否为小写
name = name.lower()
print(name)
print(name.islower())

# 字符串拼接
print("roach" + " " + "lin")

# 输出制表符(tab)
print("python\tpython")
# 输出换行符
print("python\npython")

# strip()移除字符串头尾指定的字符(默认为空格)
# lstrip()只移除字符串头处,rstrip()只移除字符串尾处
# 注意,该方法只能删除开头或结尾的字符,不能删除中间的字符
print(' spacious '.strip())
# 把参数看作一个列表,从头/尾开始逐一删除符合列表的字符,直到遇到一个不在列表中的字符为止
print('www.example.com'.strip('cmowz.'))

# 乘方
print(10 ** 6)

# str()转为字符串

# 单行注释
'''
多行注释1
多行注释2
'''
"""
多行注释3
多行注释4
"""

# Python之禅
import this

ch3.py

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# 列表
# 可以把任何东西放入列表中,列表元素之间可以没有任何关系

# 查
net = ['google', 'baidu', 'tencent', 'netease']
print(net)
print(net[0])
# 索引为-1返回最后一个元素,索引为-2返回倒数第二个元素,依此类推,在不知道列表长度时很有用
print(net[-1])

# 改
net[1] = 'riot'
print(net)

# 增
# 使用append()在列表末尾添加元素
net.append('CDPR')
print(net)
# 使用insert()在列表中插入元素
net.insert(1, 'bilibili') # 尤其小心索引位置
print(net)

# 删
# 使用del删除元素
del net[4]
print(net)
# 使用pop()删除元素并存到新变量中,参数为空则默认删除最后一个
other1 = net.pop()
print(net)
print(other1)
other2 = net.pop(1)
print(net)
print(other2)
# 使用remove()根据值删除元素
# 注意,remove()只移除列表中某个值的第一个匹配项
net.remove('tencent')
print(net)

# 排序
# 使用sort()对列表进行永久性排序
net = ['google', 'baidu', 'tencent', 'netease', 'bilibili', 'acfun', 'riot']
net.sort()
print(net)
# 参数reverse为空默认是按字母顺序排列,反序排列要指定reverse为True
net = ['google', 'baidu', 'tencent', 'netease', 'bilibili', 'acfun', 'riot']
net.sort(reverse=True)
print(net)


# 参数key指定一个函数,表示按列表元素中的哪一个部分进行排列
def second(elem):
return elem[1]


tmp = [(5, 2), (6, 4), (7, 1), (8, 3)]
tmp.sort(key=second)
print(tmp)

# key还可以是匿名函数
'''
python使用lambda来创建匿名函数。
lambda只是一个表达式,函数体比def简单很多。
lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。
lambda函数拥有自己的命名空间,且不能访问自有参数列表之外或全局命名空间里的参数。
虽然lambda函数看起来只能写一行,却不等同于C或C++的内联函数,后者的目的是调用小函数时不占用栈内存从而增加运行效率。
lambda函数的语法只包含一个语句:lambda [arg1 [,arg2,.....argn]]:expression
例子如下:
sum = lambda arg1, arg2: arg1 + arg2
print(sum(10, 20))
'''
example_list = [5, 0, 6, 1, 2, 7, 3, 4]
example_list.sort(key=lambda x: x * -1)
print(example_list)

# 使用sorted()对列表进行临时排序
# 这会让列表按特定顺序显示,但不会改变列表的原始顺序
net = ['google', 'baidu', 'tencent', 'netease', 'bilibili', 'acfun', 'riot']
print(sorted(net))
print(net)
# sorted()同样有参数reverse和key,用法与上面完全相同

# 使用reverse()反转列表的顺序
# 注意,reverse()不是指按与字母顺序相反的顺序进行排列,而是单纯地反转列表顺序,无论列表是否有序
# reverse()永久性地修改了列表的排列顺序,但可再次使用reverse()恢复到原来的状态
net.reverse()
print(net)

# 确定列表的长度
print(len(net))

ch4.py

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# 操作列表(循环)
nets = ['google', 'bilibili', 'acfun', 'riot']
for net in nets:
print(net)
# break
# continue

# 若for循环正常结束(有continue也可),则运行else语句
# 若for循环被break打断,则不运行else语句
sites = ["Baidu", "Google", "Runoob", "Taobao"]
for site in sites:
if site == "Runoob":
print("菜鸟教程!")
break
print("循环数据 " + site)
else:
print("没有循环数据!")
print("完成循环!")

# 函数range()
for value in range(5): # 默认从0开始
print(value)

for value in range(1, 6): # 可以指定区间的值
print(value)

for value in range(1, 10, 2): # 可以指定步长
print(value)

for value in range(-10, -100, -10): # 区间从大到小、步长为负数也可
print(value)

# 使用range()创建列表
numbers = list(range(10))
print(numbers)

# 结合range()和len()函数以遍历列表
nets = ['google', 'bilibili', 'acfun', 'riot']
for net in range(len(nets)):
print(net, nets[net])

# 列表解析
squares = [value ** 2 for value in range(1, 11)]
print(squares)

# 对数字列表执行简单的统计计算
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits)) # 最小值
print(max(digits)) # 最大值
print(sum(digits)) # 求和

# pass是空语句,不做任何事情,一般用作占位语句,是为了保持程序结构的完整性。

# 使用列表的一部分(切片)
nets = ['google', 'bilibili', 'acfun', 'riot', 'cygames', 'can-dao']
print(nets[1:4]) # 生成子集
print(nets[:4]) # 若没有指定起始索引,则自动从列表开头开始
print(nets[1:]) # 若没有指定终止索引,则一直到列表末尾为止
print(nets[1:5:2]) # 也可指定步长
print(nets[-3:]) # 负数(代表从列表末尾开始计算距离)同样适用

# 复制列表
nets1 = ['google', 'bilibili', 'acfun']
nets2 = nets1 # 这是不行的,实际上nets1和nets2指向同一个列表
nets1.append('riot')
nets2.append('cygames')
print(nets1)
print(nets2)

nets1 = ['google', 'bilibili', 'acfun']
nets3 = nets1[:]
nets1.append('riot')
nets3.append('cygames')
print(nets1)
print(nets3)

# 列表是可以修改的,而不可修改的列表称为元组
nets = ('google', 'bilibili', 'acfun')
print(nets)
# 元组的元素不能修改,但可以对元组变量重新赋值
nets = ('riot', 'cygames')
print(nets)

ch5.py

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
# if语句
age1 = 20
age2 = 22
if age1 >= 18 and age2 <= 25: # or类似
print(age1 + age2)

nets = ['google', 'bilibili', 'acfun', 'riot']
if 'google' in nets:
print('yes')
if 'baidu' not in nets:
print('not in')

age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
elif age >= 65: # 最后的else不是必要的
price = 5

# 当if+列表名时,若列表为空则返回false,否则返回true
requested = []
if requested:
print('not empty')

ch6.py

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# 字典(键值对)
# Python不关心键值对的添加顺序,而只关心键和值之间的关联关系

# 创建空字典
alien_1 = {}
# 定义一个字典
alien_0 = {'color': 'green', 'points': 5}
# 访问字典中的值
print(alien_0['color'])
# 添加键值对
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
# 修改字典中的值
alien_0['y_position'] = 100
print(alien_0)
# 删除键值对
del alien_0['y_position']
print(alien_0)

# 遍历字典
# 遍历所有键值对
user_0 = {
'username': 'qcym',
'first': 'roach',
'last': 'lin',
}
for key, value in user_0.items():
print('\nkey: ' + key)
print('value: ' + value)
print(user_0.items()) # items()以列表返回可遍历的(键,值)元组数组

# 遍历所有键
for key in user_0.keys():
print(key)
# 遍历字典时会默认遍历所有键
for key in user_0:
print(key)
# 可以用sorted()对键进行排序
for key in sorted(user_0.keys()):
print(key)

# 遍历所有值
for value in user_0.values():
print(value)
# 使用集合set()剔除重复项,set类似于列表,但每个元素必须是独一无二的
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for language in set(favorite_languages.values()):
print(language)

# 嵌套(将字典存储在列表中,将列表/字典作为值存储在字典中)

ch7.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 输入和while循环

# input()获取的输入是字符串,若要进行数值运算则要先用int()
message = input('Please input something: ')
print(message)

# 求模运算符(%)返回的是两数相除的余数

num = 1
while num <= 5:
print(num)
num += 1

# 设置标志变量flag

ch8.py

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# 函数

def greet(user): # 形参
print('Hello, ' + user)


greet('lin') # 实参

# 位置实参:实参的顺序与形参的顺序一一对应

# 关键字实参,实参顺序与形参顺序不必对应
greet(user='roach')


# 可以给形参指定默认值,若有实参则使用实参,若无实参则使用形参的默认值
# 使用默认值时,在形参列表中要先列出没有默认值的形参,这样才能正确解读位置实参


def repeat(user):
return user


print(repeat('lin'))


# 可选实参
def get_name(first, last, middle=''):
if middle:
name = first + ' ' + middle + ' ' + last
else:
name = first + ' ' + last
return name


print('roach', 'lin')
print('roach', 'qcym', 'lin')


# 禁止函数修改列表
# function_name(list_name[:])传递的是list_name的副本

# 传递任意数量的实参
def make_pizza(*topping): # 星号*的作用是创建空元组,并将接收到的任意数量的实参都封装到这个元组中
print(topping)


make_pizza('pepper')
make_pizza('mushroom', 'pepper', 'cheese')


# 使用任意数量的关键字实参
# 两个星号**的作用是创建空字典,并将接收到的所有键值对都封装到这个字典中
def build_profile(first, last, **user_info):
profile = {'first_name': first, 'last_name': last}
for key, value in user_info.items():
profile[key] = value
return profile


user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)

# 模块(扩展名为.py的文件)

# 需要指定module_name.function_name()
import time

start = time.perf_counter()
print(sum(range(10000000)))
end = time.perf_counter()
print((end - start), "s")

# 只要指定function_name()即可
from math import sqrt, pi

print(pi)
print(sqrt(16))

# 使用as指定别名
# 给函数指定别名:from module_name import function_name as fn
# 给模块指定别名:import module_name as mn

# 导入模块中的所有函数
# 注意,最好不要这样做,因为有可能会有同名函数
# from module_name import *

ch9.py

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# 类(面向对象编程)
# 实例化:基于类创建对象

# 创建类
class Dog:
def __init__(self, name, age): # 构造函数,初始化属性name和age
self.name = name
self.age = age

def sit(self): # 蹲下
print(self.name + ' is sitting')

def roll_over(self): # 打滚
print(self.name + ' rolled over')


# 根据类创建实例
my_dog = Dog('willie', 6)
# 访问属性
print("my dog's name is " + my_dog.name)
print('my dog is ' + str(my_dog.age) + ' years old')
# 调用方法
my_dog.sit()
my_dog.roll_over()


# 使用类和实例
# Car类
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer = 0
# 给属性指定默认值
# 类中的每个属性都必须有初始值,要么在创建实例时提供,要么在构造函数中设置默认值

def description(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name

def read_odometer(self):
print('this car has ' + str(self.odometer) + ' miles on it')

def update_odometer(self, mileage):
if mileage >= self.odometer: # 里程表不能往回拨
self.odometer = mileage
else:
print('can not roll back')

def increase_odometer(self, miles):
if miles >= 0: # 里程表不能往回拨
self.odometer += miles
else:
print('can not roll back')

def fill_gas_tank(self):
pass


my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.description())
my_new_car.read_odometer()

# 修改属性的值
# 直接修改属性的值
my_new_car.odometer = 23
my_new_car.read_odometer()
# 通过方法修改属性的值
my_new_car.update_odometer(25)
my_new_car.read_odometer()
my_new_car.update_odometer(20)
my_new_car.read_odometer()
# 通过方法对属性的值进行递增
my_new_car.increase_odometer(100)
my_new_car.read_odometer()
my_new_car.increase_odometer(-100)
my_new_car.read_odometer()


# 继承
# 子类继承了父类的所有属性和方法,同时还可以定义自己的属性和方法
# 子类的方法__init__()
class ElectricCar(Car): # 指定父类Car
def __init__(self, make, model, year):
super().__init__(make, model, year) # super()调用父类(超类superclass)的方法
self.battery_size = 70 # 给子类定义新属性

def read_battery(self): # 给子类定义新方法
print('this car has a ' + str(self.battery_size) + '-kWh battery')

def fill_gas_tank(self): # 重写父类的方法
print("this car doesn't need a gas tank")


my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.description())
my_tesla.read_battery()
my_tesla.fill_gas_tank()

# 导入类
# 从一个模块中导入多个类:from module_name import class_name1, class_name2, ......
# 导入整个模块:import module_name(使用时要指定module_name.class_name())
# 导入模块中所有类:from module_name import *(尽量不要用)
# 在一个模块中导入另一个模块:from module_name import class_name

# Python 标准库
# 哈哈,Python3.6后字典有序了,不需要from collections import OrderedDict了

ch9_1.py

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# Car类
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer = 0
# 给属性指定默认值
# 类中的每个属性都必须有初始值,要么在创建实例时提供,要么在构造函数中设置默认值

def description(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name

def read_odometer(self):
print('this car has ' + str(self.odometer) + ' miles on it')

def update_odometer(self, mileage):
if mileage >= self.odometer: # 里程表不能往回拨
self.odometer = mileage
else:
print('can not roll back')

def increase_odometer(self, miles):
if miles >= 0: # 里程表不能往回拨
self.odometer += miles
else:
print('can not roll back')

def fill_gas_tank(self):
pass


# 将实例用作属性
# 在不断给ElectricCar类添加细节时,其中可能会包含很多专门针对汽车电瓶的属性和方法,
# 所以我们可以将这些属性和方法提取出来,放到另一个名为Battery的类中,
# 并将一个Battery实例用作ElectricCar类的一个属性
class Battery:
def __init__(self, battery_size=70):
self.battery_size = battery_size

def read_battery(self):
print('this car has a ' + str(self.battery_size) + '-kWh battery')

def get_range(self):
drive_range = 0

if self.battery_size == 70:
drive_range = 240
elif self.battery_size == 85:
drive_range = 270

print('this car can go approximately ' + str(drive_range) + ' miles on a full charge')


class ElectricCar(Car): # 指定父类Car
def __init__(self, make, model, year):
super().__init__(make, model, year) # super()调用父类(超类superclass)的方法
self.battery = Battery()


my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.description())
my_tesla.battery.read_battery()
my_tesla.battery.get_range()

ch10.py

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# 文件和异常
# 函数open()返回一个表示文件的对象,Python将这个对象存储在我们将在后面使用的变量中
# 关键字with在不再需要访问文件后将其关闭,不需要调用close()
# 尽量不要单独使用open()和close(),而是用with open()代替
with open('pi_digits.txt') as file_object:
# read()读取文件的全部内容,并将其作为一个字符串存储在变量中
contents = file_object.read()
print(contents.rstrip()) # 使用rstrip()删除空行

# Python在Windows系统中表示文件路径,一是可以直接使用斜杠(/),比如'./test/1pi_digits.txt'
# 二是使用反斜杠(\)并在字符串前加r声明此字符串不要转义,
# 比如r'C:\Users\Administrator\Documents\GitHub\python-book\test\1pi_digits.txt'
with open('./test/1pi_digits.txt') as file_object:
print(file_object.read().rstrip())

with open(r'C:\Users\Administrator\Documents\GitHub\python-book\test\1pi_digits.txt') as file_object:
print(file_object.read().rstrip())

# 逐行读取
with open('pi_digits.txt') as file_object:
for line in file_object:
print(line.rstrip())

# 创建一个包含文件各行内容的列表
with open('pi_digits.txt') as file_object:
lines = file_object.readlines()

for line in lines:
print(line.rstrip())

# 使用文件的内容
with open('pi_digits.txt') as file_object:
lines = file_object.readlines()

pi_string = ''
for line in lines:
pi_string += line.strip()

print(pi_string)
print(len(pi_string))

# 包含一百万位的大型文件
with open('pi_million_digits.txt') as file_object:
lines = file_object.readlines()

pi_string = ''
for line in lines:
pi_string += line.strip()

print(pi_string[:52] + '...')
print(len(pi_string))

# 圆周率中包含你的生日吗
birthday = input('please enter your birthday, in the format of yymmdd: ')
if birthday in pi_string:
print('appear!')
else:
print('not appear!')

# 写入空文件
# 默认模式r(只读),全部模式参数:https://www.runoob.com/python3/python3-file-methods.html
with open('programming.txt', 'w') as file_object:
file_object.write('I love programming.\n')
file_object.write('I love creating new games.\n')

# 异常
# 处理ZeroDivisionError异常
# print(5/0)
# 使用try-except代码块
try:
print(5 / 0)
except ZeroDivisionError:
print("can't divide by zero")

# else代码块
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("First number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
if second_number == 'q':
break
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)

# 处理FileNotFoundError异常
'''
with open('alice.txt') as f_obj:
contents = f_obj.read()
'''

# 分析文本 & 使用多个文件
title = "Alice's Adventures in Wonderland"
print(title.split())


def count_words(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
print("sorry, the file " + filename + " doesn't exist")
else:
words = contents.split()
num_words = len(words)
print("the file " + filename + " has about " + str(num_words) + " words")


filename = 'alice.txt'
count_words(filename)

filenames = ['alice.txt', 'siddhartha.txt', 'moby_dict.txt', 'little_women.txt']
for filename in filenames:
count_words(filename)

# 存储数据
# JSON数据格式并非Python专用,这让你能够将以JSON格式存储的数据与使用其他编程语言的人分享,是一种轻便格式
# JSON(JavaScript Object Notation)格式最初是为JavaScript开发的,但随后成为了一种常见格式,被包括Python在内的众多语言所采用
'''
import json

numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj) # json.dump()写入数据
'''
import json

filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj) # json.load()读取数据
print(numbers)

# 保存和读取用户生成的数据
import json

filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input('what is your name? ')
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print('we will remember you when you come back, ' + username + '!')
else:
print('welcome back, ' + username + '!')

# 重构
import json


def get_stored_username():
"""Get stored username if available."""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username


def get_new_username():
"""Prompt for a new username."""
username = input("What is your name? ")
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
return username


def greet_user():
"""Greet the user by name."""
username = get_stored_username()
if username:
print("Welcome back, " + username + "!")
else:
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")


greet_user()

ch11.py

1
# 测试代码

project2.py

1
2
3
4
5
6
# 数据可视化
import matplotlib.pyplot as plt

squares = [1, 4, 9, 16, 25]
plt.plot(squares) # plot()绘制图形
plt.show() # show()打开matplotlib查看器,并显示绘制的图形

相关代码点此下载


Python 自学笔记
https://roachlin.github.io/2021-12-10-self-learn-python/
作者
RoachLin
发布于
2021年12月10日
许可协议