Python基础

Python(Hello World)

1.Python的安装与配置

#去Python官网下载你想要的Python版本
1.https://www.python.org/

#在系统中配置系统环境变量
变量名Path,变量值为你安装的Python的路径(我的是D:\Python32)

#安装第三方集成工具Pycharm(具体配置可自行百度)

2.Python起步

#认识print    ->   print()打印输出到屏幕
print("Hello world")

3.变量与数据类型

变量

message = "Hello Python!"
print(message)

#变量的命名和使用
1.变量只包含字母、数字、下划线,但不能以数字开头定义变量
2.变量名不能以空格分隔,以下划线为分割
3.变量名不能以函数名命名
4.变量名尽量简短且易理解
5.尽量以小写字母命名变量

#变量是标签,举个例子
message = "Hello world"
message = "Hello python"
print(message)
Hello python  #打印出的结果为Hello python

数据类型

1.字符串
#1.单引号('')和双引号(""),举个例子
message = "Good python"
message = 'Good python'


#2.使用修改字符串的大小写
1.title()	首字母大写
2.upper()	全大写
3.lower()	全小写

举个例子:
message = "Hello world"
print(message.title())
print(message.upper())
print(message.lower())

Hello World
HELLO WORLD
hello world


#3.在字符串中使用变量
first_name = "Fng"
last_name = "wming"
full_name = f"{first_name}{last_name}"
print(full_name)

Fngwming
#f字符串是3.6版本引入的,如果使用的是3.6之前的版本需要使用format()
#这样表示   print("{}{}".format(first_name,last_name))

使用制表符和换行符来添加空白

#制表符   (\t)
print("\tPython")
	Python

#换行符   (\n)
print("Languages:\nPython\nC\nJava")
Languages:
Python
C
Java

#混合使用
print("Languages:\n\tPython\n\tC\n\tJava")
Languages:
	Python
	C
	Java

删除空白

rstrip()	#剔除右边的空白
ltrip()		#剔除左边的空白
strip()		#剔除左边和右边所有的空白

#举个例子:
languages = " Python "
print(languages.rstrip())
print(languages.lstrip())
print(languages.strip())

 Python
Python 
Python

使用字符串时避免语法错误

message = 'Python's No.1'   #执行会语法报错,因为有三个单引号,Python不能识别
#修改
message = "Python's No.1"
2.数

#1 + 2       -->   得出来是整数

#1 + 1.5     -->   得出来是浮点数

#3 - 2       -->   得出来是整数

#3 - 1.5     -->   得出来是浮点数

#3 * 2     -->   得出来是整数

#3 * 0.2   -->   得出来是浮点数

#3 / 2     -->   得出来是浮点数(除法即使除数和被除数都为整数也为浮点数)

乘方运算

#2 ** 3     -->   得出来是整数

#2 ** 0.2   -->   得出来是浮点数

同一表达式中使用多种运算

#2 + (3 / 2)  --> 得出来是浮点数

浮点数

#0.1 + 0.1  (像0.1这种小数的称为浮点数)

#1 + 2.0

整数和浮点数

#4 / 2   -->2.0  除法得到的为浮点数

#1 + 2.0

#2 * 3.0

数中的下划线

这种方法使用于整数和浮点数,但只有Python3.6和更高版本支持,举个例子:

num1=14_00_00_200.0
print(num1)   #打印出来的结果为140000200 

同时给多个变量赋值

需要用逗号将变量名分开
只要变量和值的个数相同,Python就能正确地将他们关联起来,例如:
之前:
x=1
y=2
z=3
print(x,y,z)



改为:
x,y,z=1,2,3
print(x,y,z)

常量

常量类似于变量,但其值在整个生命周期内保持不变,Python没有内置的常量类型
但Python程序员会使用全大写来指出某个变量视为常量,其值应始终不变;
在代码中,要指出应将变量视为常量,可将其字母全部大写
类似这样:
MAX_CONNECTINS = 5000
print(MAX_CONNECTINS)

注释

在Python中,注释用井号(#),#后面的内容都会被Python解释器忽略

例如:
#定义常量
MAX_CONNECTINS = 5000

4.列表

什么是列表

languages = ["go", "python", "java", "c+"]
print(len(languages))
结果:   ['go', 'python', 'java', 'c+']

#遍历列表元素  (range()函数,左闭右开)
for i in range(0,len(languages)):
    print(languages[i])
    
#让他们的首字母大写
for i in range(0,len(languages)):
    print(languages[i].title())

索引从0开始而不是从1开始

languages = ["go", "python", "java", "c+"]

languages = ["go", "python", "java", "c+"]
print(languages[0])
print(languages[1])
结果为:
go
python

#注意的是:
languages = ["go", "python", "java", "c+"]
print(languages[-1])
print(languages[-2])

使用列表中得各个值

list = ["ok", "jing", "bicycle"]
full_name = f"My first {list[2].title()}"
print(full_name)
结果为:   My first Bicycle

修改列表元素

实例:    motorcycles = ["honda", "yamaha", "suzuki"]


#任务:将第一个元素的值改为"ducati"

motorcycles = ["honda", "yamaha", "suzuki"]
print(motorcycles)
motorcycles[0] = "ducati"
print(motorcycles)


#任务:在列表末尾添加元素,append
motorcycles.append("ming")
print(motorcycles)

#在列表中插入元素,insert
list_name.insert(__index索引值, __object元素)
motorcycles.insert(0, 'Fang')
print(motorcycles)
结果为:   ['Fang', 'honda', 'yamaha', 'suzuki', 'ming']


#从列表中删除元素
#1.del语句
del motorcycles[0]
print(motorcycles)

#2.使用pop()方法删除,   pop()作用,可以理解为将列表的最后一个元素弹了出来,默认为最后一个,也可以在pop(__index索引值),取到的就是该索引的元素
motorcycles = ["honda", "yamaha", "suzuki"]
test1 = motorcycles.pop()
test2 = motorcycles.pop(0)
print(test1)
print(test2)
------------
结果为:     -
suzuki     -
honda      -
------------


#3.根据值删除元素,这是在知道已有值得情况下进行删除,用remove
motorcycles = ["honda", "yamaha", "suzuki"]
motorcycles.remove("suzuki")
print(motorcycles)
#删除的一个缺点:如果列表中此值有多个,只能删除一个,全部删除需要配合循环

组织列表

1.使用sort()对列表永久排序

#按照字母顺序排列
cars = ["bmw", "audi", "toyota", "subaru"]
#源字母顺序
print(cars)
#按照字母顺序进行排序
cars.sort()
print(cars)
#按照字母反序进行排序
cars.sort(reverse=True)
print(cars)

2.使用函数sorted()对列表临时排序

cars = ["bmw", "audi", "toyota", "subaru"]
print(sorted(cars))
print(cars)
结果:
['audi', 'bmw', 'subaru', 'toyota']
['bmw', 'audi', 'toyota', 'subaru']

3.倒着打印列表,reverse()永久修改

#reverse()不是按照与字母顺序相反得顺序排序列表元素,而是反转列表元素的排列顺序
cars = ["bmw", "audi", "toyota", "subaru"]
print(cars)
cars.reverse()
print(cars)
结果为:
	['bmw', 'audi', 'toyota', 'subaru']	#源列表
	['subaru', 'toyota', 'audi', 'bmw']	#使用reverse()修改之后的列表

确定列表的长度

#确定列表的长度
cars = ["bmw", "audi", "toyota", "subaru"]
print(len(cars))

使用列表是时避免索引错误

IndexError: list index out of range

#使用列表时,避免索引错误
cars = ["bmw", "audi", "toyota", "subaru"]
print(cars[4])

所以在写之前应该len()一下确认列表长度
4.1遍历整个列表

1.遍历

任务:将名单上的每个名字打印出来
name=["alice", "xiaoming", "xiaoqian"]

#遍历列表
方法1:
name=["Alice", "Xiaoming", "Xiaoqian"]
for i in range(0,len(name)):
    print(name[i])
    
    
    
方法2:
for i in name:
    print(i)

2.在for循环中执行更多的操作

name=["alice", "xiaoming", "xiaoqian"]
任务打印出:
Alice,that was a great trick!
Xiaoming,that was a great trick!
Xiaoqian,that was a great trick!

#方法1:
name=["alice", "xiaoming", "xiaoqian"]
for i in range(0, len(name)):
    print(name[i].title(), ",that was a great trick!")
    
#方法2
for i in name:
    print(f"{i.title()},that was a great trick!")
    
    
    
    
#打印出如下:
Alice,that was a great trick!
I can't wait to see your trick,Alice.

Xiaoming,that was a great trick!
I can't wait to see your trick,Xiaoming.

Xiaoqian,that was a great trick!
I can't wait to see your trick,Xiaoqian.
#方法:
for i in name:
    print(f"{i.title()},that was a great trick!")
    print(f"I can't wait to see your trick,{i.title()}.\n")

在for循环结束后执行一些操作

任务:打印出如下
Alice,that was a great trick!
I can't wait to see your trick,Alice.

Xiaoming,that was a great trick!
I can't wait to see your trick,Xiaoming.

Xiaoqian,that was a great trick!
I can't wait to see your trick,Xiaoqian.

Thank you,everyone.That was a great magic show!

#方法:
for i in name:
    print(f"{i.title()},that was a great trick!")
    print(f"I can't wait to see your trick,{i.title()}.\n")
print("Thank you,everyone.That was a great magic show!")

4.2避免缩进错误

1.忘记缩进

#ERROR
for i in name:
print(f"{i.title()},that was a great trick!")
    print(f"I can't wait to see your trick,{i.title()}.\n")
    
#√:
for i in name:
    print(f"{i.title()},that was a great trick!")
    print(f"I can't wait to see your trick,{i.title()}.\n")

2.忘记缩进额外的代码行

任务:打印出如下
Alice,that was a great trick!
I can't wait to see your trick,Alice.

Xiaoming,that was a great trick!
I can't wait to see your trick,Xiaoming.

Xiaoqian,that was a great trick!
I can't wait to see your trick,Xiaoqian.

#ERROR:
for i in name:
    print(f"{i.title()},that was a great trick!")
print(f"I can't wait to see your trick,{i.title()}.\n")

#√:
for i in name:
    print(f"{i.title()},that was a great trick!")
	print(f"I can't wait to see your trick,{i.title()}.\n")
    

3.不必要的缩进

#ERROR
print("不必要的缩进")
message = "Hello,World!"
    print(message)
    
#√:
print("不必要的缩进")
message = "Hello,World!"
print(message)

4.循环后不必要的缩进

任务:打印出如下
Alice,that was a great trick!
I can't wait to see your trick,Alice.

Xiaoming,that was a great trick!
I can't wait to see your trick,Xiaoming.

Xiaoqian,that was a great trick!
I can't wait to see your trick,Xiaoqian.

Thank you,everyone.That was a great magic show!

#√:
for i in name:
    print(f"{i.title()},that was a great trick!")
    print(f"I can't wait to see your trick,{i.title()}.\n")
print("Thank you,everyone.That was a great magic show!")

#ERROR
for i in name:
    print(f"{i.title()},that was a great trick!")
    print(f"I can't wait to see your trick,{i.title()}.\n")
	print("Thank you,everyone.That was a great magic show!")

5.遗漏了冒号

#ERROR
for i in range(0, len(name))
    print(name[i].title(), ",that was a great trick!")
    
#√:
for i in range(0, len(name)):
    print(name[i].title(), ",that was a great trick!")
4.3 range()和list()
range(x)    ==    range(0,x)
range(x,y)
range(x,y,z)

for i in range(6):
    print(i)
0
1
2
3
4
5

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

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

#步长为2
for i in range(0, 6, 2):
    print(i)
    
总计:range()函数,左闭有开(左边能取到,右边取不到,且默认从0开始),带有步长的,意为间隔,不指定步长,默认为1


----------------------------------------------------------------


num = list(range(1,6))
print(num)

结果:[1, 2, 3, 4, 5]




print("任务1:打印1~10的偶数,步长为2")
print(list(range(2, 11, 2)))

print("任务2:打印1~10的奇数,步长为2")
print(list(range(1, 11, 2)))

print("创建一个列表,包含1~10的平方")
list = []
for i in range(1, 11):
    value = i ** 2
    list.append(value)
print(list)

对数字列表执行简单的统计计算

#找出数字列表的最大值、最小值、总和
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(f"最大值:{max(digits)}")
print(f"最小值:{min(digits)}")
print(f"总和:{sum(digits)}")

列表解析

#上边计算1~10的平方和太过麻烦,可用两行代码解决完毕,这就是列表解析

list = [i ** 2for i in range(1, 11)]
print(list)
4.4使用列表的一部分

4.4.1切片

#列表的切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
#打印列表的第一个元素
print(players[0])

#打印列表的第1、2、3个元素(索引0、1、2)
print(players[0:3])

#打印列表的第2、3、4个元素(索引1、2、3)
print(players[1:4])

#打印列表的最后三个元素(负数索引)
print(players[-3:])

#让python每隔2个元素就提取1个
print(players[0::2])

遍历切片

players = ['charles', 'martina', 'michael', 'florence', 'eli']
#打印出如下结果:
Here are the first three players on my team:
charles
martina
michael

#遍历切片,方法
print("Here are the first three players on my team:")
for i in players[0:3]:
    print(i.title())

复制列表

#复制列表
myfoods = ['pizza', 'falafel', 'carrot', 'cake']
friend_foods = myfoods[:]
print(f"myfoods:  {myfoods}\n")
print(f"friend_foods:  {friend_foods}\n")

myfoods.append('chiken')
friend_foods.append('coffe')

print(f"myfoods:  {myfoods}\n")
print(f"friend_foods:  {friend_foods}\n")

#结果:
myfoods:  ['pizza', 'falafel', 'carrot', 'cake']

myfoods:  ['pizza', 'falafel', 'carrot', 'cake']

myfoods:  ['pizza', 'falafel', 'carrot', 'cake', 'chiken']

myfoods:  ['pizza', 'falafel', 'carrot', 'cake', 'coffe']
    
    
    
    
#注意:
myfoods = ['pizza', 'falafel', 'carrot', 'cake']
friend_foods = myfoods
print(f"myfoods:  {myfoods}\n")
print(f"friend_foods:  {friend_foods}\n")

myfoods.append('chiken')
friend_foods.append('coffe')

print(f"myfoods:  {myfoods}\n")
print(f"friend_foods:  {friend_foods}\n")

#结果:
myfoods:  ['pizza', 'falafel', 'carrot', 'cake']

myfoods:  ['pizza', 'falafel', 'carrot', 'cake']

myfoods:  ['pizza', 'falafel', 'carrot', 'cake', 'chiken', 'coffe']

myfoods:  ['pizza', 'falafel', 'carrot', 'cake', 'chiken', 'coffe']

5.0 元组


#元组
dimensions = (200, 500)
print(dimensions[0])
print(dimensions[1])

5.1 遍历元组中的所有值

#遍历元组中的所有值
dimensions = (200, 500)
for i in dimensions:
    print(i)

5.3 修改元组变量

dimensions = (200, 500)
print(dimensions)
dimensions = (400, 500)
print(dimensions)
#不能通过索引的方式去赋值,但是可以通过如上方法直接修改元组的变量

6.0 If条件语句


#一个简单的示例:
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
for i in digits:
    if i == 2:
        print(f"This is {i}")
    else:
        print(f"This is not 2")

6.2条件测试

True False
car = "audi"
print(car == "bwm")

car = "audi"
print(car == "audi")

6.3 检查是否相等时,忽略大小写

car = "Audi"
print(car == "audi")     -->>>   False
#不忽略大小写

car = "Audi"
print(car.lower() == "audi")     -->>>   True

6.4 检查是否不相等

#要判断两个值是否不等,可结合使用感叹号和等号(! =)
car = "Audi"
if car != 'bwm':
    print("This is not BWM")

6.5 数值比较

==
>
<
>=
<=

6.6 检查多个条件

1.使用 and 检查多个条件

有假则假
2.使用 or 检查多个条件

有真则真

6.7.1 检查特定值是否包含在列表中

requested_toppings = ["mushrooms", "onions", "pineapple"]

print("mushrooms"  in requested_toppings)

6.7.2 检查特定值是否不包含在列表中

requested_toppings = ["mushrooms", "onions", "pineapple"]
topping = "mushrooms"
if topping not in requested_toppings:
    print("mushrooms不在列表中")
else:
    print("mushrooms在列表中"
          
#结果:
mushrooms在列表中

6.8 布尔值表达式

game_active = True
can_edit = False

6.9 if语句

1.简单的if语句

如果年龄大于等于18,打印:
You are old enough to vote!
Have you registerd to vote yet?

age = 20
if age >= 18:
    print("You are old enough to vote!\nHave you registerd to vote yet?")
  1. if - else 语句
如果年龄大于等于18,打印:
You are old enough to vote!
Have you registerd to vote yet?
如果年龄小于等于18,打印:
Sorry,you are too young to vote.
Please register to vote as soon as you turn 18!

age = 10
if age >= 18:
    print("You are old enough to vote!\nHave you registerd to vote yet?")
else:
    print("Sorry,you are too young to vote.\nPlease register to vote as soon as you turn 18!")
  1. if - elif - else结构
根据年龄阶段收费的游乐场:
4岁以下免费;
4~18岁收费25美元;
18岁(含)以上收费40美元;

age = 17
if age < 4:
    price = 0
    print(f"you cost {price}$!")
elif age < 18:
    price = 25
    print(f"you cost {price}$!")
else:
    price = 40
    print(f"you cost {price}$!")
  1. 使用多个elif代码块
根据年龄阶段收费的游乐场:
4岁以下免费;
4~18岁收费25美元;
18岁(含)以上收费40美元;
65岁(含)以上的老人收费20美元;
增加一个打折条件判断,判断顾客是否符合打折条件。假设对于65岁(含)以上的老人,可半价(即20美元)购买门票!


age = 64
if age < 4:
    price = 0
    print(f"you cost {price}$!")
elif age < 18:
    price = 25
    print(f"you cost {price}$!")
elif age < 65:
    price = 40
    print(f"you cost {price}$!")
else:
    price = 20
    print(f"you cost {price}$!")

​ 5. 省略else代码块

age = 65
if age < 4:
    price = 0
    print(f"you cost {price}$!")
elif age < 18:
    price = 25
    print(f"you cost {price}$!")
elif age < 65:
    price = 40
    print(f"you cost {price}$!")
elif age >= 65:
    price = 20
    print(f"you cost {price}$!")

​ 6. 测试多个条件

requested_toppings = ["mushrooms", "onions", "pineapple"]
if "mushrooms" in requested_toppings:
    print("ADD mushrooms")
if "onions" in requested_toppings:
    print("onions")
if "pineapple" in requested_toppings:
    print("pineapple")

6.9.1 使用if语句处理列表

#任务:
披萨配料:mushrooms、green peppers、extra、cheese
使用for循环告诉用户需要陆续添加到披萨得三种配料才能完成披萨制作
ADD xx配料
ADD xx配料
ADD xx配料
完成你的披萨啦!!!

requested_toppings = ["mushrooms", "green peppers", "extra", "cheese"]
for i in requested_toppings:
    print(f"ADD {i}")
print("完成你的披萨啦!!!")
#青椒用完了,告诉用户不能添加青椒的原因!
方法1:
requested_toppings = ["mushrooms", "green peppers", "extra", "cheese"]
for i in requested_toppings:
    if "green peppers" == i:
        print("青椒用完了!!!")
    else:
        print(f"ADD {i}")
print("完成你的披萨啦!!!")
方法2:
requested_toppings = ["mushrooms", "green peppers", "extra", "cheese"]
for i in requested_toppings:
    if "green peppers" == i:
        print("青椒用完了!!!")
        continue
    print(f"ADD {i}")
print("完成你的披萨啦!!!")

6.9.2 确定列表不是空的

requested_toppings = []
if requested_toppings:
    for i in requested_toppings:
        print(f"ADD {i}")
    print("完成你的披萨啦!!!")
else:
    print("您未点配料,是否要原味的披萨?")

6.9.3 使用多个列表

avaliable_toppings = ["mushrooms", "olives", "green peppers", "pepperoni", "pineapple", "extra cheese"]
requested_toppings = ["mushrooms", "french fries", "extra cheese"]
for i in requested_toppings:
    if i not in avaliable_toppings:
        print(f"Soory,{i}配料已用完!")
    else:
        print(f"ADD {i}")
print("完成你的披萨啦!!!")

6.9.4 设置if语句的格式

#ERROR

if age>=18:
    print("不推荐,因为代码不易读")
#√:

if age >= 18:
    print("不推荐,因为代码不易读")

7.0 字典


#一个简单的字典  (key:values)
alien = {'color':'green','poinits':'5'}
print(alien['color'])
print(alien['poinits'])
7.1 使用字典
alien = {'color':'green','poinits':'5'}
alien = {'color':'green'}
7.2 访问字典中的值
alien = {'color':'green'}
print(alien['color'])
7.3 修改字典的值
alien = {'color':'green'}
alien['color'] = yellow
print(alien['color'])
#结果为:yellow
7.4 添加键值对
#字典是一种动态结构,可随时在其中添加键值对。要添加键值对,可依此指定字典名、用方括号括起来键和相关联的值。
alien = {'color':'green','poinits':'5'}
print(alien)
#新增键值对
alien['x_position'] = 0
alien['y_position'] = 25
print(alien)
#结果
{'color': 'green', 'poinits': '5'}
{'color': 'green', 'poinits': '5', 'x_position': 0, 'y_position': 25}
7.5 先创建一个空字典
alien = {}
alien['color'] = 'green'
alien['poinits'] = '5'
print(alien)
#结果
{'color': 'green', 'poinits': '5'}
7.6 删除键值对
#任务:字典alien = {'color':'green','poinits':'5'}
使用del语句从字典中删除键‘points’和它的值
del 字典名['要删除的键']

alien = {'color':'green','poinits':'5'}
del alien['color']
print(alien)
7.7 由类似对象组成的字典
任务:打印出Sarah's favorite language is C.

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python'
}

print(f"Sarah's favorite language is {favorite_languages['sarah'].title()}")
7.8 使用get()来访问值
alien = {'color':'green','poinits':'5'}
print(alien['no'])

#此时会扔出错误:
    print(alien['no'])
KeyError: 'no'
    
#这种情况我们需要使用get()
alien = {'color':'green','poinits':'5'}
alien_point = alien.get('point', 'No point value show')
print(alien_point)
>>>>输出结果为:
No point value show
#原因:
get()取一个字典中的key,如果取不到,则会返回','后面的值,如果能取到,则返回key对应的value


#介绍下 下面这种情况
alien = {'color':'green','poinits':'5'}
alien_point = alien.get('point')
print(alien_point)
>>>>输出结果为:
None
#原因:
get(),没有指定没有key的返回值,若没有对应的key、value的话,则返回None
7.9 遍历字典
#遍历所有的键值对
user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi'
}

#任务:打印出如下
#key:username
#value: efermi

#key:first:
#value:enrico

#key:last
#value:fermi

item()
返回可遍历的(,) 元组数组


for a, b in user_0.items():
    print(f"\nKey:{a}")
    print(f"Value:{b}")

    
    
任务:打印以下内容
Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python'
}


for key, value in favorite_languages.items():
    print(f"{key.title()}'s favorite language is {value.title()}.")
7.10 遍历字典中的所有键
key()方法-返回一个字典所有键
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python'
}

打印出:
Hi jen.
Hi Sarah.
	sarah,I see you love C!
Hi Edward.
Hi Phil.
	Phil,I see you love Python!
    
name = ['sarah', 'phil']
for key in favorite_languages.keys():
    print(f"Hi,{key.title()}.")
    if key in name:
        print(f"\t{key.title()},I see you love {favorite_languages[f'{key}']}")
        
if 'erni' not in favorite_languages.keys():
    print("Erni not in favorite_languages")
6.3.3 按照特定顺序遍历字典中的所有键
使用函数sorted()对列表临时排序
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python'
}
for i in favorite_languages.keys():
    print(f"{i.title()},thanks you!")
    
Jen,thanks you!
Sarah,thanks you!
Edward,thanks you!
Phil,thanks you!
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python'
}

for i in sorted(favorite_languages.keys()):
    print(f"{i.title()},thanks you!")
    
Edward,thanks you!
Jen,thanks you!
Phil,thanks you!
Sarah,thanks you!
6.3.4 遍历字典中的所有值
keys()方法-返回字典中所有的键
value()方法-返回字典中的所有值
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python'
}


for i in favorite_languages.values():
    print(f"{i.title()}")
    
    
Python
C
Ruby
Python
#会发现有重复的,我们可以使用如下方法
使用set()函数进行去重
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python'
}

for i in set(favorite_languages.values()):
    print(f"{i.title()}")
    
    
Ruby
C
Python

6.4 嵌套(套娃)

6.4.1 字典列表
alien_0 = {'color':'green','points':'5'}
alien_1 = {'color':'yellow','points':'10'}
alien_2 = {'color':'red','points':'15'}
for i in alien:
    print(i)
    
{'color': 'green', 'points': '5'}
{'color': 'yellow', 'points': '10'}
{'color': 'red', 'points': '15'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
{'color': 'green', 'points': '5', 'speed': 'slow'}
...
{'color': 'green', 'points': '5', 'speed': 'slow'}
Total number of aliens:30
#创建一个用于存储外星人的空列表
aliens = []

#创建30个绿色的外星人
for i in range(1, 31):
    new_alien = {'color': 'green', 'points': '5', 'speed': 'slow'}
    aliens.append(new_alien)

#显示前5个外星人
for i in aliens[0:5]:
    print(i)

#显示....
print("...")

#显示创建了多少个外星人
print(f"Total number of aliens:{len(aliens)}")
#创建一个用于存储外星人的空列表
aliens = []

#创建30个绿色的外星人
for i in range(1, 31):
    new_alien = {'color': 'green', 'points': '5', 'speed': 'slow'}
    aliens.append(new_alien)

#前三个外星人修改为黄色、速度为中等且值10分
方法1for i in range(0,3):
    aliens[i] = "{'color': 'yellow', 'points': '10', 'speed': 'mid'}"

方法2for i in aliens[0:3]:
    if i['color'] == 'green':
        i['color'] = 'yellow'
        i['points'] = '10'
        i['speed'] = 'mid'
    
#显示前5个外星人
for i in aliens[0:5]:
    print(i)

#显示....
print("...")

#显示创建了多少个外星人
print(f"Total number of aliens:{len(aliens)}")
#创建一个用于存储外星人的空列表
aliens = []

#创建30个绿色的外星人
for i in range(1, 31):
    new_alien = {'color': 'green', 'points': '5', 'speed': 'slow'}
    aliens.append(new_alien)

#编写一条if语句来确保只修改绿色外星人
#如果外星人是绿色的,就将其颜色改为'yellow',将其速度改为'mediu',并将其分数改为10
	#将黄色外星人改为移动速度快且值为15分的红色外星人
for i in aliens[:3]:
    if i['color'] == 'green':
        i['color'] = 'yellow'
        i['speed'] = 'mediu'
        i['points'] = '10'
    elif i['color'] == 'yellow':
        i['speed'] = 'fast'
        i['points'] = '15'
        i['color'] = 'red'
    
    
#显示前5个外星人
for i in aliens[0:5]:
    print(i)

#显示....
print("...")

#显示创建了多少个外星人
print(f"Total number of aliens:{len(aliens)}")
6.4.2 在字典列表中存储列表
pizza = {
    'crust': 'thick'
    'toppings': '['mushrooms', 'extra cheese']'
}

You ordered a thick-crust pizza with the following toppings:
    mushrooms
    extra cheese
#存储所点披萨的信息
pizza = {
    'crust': 'thick'
    'toppings': "['mushrooms', 'extra cheese']"
}

#概述所点的比萨
print(f"You ordered a {pizza['crust']}-crust pizza with the following toppings:")

#for循环遍历键’toppings‘
for i in pizza['toppings']:
    print("\t" + i)
favorite_languages = {
    'jen': ['python', 'ruby'],
    'sarah': ['c'],
    'edward': ['ruby', 'go'],
    'phil': ['python', 'haskell']
}


Jen's favorite languages are:
	Python
	Ruby
Sarah's favorite languages are:
	C
Edward's favorite languages are:
	Ruby
	Go
Phil's favorite languages are:
	Python
	Haskell
for a, b in favorite_languages.items():
    print(f"{a.title()}'s favorite languages are:")
    for i in b[:]:
        print(f"\t{i.title()}")
6.4.3 在字典中存储字典
users = {
	'aeinstein':{
		'first': 'albert',
		'last': 'einstein',
		'location': 'princeton'
	},
	'mcurie':{
		'first': 'marie',
		'last': 'curie',
		'location': 'paris'
	}
}


7.用户输入和while循环

7.1 函数input()的工作原理

任务:让用户输入文本,把文本呈现给用户

Tell me something,and I will repeat it back to you: Hello everyone!
Hello everyone!
message = input("Tell me something,and I will repeat it back to you:")
print(message)
7.1.1 编写清晰的程序
变量 = input(参数: 说明/提示)
name = input("Please enter your name:")
print(f"\nHello,{name}")
prompt = "if you tell us who you are,we can personalize the message you see."
#prompt = prompt + "\nWhat is your first name?"
prompt += "\nWhat is your first name?"
name = input(prompt)
print(f"Hello,{name}")
7.1.2 使用int()来获取数值输入
int()  #可以把字符串转换为整型值
age = input("How old are you?")
age >= 18
#输入20,会报错---->TypeError: '>=' not supported between instances of 'str' and 'int'


#解决
age = input("How old are you?")
age = int(age)
age >= 18  
任务:  询问用户身高多少。
如果用户身高大于48inches,可以做过山车. (You're tall enough to ride!)
如果用户身高小于48inches,不可以坐过山车.(You'll be able to ride when you're alittle oder.)
sg = input("What is your height?")
if int(sg) >= 48:
    print("You're tall enough to ride!")
else:
    print("You'll be able to ride when you're alittle oder.")
7.1.3 求模运算符
将两个数相除并返回余数
如果一个数可被另一个数整数,余数就为0,因此求模运算将返回0.
可利用这一点来判断一个数是奇数还是偶数
print(4 % 3)
>>>1
print(5 % 3)
>>>2
print(6 % 3)
>>>0
print(7 % 3)
>>>1
#任务:
Enter a number,and I'll tell you It's even or odd:数字
The number 数字 is 偶数/奇数!


number = input("Enter a number,and I'll tell you It's even or odd:")
number_qy = int(number) % 2
if number_qy == 1:
    print(f"The number {number} is 奇数!")
else:
    print(f"The number {number} is 偶数!")
7.2 while 循环简介
for 循环-用于针对集合中的每个元素都执行一个代码块
while循环-则不断运行,直到指定的条件不满足为止
7.2.1 使用while 循环
例子:从1开始递减,大于5就停止递增
#方法1
number = 1
while True:
    print(number)
    number += 1
    if number > 5:
        break
#方法2      
number = 1
while  number <= 5:
    print(number)
    number += 1
7.2.2 让用户选择何时退出-设定退出值
#空字符串
message = ""
#空列表
message = []
#空字典
message = {}
prompt = "\nTell me something,and I will repeat it back to you:"
prompt += "\nEnter quit to end the program."
message = ""
while message != 'quit':
    message = input(prompt)
    if message == 'quit':
        break
7.2.3 使用标志
定义一个变量,用于判断整个程序是否处于活动状态。这个变量称为标志.
可以让程序在标志为True时继续运行,并在任何事件导致标志的值为False时让程序停止运行.
这样,在while语句中就只需检查一个条件:标志的当前的值是否为True。然后将所有其他测试(是否发生了应将标志设置为False的事件)都放在其他地方,从而让程序更整洁.
prompt = "\nTell me something,and I will repeat it back to you:"
prompt += "\nEnter quit to end the program."
active = True
while active:
    message = input(prompt)
    if message == 'quit':
        break
    else:
        print(message)
7.2.4 使用break退出循环
prompt = "\nTell me something,and I will repeat it back to you:"
prompt += "\nEnter quit to end the program."
active = True
while active:
    message = input(prompt)
    if message == 'quit':
        break
    else:
        print(message)

在任何Python的循环中都可以使用break语句

7.2.5 在循环中使用continue
跳出本次循环,进入下一次循环
break-不执行余下的代码,退出整个循环
continue-不执行余下代码,返回循环的开头
#例子:从1数到10但只打印奇数的循环
number = 0
while number < 10:
    number += 1
    if number %2 == 1:
        print(number)
    else:
        continue
7.2.6 避免无限循环
#无限循环
x =1
while x <= 5:
    print(x)

#√
x =1
while x <= 5:
    i += 1
    print(x)
7.3 使用while循环处理列表和字典
7.3.1 在列表之间移动元素
假设有一个列表包含新注册但还未验证的网站用户
unconfiremed_user = ['alice', 'brian', 'candace']

验证这些用户后,如何将他们移动到另一个已验证用户列表中呢?

confiremed_user = []

办法是使用一个while循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其他加入另一个已验证用户的列表中.
#首先,创建一个未验证用户列表
#和一个用于存储已验证用户的空列表
unconfiremed_user = ['alice', 'brian', 'candace']
confiremed_user = []

#验证每个用户,直到没有验证用户为止
#将每个经过验证的用户都移动到已验证用户列表中

while unconfiremed_user:
    current_user = unconfiremed_user.pop().title()
    confiremed_user.append(current_user)

#显示所有已验证的用户
print(f"All authenticated users:")
for user in confiremed_user:
    print(f"\t{user}")
7.3.2 删除为特定值的所有列表元素
移除cat
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
#移除cat
while 'cat' in pets:
    pets.remove('cat')
print(pets)
7.3.3 使用用户输入来填充字典
#投票例子
responses = {}
while True:
    user_key = "Please enter your name!"
    user_value = "Please enter the mountain you want to climb!"
    report = "Do you want another person to investigate?  [yes/no]"
    name = input(user_key)
    mt = input(user_value)
    reports = input(report)
    responses[name] = mt
    if reports == "no":
        break
    print(responses)

8.1 定义函数

#定义函数
def greet_user():
    #显示简单的问候语
    print("Hello!")
#调用函数
greet_user
8.1.1 向函数传递信息
def greet_user(username):
    print(f"Hello!{username.title()}")
greet_user('ming')

结果为:
>>>  Hello!Ming
#我们在调用函数的时候,将其传递给username
8.1.2 实参和形参
def greet_user(username):
    print(f"Hello!{username.title()}")
greet_user('ming')

#username形参
#'ming'实参

8.2传递实参

位置实参+关键字实参
8.2.1位置实参
任务:打印

I have a xxx.
My xxxx's name os xxx.
基于实参的顺序在函数调用时把每个实参关联到函数定义的形参
def desscribe(animal_type, pet_name):
    print(f"I have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name}")

desscribe('hashiqi', 'logs')

1.多次调用函数

def desscribe(animal_type, pet_name):
    print(f"I have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name}")

#调用一次
desscribe('hashiqi', 'logs')
#调用两次
desscribe('bomei', 'qianqian')

2.位置实参的顺序很重要

def desscribe(animal_type, pet_name):
    print(f"I have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name}")

desscribe('hashiqi', 'logs')
#若是将上边的实参更换顺序,就不对了,如下:
desscribe('logs''hashiqi')
8.2.2关键字实参

在实参中将名称和值关联起来

def desscribe(animal_type, pet_name):
    print(f"I have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name}")

desscribe(animal_type='hashiqi', pet_name='logs')
8.2.3 默认值
在调用函数时,给形参提供了实参,Python就使用你指定的实参值.
你没有给形参提供实参,就使用形参默认值

可给每个形参指定默认值
给animal_type形参指定默认值dog
def desscribe(animal_type, pet_name="xiaogou"):
    print(f"I have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name}")

desscribe(animal_type='hashiqi')
#在这可以发现:我们没有给pet_name指定值,但是我们在当初给其设定了一个默认值,当我们不指定的时候,就为默认值.
8.2.4 等效的函数调用
def desscribe(animal_type, pet_name="xiaogou"):
    print(f"I have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name}")

desscribe(animal_type='hashiqi')
desscribe('hashiqi')

>>>
I have a hashiqi.
My hashiqi's name is xiaogou
I have a hashiqi.
My hashiqi's name is xiaogou
#我们在调用函数的时候,一定要说明好实参传给哪个形参
8.2.5 避免实参错误
def desscribe(animal_type, pet_name):
    print(f"I have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name}")
desscribe()

#ERROR:>>>>
TypeError: desscribe() missing 2 required positional arguments: 'animal_type' and 'pet_name'

8.3 返回值

函数返回值-返回值
在函数中,可以用Return语句将函数内部的值返回到调用函数的代码行
8.3.1 返回简单值
first name: jimi
last name: jimi hendrix

full name: Jimi Hendrix(首字母大写)
def big_name(first_name, last_name):
    full_name = f"{first_name} {last_name}"
    return full_name.title()
report = big_name('jimi', 'henrix')
print(report)
#result >>>
Jimi Henrix

#定义两个形参first_name, last_name。下面调用函数,一直到return返回值,将结果返回给report,最后输出打印。
8.3.2 让实参变成可选的
def big_name(first_name,last_name , middle_name=''):
    if middle_name == '':
        full_name = f"{first_name} {last_name}"
    else:
        full_name = f"{first_name} {middle_name} {last_name}"
    return full_name.title()
report = big_name('jimi', 'henrix')
print(report)
8.3.3 返回字典
{'first':'jimi', 'last':'hendrix'}
def big_name(first_name,last_name):
    zd = {}
    zd[first_name] = last_name
    return zd
bg = big_name('jimi', 'henrix')
print(bg)
def big_name(first_name,last_name,age=None):
    zd = {}
    zd[first_name] = last_name
    if age:
        zd['age'] = age
    return zd
bg = big_name('jimi', 'henrix','27')
print(bg)
8.3.4 结合使用函数和while循环
def name(first_name,last_name):
    full_name = f"{first_name}{last_name}"
    return full_name.title()


while True:
    print("\nPlease enter your name:")
    print("enter 'q' at any time to quit!")
    f_name = input("First_name:")
    if f_name == 'q':
        break

    l_name = input("Last_name:")
    if l_name == 'q':
        break

    formatted_name = name(f_name,l_name)
    print(f"\nhello,{formatted_name}")
8.4 传递列表
任务:

user_name = ['hannah', 'ty', 'margot']
Hello,Hannash!
Hello,Ty!
Hello,Margot!
def list_name(names):
    for name in names:
        msg = f"Hello,{name.title()}!"
        print(msg)

user_name = ['hannah', 'ty', 'margot']
list_name(user_name)
8.4.1 在函数中修改列表
#首先创建一个列表,其中包含一些要都打印的设计
unprinted_designs = ['phone case', 'robotpendant', 'dodecahedron']
completed_models = []

#模拟打印每个设计,直到没有未打印的设计为止
#打印每个设计后,都将其移到列表cpmpleted_models中


#显示打印好的所有模型

def desgin(demo_unprinted,demo_completed):
    while demo_unprinted:
        demo_current_desgin = demo_unprinted.pop()
        print(f"Printed current_desgin: {demo_current_desgin}")
        demo_completed.append(demo_current_desgin)
def printed(show_completed):
    for i in show_completed:
        print(i)

unprinted_designs = ['phone case', 'robotpendant', 'dodecahedron']
completed_models = []
desgin(unprinted_designs, completed_models)
printed(completed_models)
8.4.2 禁止函数修改列表
将列表的副本传递给函数
function_name(list_name[:]):
#此方法会将unprinted_designs这个列表置为空
def desgin(demo_unprinted,demo_completed):
    while demo_unprinted:
        demo_current_desgin = demo_unprinted.pop()
        print(f"Printed current_desgin: {demo_current_desgin}")
        demo_completed.append(demo_current_desgin)
def printed(show_completed):
    for i in show_completed:
        print(i)

unprinted_designs = ['phone case', 'robotpendant', 'dodecahedron']
completed_models = []
desgin(unprinted_designs, completed_models)
printed(completed_models)
#此方法讲列表的副本传递给函数,就不会讲unprinted_designs列表置空
def desgin(demo_unprinted,demo_completed):
    while demo_unprinted:
        demo_current_desgin = demo_unprinted.pop()
        print(f"Printed current_desgin: {demo_current_desgin}")
        demo_completed.append(demo_current_desgin)
def printed(show_completed):
    for i in show_completed:
        print(i)

unprinted_designs = ['phone case', 'robotpendant', 'dodecahedron']
completed_models = []
desgin(unprinted_designs[:], completed_models)
printed(completed_models)
8.5 传递任意数量的实参
形参名*toppings中的星号:让python创建一个名为toppings的空元组,并且把收到的所有值也就是我们这里函数调用时给的这些实参都装到这一个元组中
def make_pizza(toppings):
    """打印顾客点的所有配料"""
    print(toppings)
make_pizza('pepperonli')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

ERROR:  >>>> TypeError: make_pizza() takes 1 positional argument but 3 were given  #紧接受一个位置的传参,但是我们这给了三个
        
解决:
def make_pizza(*toppings):
    """打印顾客点的所有配料"""
    print(toppings)
make_pizza('pepperonli')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
#紧需要在形参toppings前加一个*号就可以了
#   '*'的作用:让python创建一个名为toppings的空元组,并且把收到的所有值也就是我们这里函数调用时给的这些实参都装到这一个元组中
def make_pizza(*toppings):
    print("\nMake a pizza with the following toppings:")
    for topping in toppings:
        print(f"- {topping}")
make_pizza('pepperonli')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
8.5.1 结合使用位置实参和任意数量实参
def make_pizza(size, *toppings):
    print(f"\nMake a {size} pizza with the following toppings:")
    for topping in toppings:
        print(f"- {topping}")
make_pizza('16', 'pepperonli')
make_pizza('19', 'mushrooms', 'green peppers', 'extra cheese')
#使用位置实参的时候,将带星号的放在最后面。
8.5.2 使用任意数量的关键字实参
def build_profile(**test):   可以让python创建一个名为test的空字典,并将所有名称值对都放到这个字典中。在这个函数中,可以像访问其他字典那样访问user_info中的名称值对.
build_profile('albert', 'einstein'
             location='princeton',
             field='physics')


def build_profile(first, last, **user_info):
    """"创建一个空字典,其中包含我们知道的一切"""
    user_info['first_name'] = first
    user_info['last_name'] = last
    return user_info

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


#结果为>>>
{'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}
8.6 将函数存储在模块中
8.6.1 导入整个模块
###first.py
def make_pizza(size, *toppings):
    print(f"\nMake a {size} pizza with the following toppings:")
    for topping in toppings:
        print(f"- {topping}")

#在其他python文件中进行调用
import first
# module_name.function_name()
first.make_pizza(16, 'pepperoni')
first.make_pizza(16, 'mushrooms', 'pepperoni')
8.6.2 导入特性的函数
from first import make_pizza
first.make_pizza(16, 'pepperoni')
first.make_pizza(16, 'mushrooms', 'pepperoni')
8.6.3 使用as给函数指定别名
from first import make_pizza as mp
mp(16, 'pepperoni')
mp(16, 'mushrooms', 'pepperoni')
8.6.4 使用as给模块指定别名
import first as  p
p.make_pizza(16, 'pepperoni')
p.make_pizza(16, 'mushrooms', 'pepperoni')
8.6.5 导入模块中的所有函数
from first import *
make_pizza(16, 'pepperoni')
make_pizza(16, 'mushrooms', 'pepperoni')
9.1 创建和使用类
9.1 创建Dog类
#类的首字母一定是要大写的
class Dog():
    """"一次模拟小狗的简单尝试"""
    def __init__(self, name, age): ##当Python每次调用这个__init__()方法的时候,它创建Dog实例,会自动传入实参self。每一个与实例相关联的这个方法,调用它都会自动传
        """"初始化属性name,age"""
        self.name = name  #以self为前缀的变量可以供类中所有方法使用,获取形参name相关联的值,将对应的值赋值给变量name
        self.age = age

    def __sit__(self):
        """模拟小狗收到命令时蹲下"""
        print(f"{self.name} is now sitting!")

    def __having(self):
        """模拟小狗收到命令时打滚"""
        print(f"{self.name} rolled over!")

mydog = Dog("Hsq", 2)

print(f"My dog's name is {mydog.name}")

print(f"My dog's age is {mydog.age}")
9.1.2 根据类创建实例

1.访问属性

mydog.name

2.调用方法

class Dog():
    """"一次模拟小狗的简单尝试"""
    def __init__(self, name, age): ##当Python每次调用这个__init__()方法的时候,它创建Dog实例,会自动传入实参self。每一个与实例相关联的这个方法,调用它都会自动传
        """"初始化属性name,age"""
        self.name = name  #以self为前缀的变量可以供类中所有方法使用,获取形参name相关联的值,将对应的值赋值给变量name
        self.age = age

    def sit(self):
        """模拟小狗收到命令时蹲下"""
        print(f"{self.name} is now sitting!")

    def having(self):
        """模拟小狗收到命令时打滚"""
        print(f"{self.name} rolled over!")
#创建一个实例
mydog = Dog("Hsq", 2)

#调用方法
mydog.sit()
mydog.having()

3.创建多个实例

class Dog():
    """"一次模拟小狗的简单尝试"""
    def __init__(self, name, age): ##当Python每次调用这个__init__()方法的时候,它创建Dog实例,会自动传入实参self。每一个与实例相关联的这个方法,调用它都会自动传
        """"初始化属性name,age"""
        self.name = name  #以self为前缀的变量可以供类中所有方法使用,获取形参name相关联的值,将对应的值赋值给变量name
        self.age = age

    def sit(self):
        """模拟小狗收到命令时蹲下"""
        print(f"{self.name} is now sitting!")

    def having(self):
        """模拟小狗收到命令时打滚"""
        print(f"{self.name} rolled over!")

mydog = Dog("Hsq", 2)
yourdog = Dog("White", 3)

mydog.sit()
mydog.having()

print("----")

yourdog.sit()
yourdog.having()
class Dog():
    """"一次模拟小狗的简单尝试"""
    def __init__(self, name, age): ##当Python每次调用这个__init__()方法的时候,它创建Dog实例,会自动传入实参self。每一个与实例相关联的这个方法,调用它都会自动传
        """"初始化属性name,age"""
        self.name = name  #以self为前缀的变量可以供类中所有方法使用,获取形参name相关联的值,将对应的值赋值给变量name
        self.age = age

    def sit(self):
        """模拟小狗收到命令时蹲下"""
        print(f"{self.name} is now sitting!")

    def having(self):
        """模拟小狗收到命令时打滚"""
        print(f"{self.name} rolled over!")

mydog = Dog("Hsq", 2)
yourdog = Dog("White", 3)

print(f"Mydog's name is {mydog.name}")
print(f"Mydog's age is {mydog.age}")
mydog.sit()

print("----")

print(f"Yourdog's name is {yourdog.name}")
print(f"Yourdog's age is {yourdog.age}")
yourdog.sit()
9.2 使用类和实例
9.2.1 Car类
class Car:
    """"模拟汽车"""

    def __init__(self, make, model, year):
        """初始化汽车的属性"""
        self.make = make
        self.model = model
        self.year = year

    def get_car_sz(self):
        """汽车的属性"""
        descripts = f"{self.year} {self.make} {self.model}"
        return descripts.title()


MyCar = Car("Aodi", "a4", 2019)
print(MyCar.get_car_sz())
9.2.2 给属性指定默认值
1.一开始汽车的里程为0,添加一个名为odometer_reading的属性,其初始值总是为02.添加了一个名为read_odometer()的方法,用于读取汽车的里程表
class Car:
    """"模拟汽车"""

    def __init__(self, make, model, year):
        """初始化汽车的属性"""
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_car_sz(self):
        """汽车的属性"""
        descripts = f"{self.year} {self.make} {self.model}"
        return descripts.title()

    def read_odometer(self):
        print(f"The course of {self.make} Automobile is {self.odometer_reading}")


MyCar = Car("Aodi", "a4", 2019)
print(MyCar.get_car_sz())
MyCar.read_odometer()
9.2.3修改属性的值
1.直接修改属性的值
直接将里程表读数设置为23
class Car:
    """"模拟汽车"""

    def __init__(self, make, model, year):
        """初始化汽车的属性"""
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_car_sz(self):
        """汽车的属性"""
        descripts = f"{self.year} {self.make} {self.model}"
        return descripts.title()

    def read_odometer(self):
        print(f"The course of {self.make} Automobile is {self.odometer_reading}")


MyCar = Car("Aodi", "a4", 2019)
print(MyCar.get_car_sz())

MyCar.odometer_reading = 23
MyCar.read_odometer()
2.通过方法修改属性的值
无需直接访问属性,而可将值传递给方法,由它在内部进行更新
class Car:
    """"模拟汽车"""

    def __init__(self, make, model, year):
        """初始化汽车的属性"""
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_car_sz(self):
        """汽车的属性"""
        descripts = f"{self.year} {self.make} {self.model}"
        return descripts.title()

    def read_odometer(self):
        print(f"The course of {self.make} Automobile is {self.odometer_reading}")

    def update_odometer(self, mileage):
        self.odometer_reading = mileage


Mycar = Car(2019, "Aodi", "A4")
print(Mycar.get_car_sz())
Mycar.update_odometer(23)
Mycar.read_odometer()
update_odometer()在修改属性前检查指定的读数是否合理。
如果新指定的里程(mileage)大于或等于原来的里程(self.odometer_reading),
就将里程表读数改为新指定的里程;
否则发出警告,指出不能将里程表往回调。
class Car:
    """"模拟汽车"""

    def __init__(self, make, model, year):
        """初始化汽车的属性"""
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_car_sz(self):
        """汽车的属性"""
        descripts = f"{self.year} {self.make} {self.model}"
        return descripts.title()

    def read_odometer(self):
        print(f"The course of {self.make} Automobile is {self.odometer_reading}")

    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
            Mycar.read_odometer()
        else:
            print("Warn: You can't set the odometer back.")


Mycar = Car(2019, "Aodi", "A4")
print(Mycar.get_car_sz())
Mycar.update_odometer(-2)
3.通过方法对属性的值进行递增
假设我们购买了一辆二手车,且从购买到登记期间增加了100英里的里程。
class Car:
    """"模拟汽车"""

    def __init__(self, make, model, year):
        """初始化汽车的属性"""
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_car_sz(self):
        """汽车的属性"""
        descripts = f"{self.year} {self.make} {self.model}"
        return descripts.title()

    def read_odometer(self):
        print(f"The course of {self.make} Automobile is {self.odometer_reading}")

    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
            Mycar.read_odometer()
        else:
            print("Warn: You can't set the odometer back.")

    def increase_odometer(self, mileage):
        self.odometer_reading += mileage




Mycar = Car(2019, "Aodi", "A4")
print(Mycar.get_car_sz())

Mycar.update_odometer(23_00)

Mycar.increase_odometer(100)
Mycar.read_odometer()
9.3继承
9.3.1子类的方法init()
一个类可以继承另一个类的所有属性和方法,被继承的类称为父类,新的类称为子类.
需要注意的是:在创建子类的时候,父类必须是包含在当前文件中,位于子类前面
class Mycar(object):
    pass


class Car:
    """"模拟汽车"""

    def __init__(self, make, model, year):
        """初始化汽车的属性"""
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_car_sz(self):
        """汽车的属性"""
        descripts = f"{self.year} {self.make} {self.model}"
        return descripts.title()

    def read_odometer(self):
        print(f"The course of {self.make} Automobile is {self.odometer_reading}")

    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("Warn: You can't set the odometer back.")

    def increase_odometer(self, mileage):
        self.odometer_reading += mileage


class Electriccar(Car):
    """电动车"""
    """需要注意的是:在创建子类的时候,父类必须是包含在当前文件中,位于子类前面"""

    def __init__(self, make, model, year):
        """初始化父类的属性,super()这个函数是一个特殊函数,可以调用父类的方法"""
        super().__init__(make, model, year)


# 创建Electriccar的实例,赋值给my_tesla
my_tesla = Electriccar(21, "BWM", "x5")
print(my_tesla.get_car_sz())

>>>结果:
	X5 21 Bwm
9.3.2给子类定义属性和方法
1.继承Car类
2.编写新方法:电瓶容量75
class Mycar(object):
    pass


class Car:
    """"模拟汽车"""

    def __init__(self, make, model, year):
        """初始化汽车的属性"""
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_car_sz(self):
        """汽车的属性"""
        descripts = f"{self.year} {self.make} {self.model}"
        return descripts.title()

    def read_odometer(self):
        print(f"The course of {self.make} Automobile is {self.odometer_reading}")

    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("Warn: You can't set the odometer back.")

    def increase_odometer(self, mileage):
        self.odometer_reading += mileage


class Electriccar(Car):
    """电动车"""
    """需要注意的是:在创建子类的时候,父类必须是包含在当前文件中,位于子类前面"""
    def __init__(self, make, model, year):
        """初始化父类的属性,super()这个函数是一个特殊函数,可以调用父类的方法"""
        super().__init__(make, model, year)
        """添加新的属性:电瓶容量"""
        self.battery_size = 75

    def capacity(self):
        print(f"The capacity of {self.make} battery car is {self.battery_size}.")

# 创建Electriccar的实例,赋值给my_tesla
my_tesla = Electriccar(21, "BWM", "x5")
print(my_tesla.get_car_sz())
my_tesla.capacity()
#自我扩展:定义一个方法,进行嗲偶哦那个方法自减10
class Mycar(object):
    pass


class Car:
    """"模拟汽车"""

    def __init__(self, make, model, year):
        """初始化汽车的属性"""
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_car_sz(self):
        """汽车的属性"""
        descripts = f"{self.year} {self.make} {self.model}"
        return descripts.title()

    def read_odometer(self):
        print(f"The course of {self.make} Automobile is {self.odometer_reading}")

    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("Warn: You can't set the odometer back.")

    def increase_odometer(self, mileage):
        self.odometer_reading += mileage


class Electriccar(Car):
    """电动车"""
    """需要注意的是:在创建子类的时候,父类必须是包含在当前文件中,位于子类前面"""
    def __init__(self, make, model, year):
        """初始化父类的属性,super()这个函数是一个特殊函数,可以调用父类的方法"""
        super().__init__(make, model, year)
        """添加新的属性:电瓶容量"""
        self.battery_size = 75

    def capacity(self):
        print(f"The capacity of {self.make} battery car is {self.battery_size}.")

    def update_capacity(self):
        self.battery_size -= 10

# 创建Electriccar的实例,赋值给my_tesla
my_tesla = Electriccar(21, "BWM", "x5")
print(my_tesla.get_car_sz())
my_tesla.capacity()

my_tesla.update_capacity()
my_tesla.capacity()
9.3.3 重写父类的方法
#父类定义了一个方法:
    def fill_gas_tank(self):
        print("This car needs a gas tank!")
        
#子类定义了一个方法
    def fill_gas_tank(self):
        print("The electric car does not have a mailbox!")
        
#用子类去调用:
my_tesla = Electriccar(21, "BWM", "x5")
print(my_tesla.get_car_sz())
my_tesla.capacity()

my_tesla.fill_gas_tank()

#调用fill_gas_tank()方法结果为:
	The electric car does not have a mailbox!
9.3.4 将实例用作属性
在Electriccar类和Car类之间创建一个Battery类(在这个类没有继承谁)
class Mycar(object):
    pass


class Car:
    """"模拟汽车"""

    def __init__(self, make, model, year):
        """初始化汽车的属性"""
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_car_sz(self):
        """汽车的属性"""
        descripts = f"{self.year} {self.make} {self.model}"
        return descripts.title()

    def read_odometer(self):
        print(f"The course of {self.make} Automobile is {self.odometer_reading}")

    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("Warn: You can't set the odometer back.")

    def increase_odometer(self, mileage):
        self.odometer_reading += mileage

    def fill_gas_tank(self):
        print("This car needs a gas tank!")


class Battery:
    def __init__(self, battery_size=75):
        self.battery_size = battery_size

    def descripts_battery(self):
        print(f"This car has a {self.battery_size} -kwh battery!")


class Electriccar(Car):
    """电动车"""
    """需要注意的是:在创建子类的时候,父类必须是包含在当前文件中,位于子类前面"""

    def __init__(self, make, model, year):
        """初始化父类的属性,super()这个函数是一个特殊函数,可以调用父类的方法"""
        super().__init__(make, model, year)
        """定义新类,没有继承类"""
        self.battery = Battery()

    def fill_gas_tank(self):
        print("The electric car does not have a mailbox!")


# 创建Electriccar的实例,赋值给my_tesla;每次创建;
# Electriccar的实例,就会自动创建Battery这个实例;
my_tesla = Electriccar(21, "BWM", "x5")
print(my_tesla.get_car_sz())

my_tesla.battery.descripts_battery()
#创建Electriccar实例.调用将实例Battery用作属性的battery属性(self.battery ).调用方法
#扩展:增加了一个方法(判断)

class Mycar(object):
    pass


class Car:
    """"模拟汽车"""

    def __init__(self, make, model, year):
        """初始化汽车的属性"""
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_car_sz(self):
        """汽车的属性"""
        descripts = f"{self.year} {self.make} {self.model}"
        return descripts.title()

    def read_odometer(self):
        print(f"The course of {self.make} Automobile is {self.odometer_reading}")

    def update_odometer(self, mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("Warn: You can't set the odometer back.")

    def increase_odometer(self, mileage):
        self.odometer_reading += mileage

    def fill_gas_tank(self):
        print("This car needs a gas tank!")


class Battery:
    def __init__(self, battery_size=75):
        self.battery_size = battery_size

    def descripts_battery(self):
        print(f"This car has a {self.battery_size} -kwh battery!")

    def get_range(self):
        """打印一条信息:指出电瓶容量的信息"""
        if self.battery_size == 75:
            range = 260
        elif self.battery_size == 100:
            range = 315


class Electriccar(Car):
    """电动车"""
    """需要注意的是:在创建子类的时候,父类必须是包含在当前文件中,位于子类前面"""

    def __init__(self, make, model, year):
        """初始化父类的属性,super()这个函数是一个特殊函数,可以调用父类的方法"""
        super().__init__(make, model, year)
        """定义新类,没有继承类"""
        self.battery = Battery()

    def fill_gas_tank(self):
        print("The electric car does not have a mailbox!")


# 创建Electriccar的实例,赋值给my_tesla;每次创建Electriccar的实例,就会自动创建Battery这个实例;
my_tesla = Electriccar(21, "BWM", "x5")
print(my_tesla.get_car_sz())

my_tesla.battery.descripts_battery()
my_tesla.battery.get_range()
10.0 文件和异常
10.1.1 从文件中读取数据

with open 返回的文件对象,只能在with代码块内使用!!

想要在with代码块外使用我们则使用readlines()函数

with open('C:/Users/Ming/Desktop/Pthon/Python_test/pi_digits.txt') as file_object:
    contents = file_object.read()
print(contents


#结果>>>(输出最后是有空行的)
3.1415926535
  8979323846
  2643383279
      
#在这我犯了个错:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: tr
    
#原因是在windows系统当中读取文件路径可以使用\,但是在python字符串中\有转义的含义,如\t可代表TAB,\n代表换行,所以我们需要采取一些方式使得\不被解读为转义字符
>>> 改为这样的路径就可以了
>>> 'C:/Users/Ming/Desktop/Pthon/Python_test/pi_digits.txt'
10.1.2 rstrip()函数
#10.1 的结果是有空行的,我们用以下方法取消

with open('C:/Users/Ming/Desktop/Pthon/Python_test/pi_digits.txt') as file_object:
    contents = file_object.read()
print(contents.rstrip())  #我们使用rstrip()函数取消空行
#结果>>>
3.1415926535
  8979323846
  2643383279
10.1.3 将路径赋值变量,进行引用
file_path = 'C:/Users/Ming/Desktop/Pthon/Python_test/pi_digits.txt'
with open(file_path) as file_object:
    contents = file_object.read()
print(contents.rstrip())
10.1.4 逐行读取
file_path = 'C:/Users/Ming/Desktop/Pthon/Python_test/pi_digits.txt'
with open(file_path) as file_object:
    for line in file_object:
        print(line)
        
#结果有换行
3.1415926535

  8979323846

  2643383279

#同样,我们使用rstrip()函数进行取消
file_path = 'C:/Users/Ming/Desktop/Pthon/Python_test/pi_digits.txt'
with open(file_path) as file_object:
    for line in file_object:
        print(line.rstrip())
10.1.5 创建一个文件各行内容的列表
file_path = 'C:/Users/Ming/Desktop/Pthon/Python_test/pi_digits.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()
for line in lines:
    print(line.rstrip())
10.1.6 使用文件的内容
#将上边的结果进行调整为一行

file_path = 'C:/Users/Ming/Desktop/Pthon/Python_test/pi_digits.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()

p1 = ''
for line in lines:
    p1 = p1 + line.rstrip()
print(p1)
print(len(p1))


#结果>>>
3.1415926535  8979323846  2643383279
36
#我们会发现,每个字符串之间是有空行的,我们想要取消调空行,使用strip()函数
file_path = 'C:/Users/Ming/Desktop/Pthon/Python_test/pi_digits.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()

p1 = ''
for line in lines:
    p1 = p1 + line.strip()
print(p1)
print(len(p1))
#结果>>>
3.141592653589793238462643383279
32
10.1.7 包含100w位的大型文件
#我们不需要全部打印出来,只需要打印出后十位

file_path = 'C:/Users/Ming/Desktop/Pthon/源代码文件/chapter_10/pi_million_digits.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()

p1 = ''
for line in lines:
    p1 = p1 + line.strip()
print(f"{p1[:12]}...")
print(len(p1))
让用户自动输入他的生日,在圆周率中进行查找,如果查找到了打印在圆周率中;如果找不到则打印没在圆周率中
file_path = 'C:/Users/Ming/Desktop/Pthon/源代码文件/chapter_10/pi_million_digits.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()

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

birthday = input("Please enter your birthday,format mmddyy: ")
if birthday in p1:
    print("Your anger appears in the pi.")
else:
    print("Your anger appears not in the pi.")
10.2 写入文件
   # w是写入模式
file_name = "C:/Users/Ming/Desktop/Pthon/Python_test/programming.txt"
with open(file_name, 'w') as file_object:
    file_object.write("I love programming.\n")
    file_object.write("I love new games.\n")
#>>> 去相应的路径下查找这个文件,可以看到那两行输出

# a是追加模式
file_name = "C:/Users/Ming/Desktop/Pthon/Python_test/programming.txt"
with open(file_name, 'a') as file_object:
    file_object.write("I also love programming.\n")
    file_object.write("I don't love new games.\n")

#>>> 可以看到除了之前那两行输出外,又新增了两行输出.
print(5/0)
#报错如下:
ZeroDivisionError: division by zero
    
#解决:
try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")
    
#如果try后面的代码块执行出错的话,会打印输出: You can't divide by zero!
#如果try后面的代码块执行不出错的话,则会忽略except后面的代码块的内容;
print("Give me two number, and I'll divide thme.")
print("Enter 'q' to quit.")

while True:
    first_numner = input("\nPlease enter your first number.")
    if first_numner == 'q':
        break
    second_number = input("Please enter your second number.")
    if second_number == 'q':
        break

    

    try:
        answer = int(first_numner) / int(second_number)
    except ZeroDivisionError:
        print("You can't divide by zero!")
    else:
        print(answer)
       
file_name = 'C:/Users/Ming/Desktop/Pthon/Python_test/alice.txt'
with open(file_name, encoding='utf-8') as f:
    contents = f.read()
    
#执行报错  No such file or directory: 'C:/Users/Ming/Desktop/Pthon/Python_test/alice.txt'

#此时我们需要整改,如下:
from os import closerange


file_name = 'C:/Users/Ming/Desktop/Pthon/Python_test/alice.txt'

try:
    with open(file_name, encoding='utf-8') as f:
        contents = f.read()
except FileNotFoundError:
    print("Sorry, the file does not exits.")

split()方法

split()方法:以空格为分割隔线,将字符分割,为<列表>
title = "Alice is beautiful."

str_title = title.split()
print(str_title)


#结果:
['Alice', 'is', 'beautiful.']

print(type(str_title))
#结果为: 列表  <class 'list'>
file_name = 'C:/Users/Ming/Desktop/Pthon/Python_test/alice.txt'

try:
    with open(file_name, encoding='utf-8') as f:
        contents = f.read()
except FileNotFoundError:
    print("Sorry, the file does not exits.")
else:
    words = contents.split()
    numbet_words = len(words)
    print(f"{file_name.split('/')[-1]} has about {numbet_words} words")
    
#结果>>>
	alice.txt has about 29465 words
def words(file_name):
    """计算一个txt文件有多少个单词"""
    try:
        with open(file_name, encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        print("Sorry, the file does not exits.")
    else:
        words = contents.split()
        numbet_words = len(words)
        print(f"{file_name.split('/')[-1]} has about {numbet_words} words\n")

words('C:/Users/Ming/Desktop/Pthon/Python_test/alice.txt')
words('C:/Users/Ming/Desktop/Pthon/Python_test/programming.txt')
def words(file_name):
    """计算一个txt文件有多少个单词"""
    try:
        with open(file_name, encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        print("Sorry, the file does not exits.")
    else:
        words = contents.split()
        numbet_words = len(words)
        print(f"{file_name.split('/')[-1]} has about {numbet_words} words\n")

file_name = ['C:/Users/Ming/Desktop/Pthon/Python_test/alice.txt', 'C:/Users/Ming/Desktop/Pthon/Python_test/programming.txt', 'C:/Users/Ming/Desktop/Pthon/Python_test/pi_digits.txt']
for file in file_name:
    words(file)
    
#结果>>>
alice.txt has about 29465 words

programming.txt has about 16 words

pi_digits.txt has about 3 words

def words(file_name):
    """计算一个txt文件有多少个单词"""
    try:
        with open(file_name, encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        pass    #不存在则pass掉(略过)
    else:
        words = contents.split()
        numbet_words = len(words)
        print(f"{file_name.split('/')[-1]} has about {numbet_words} words\n")

file_name = ['not_exit', 'C:/Users/Ming/Desktop/Pthon/Python_test/alice.txt', 'C:/Users/Ming/Desktop/Pthon/Python_test/programming.txt', 'C:/Users/Ming/Desktop/Pthon/Python_test/pi_digits.txt']
for file in file_name:
    words(file)
10.3 存储数据(json模块)
JSON模块:可以将简单的数据结构存储在文件中,程序再次运行的时候,可以加载这个文件中的数据
10.3.1 json.dump()
json.dump() 要存什么数据,存在哪里
json.load() 要读什么数据

json.dump()

import json

numbers = ['1', '2', '3', '4']
file_name = 'number.json'
with open(file_name, 'w') as f:
    json.dump(numbers, f)
    
#首先尽管没有这个number.json文件,调用dump()函数,将列表写入在了文件中

json.load()

import json

file_name = 'number.json'
with open(file_name) as f:
    number_load = json.load(f)

print(number_load)
#首先用with open()函数打开文件,打开了之后,调用load()函数,读取内容,并将内容打印.
10.3.2 保存和读取用户生成的数据
1. 把用户输入的名字保存到username.json文件中
import json

name = input("Please enter a first name: ")

file_name = 'username.json'
with open(file_name, 'w') as f:
    json.dump(name, f)
    print(f"We'll remember you when you come back, {name}")


2. 向用户打招呼,打招呼的时候,要提到他的名字
import json

file_name = 'username.json'
with open(file_name) as f:
    name = json.load(f)
    print(f"Welcome back, {name}")

10.3.3 重构
import json

def get_stored_username():
    """Read the name from the file."""
    file_name = 'username.json'
    try:
        with open(file_name) as f:
            username = json.load(f)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_name():
    """Save the name entered by the user to a file."""
    file_name = 'username.json'
    user_name = input("Please enter the name you want to add: ")
    with open(file_name, 'w') as f:
        json.dump(user_name, f)
    return user_name

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

greet_user()
11.1测试函数
def get_formatted_name(first_name, last_name, middle=''):
    """生成全名"""
    if middle:
        full_name = f"{first_name} {middle} {last_name}"
        return full_name.title()
    else:
        full_name = f"{first_name} {last_name}"
        return full_name.title()

from full_name import get_formatted_name

print("Enter 'q' to quit.")

while True:
    first_name = input("\nPlease give me your first name: ")
    if first_name == 'q':
        break
    last_name = input("\nPlease enter your last name: \n")
    if last_name == 'q':
        break

    formatted_name = get_formatted_name(first_name, last_name)
    print(f"\tNeatly formatted name: {formatted_name}.")

import unittest


from full_name import get_formatted_name

class NamespaceTestcase(unittest.TestCase):
    """测试full_name.py"""
    def test_first_last_name(self):
        """能否处理像Janis Joplin这样的姓名吗?"""
        formatted_name = get_formatted_name('Janis', 'Joplin')
        self.assertEqual(formatted_name, 'Janis Joplin')

    def test_first_middle_last_name(self):
        "have middle name."
        formatted_name = get_formatted_name('Fang', 'Ming', 'Wei')
        self.assertEqual(formatted_name, 'Fang Wei Ming')

if __name__ == '__main__':
    unittest.main()
11.2 测试类
class survery:
    def __init__(self, question):
        """存储一个问题,并为存储问题做准备"""
        self.question = question
        self.responses = []

    def show_question(self):
        "打印问题"
        print(self.question)

    def store_responses(self, newreponses):
        """存储单位问题"""
        self.responses.append(newreponses)
    
    def show_results(self):
        """显示收集到的所有答案"""
        print("Survery result is")
        for result in self.responses:
            print(f"\t- {result}")
            
from survery import survery

#定义一个问题,并创建一个调查问卷
question = "What language did you first learn to speak?"
my_survery = survery(question)

#显示并存储答案
my_survery.show_question()
print("Enter 'q' to quit.\n")

while True:
    reponses = input(question)
    if reponses == 'q':
        break
    my_survery.store_responses(reponses)

#显示收集到的所有答案
my_survery.show_results()
import unittest

from survery import survery

class Survery_test(unittest.TestCase):

    def setUp(self):
        """创建一个调查对象和一组答案,供使用的测试方法使用,setUp方法无论放在什么未知,都是先运行此方法"""
        question = "What language did you first learn to speak?"
        self.my_survery = survery(question)
        self.responses = ['English', 'Chinese', 'Mandarin']


    """针对survery类的测试"""
    def test_survery_test(self):
        self.my_survery.store_responses(self.responses[0])
        self.assertIn(self.responses[0], self.my_survery.responses)


    def test_survery_three_test(self):
        """测试三个答案"""
        for response in self.responses:
            self.my_survery.store_responses(response)
        for response in self.responses:
            self.assertIn(response, self.my_survery.responses)

if __name__ == '__main__':
    unittest.main()
    
    

setUp方法

每次执行函数方法时,必须先执行一次setUp(self)函数,其他方法需要在前加self引用
15. 生成数据
15.1 安装matplotlib库
python -m pip install -U pip
python -m pip install -U matplotlib
15.2 绘制简单的折线图
import matplotlib.pyplot as plt

squares = [1, 4, 9, 16, 25]

"""subplots可以在一个图片中绘多个图标,fig表示整个图片,ax表示图片中的各个图标"""
fig, ax = plt.subplots()


ax.plot(squares)

plt.show()

#运行查看效果
15.3 修改标签文字和线条粗细
import matplotlib.pyplot as plt

input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]

"""subplots可以在一个图片中绘多个图标,fig表示整个图片,ax表示图片中的各个图标"""
fig, ax = plt.subplots()


ax.plot(input_values, squares, linewidth=3)

#图表的标题
ax.set_title("平方数", fontsize=14)

#x轴小标题
ax.set_xlabel("值", fontsize=14)

#y轴小标题
ax.set_ylabel("值的平方", fontsize=14)

#修改刻度标记的大小
ax.tick_params(axis='both', labelsize=14)

plt.show()
15.3 内置样式
#查看样式
>>>python
>>> import matplotlib.pyplot as plt
>>> plt.style.available
['Solarize_Light2', '_classic_test_patch', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']
import matplotlib.pyplot as plt

input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]

plt.style.use('seaborn-whitegrid')

"""subplots可以在一个图片中绘多个图标,fig表示整个图片,ax表示图片中的各个图标"""
fig, ax = plt.subplots()

ax.plot(input_values, squares, linewidth=3)

#图表的标题
ax.set_title("平方数", fontsize=14)

#x轴小标题
ax.set_xlabel("值", fontsize=14)

#y轴小标题
ax.set_ylabel("值的平方", fontsize=14)

#修改刻度标记的大小
ax.tick_params(axis='both', labelsize=14)

plt.show()
15.4 使用scatter绘制散点图
import matplotlib.pyplot as plt


plt.style.use('seaborn')

plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']

fig, ax = plt.subplots()

ax.scatter(2,4, s=150)

#图表的标题
ax.set_title("平方数", fontsize=14)

#x轴小标题
ax.set_xlabel("值", fontsize=14)

#y轴小标题
ax.set_ylabel("值的平方", fontsize=14)

#刻度标记的大小
ax.tick_params(axis='both', which='major', labelsize=14)

plt.show()
15.4 使用scatter绘制一系列散点图
import matplotlib.pyplot as plt

x_values = [1, 2, 3, 4, 5]
y_values = [1, 4, 9, 16 ,25]

plt.style.use('seaborn')

#中文字体的设置
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']

fig, ax = plt.subplots()

ax.scatter(x_values,y_values, s=100)

#图表的标题
ax.set_title("平方数", fontsize=14)

#x轴小标题
ax.set_xlabel("值", fontsize=14)

#y轴小标题
ax.set_ylabel("值的平方", fontsize=14)

#刻度标记的大小
ax.tick_params(axis='both', which='major', labelsize=14)

plt.show()
15.5 自动计算数据
import matplotlib.pyplot as plt

x_values = range(1,1001)
y_values = [x ** 2 for x in x_values]

plt.style.use('seaborn')

#中文字体的设置
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']

fig, ax = plt.subplots()

ax.scatter(x_values,y_values, s=100)

#图表的标题
ax.set_title("平方数", fontsize=14)

#x轴小标题
ax.set_xlabel("值", fontsize=14)

#y轴小标题
ax.set_ylabel("值的平方", fontsize=14)

#刻度标记的大小
ax.tick_params(axis='both', which='major', labelsize=14)

#每个坐标轴的取值范围,x轴的取值范围:0—1100,y轴的取值范围:0—1100000
ax.axis([0, 1100, 0, 1100000])

plt.show()
15.6 自定义颜色
import matplotlib.pyplot as plt

x_values = range(1,1001)
y_values = [x ** 2 for x in x_values]

plt.style.use('seaborn')

#中文字体的设置
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']

fig, ax = plt.subplots()

#ax.scatter(x_values,y_values, s=50, c='red')     
ax.scatter(x_values,y_values, s=50, c=(0, 0.8, 0))    #RGB值来定义

#图表的标题
ax.set_title("平方数", fontsize=14)

#x轴小标题
ax.set_xlabel("值", fontsize=14)

#y轴小标题
ax.set_ylabel("值的平方", fontsize=14)

#刻度标记的大小
ax.tick_params(axis='both', which='major', labelsize=14)

#每个坐标轴的取值范围,x轴的取值范围:0—1100,y轴的取值范围:0—1100000
ax.axis([0, 1100, 0, 1100000])

plt.show()
15.7使用颜色映射
import matplotlib.pyplot as plt

x_values = range(1,1001)
y_values = [x ** 2 for x in x_values]

plt.style.use('seaborn')

#中文字体的设置
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']

fig, ax = plt.subplots()

ax.scatter(x_values,y_values, c=y_values, cmap=plt.cm.Blues, s=10)

#图表的标题
ax.set_title("平方数", fontsize=14)

#x轴小标题
ax.set_xlabel("值", fontsize=14)

#y轴小标题
ax.set_ylabel("值的平方", fontsize=14)

#刻度标记的大小
ax.tick_params(axis='both', which='major', labelsize=14)

#每个坐标轴的取值范围,x轴的取值范围:0—1100,y轴的取值范围:0—1100000
ax.axis([0, 1100, 0, 1100000])

plt.show()
15.8 自动保存图表
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox

x_values = range(1,1001)
y_values = [x ** 2 for x in x_values]

plt.style.use('seaborn')

#中文字体的设置
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']

fig, ax = plt.subplots()

ax.scatter(x_values,y_values, c=y_values, cmap=plt.cm.Blues, s=10)

#图表的标题
ax.set_title("平方数", fontsize=14)

#x轴小标题
ax.set_xlabel("值", fontsize=14)

#y轴小标题
ax.set_ylabel("值的平方", fontsize=14)

#刻度标记的大小
ax.tick_params(axis='both', which='major', labelsize=14)

#每个坐标轴的取值范围,x轴的取值范围:0—1100,y轴的取值范围:0—1100000
ax.axis([0, 1100, 0, 1100000])

plt.savefig('squares_plot.png', bbox_inches='tight')
15.9 创建Randomwalk的类
from random import choice

class Randomwalk:
    """生成一个随机漫步数据的类"""
    def __init__(self, number_point=5000):
        """初始化随机漫步数据的属性"""
        self.number_point = number_point

        #所有漫步数据都始于(0,0)
        self.x_values = [0]
        self.y_values = [0]
15.10 选择方向
    def fill_walk(self):
        """计算随机漫步包含的所有点"""
        #不断进行漫步,直到达指定的长度
        while len(self.x_values) < self.number_point:
            #决定前进的方向,以及沿这个方向前进的距离
            x_direction = choice(1, -1)
            x_distance = choice([0, 1, 2, 3, 4])
            x_step = x_distance * x_direction

            y_direction = choice(1, -1)
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_distance * y_direction

            #拒绝原地踏步
            if x_direction == 0 and y_direction == 0:
                continue

            #计算下一个点的x值和y值
            x = self.x_values[-1] + x_step
            y = self.y_values[-1] + y_step
            self.x_values.append(x)
            self.y_values.append(y)
15.11 绘制随机漫步图
#matplolib.py

from random import choice

class Randomwalk:
    """生成一个随机漫步数据的类"""
    def __init__(self, number_point=5000):
        """初始化随机漫步数据的属性"""
        self.number_point = number_point

        #所有漫步数据都始于(0,0)
        self.x_values = [0]
        self.y_values = [0]

    def fill_walk(self):
        """计算随机漫步包含的所有点"""
        #不断进行漫步,直到达指定的长度
        while len(self.x_values) < self.number_point:
            #决定前进的方向,以及沿这个方向前进的距离
            x_direction = choice([1, -1])
            x_distance = choice([0, 1, 2, 3, 4])
            x_step = x_distance * x_direction

            y_direction = choice([1, -1])
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_distance * y_direction

            #拒绝原地踏步
            if x_direction == 0 and y_direction == 0:
                continue

            #计算下一个点的x值和y值
            x = self.x_values[-1] + x_step
            y = self.y_values[-1] + y_step
            self.x_values.append(x)
            self.y_values.append(y)


#rw.py

import matplotlib.pyplot as plt

from matplolib import Randomwalk

rw = Randomwalk()
rw.fill_walk()

plt.style.use('classic')
fig, ax = plt.subplots()
ax.scatter(rw.x_values, rw.y_values, s=15)

plt.show()
15.12 模拟多次随机漫步
from logging import raiseExceptions
import matplotlib.pyplot as plt

from matplolib import Randomwalk

while True:
    rw = Randomwalk()
    rw.fill_walk()

    plt.style.use('classic')
    fig, ax = plt.subplots()
    ax.scatter(rw.x_values, rw.y_values, s=15)

    plt.show()

    response = input("Do you want to do it again? [Y/N]")
    if response == 'N':
        break
15.13 给点着色
from logging import raiseExceptions
import matplotlib.pyplot as plt

from matplolib import Randomwalk

while True:
    rw = Randomwalk()
    rw.fill_walk()

    plt.style.use('classic')
    fig, ax = plt.subplots()
    number_points = range(rw.number_point)
    ax.scatter(rw.x_values, rw.y_values, c=number_points,cmap=plt.cm.Blues, s=15)

    plt.show()

    response = input("Do you want to do it again? [Y/N]")
    if response == 'N' or 'n':
        break
15.14 突出起点、终点
from logging import raiseExceptions
import matplotlib.pyplot as plt

from matplolib import Randomwalk

while True:
    rw = Randomwalk()
    rw.fill_walk()

    plt.style.use('classic')
    fig, ax = plt.subplots()
    number_points = range(rw.number_point)
    ax.scatter(rw.x_values, rw.y_values, c=number_points,cmap=plt.cm.Blues, s=15)

    #突出起点终点
    ax.scatter(0, 0, c='green', edgecolors='none', s=50)
    ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=50)



    plt.show()

    response = input("Do you want to do it again? [Y/N]")
    if response == 'N' or 'n':
        break

15.15 隐藏坐标轴
from logging import raiseExceptions
import matplotlib.pyplot as plt

from matplolib import Randomwalk

while True:
    rw = Randomwalk()
    rw.fill_walk()

    plt.style.use('classic')
    fig, ax = plt.subplots()
    number_points = range(rw.number_point)
    ax.scatter(rw.x_values, rw.y_values, c=number_points,cmap=plt.cm.Blues, s=15)

    #突出起点终点
    ax.scatter(0, 0, c='green', edgecolors='none', s=50)
    ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=50)

    #隐藏坐标轴
    ax.get_yaxis().set_visible(False)
    ax.get_xaxis().set_visible(False)



    plt.show()

    response = input("Do you want to do it again? [Y/N]")
    if response == 'N' or 'n':
        break

15.16增加点数
#改变程序中控制点数的变量就可以
number_point=2000
15.17 调整图标尺寸
from logging import raiseExceptions
import matplotlib.pyplot as plt

from matplolib import Randomwalk

while True:
    rw = Randomwalk()
    rw.fill_walk()

    plt.style.use('classic')
    fig, ax = plt.subplots(figsize=(15, 9), dpi=128)
    number_points = range(rw.number_point)
    ax.scatter(rw.x_values, rw.y_values, c=number_points,cmap=plt.cm.Blues, s=1)

    #突出起点终点
    ax.scatter(0, 0, c='green', edgecolors='none', s=50)
    ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=50)

    #隐藏坐标轴
    ax.get_yaxis().set_visible(False)
    ax.get_xaxis().set_visible(False)



    plt.show()

    response = input("Do you want to do it again? [Y/N]")
    if response == 'N' or 'n':
        break

16.0 Plotly
16.1 安装plotly
pythom -m pip install plotly==5.1.0
16.2 创建die类
from random import randinit, random

class die:
    def __init__(self, number=6):
        self.number = number
    
    def roll(self):
        return random(1, self.number)
16.3 扔筛子
from die import Die


results = []

die = Die()

for i in range(100):
    result = die.roll()
    results.append(result)
    print(results)
16.4每个点数出现的次数
from typing import ValuesView
from die import Die


results = []

die = Die()

for i in range(100):
    result = die.roll()
    results.append(result)
    print(results)

frequencies = []
for value in range(1, die.number+1):
    frequencie = results.count(value)
    frequencies.append(frequencie)
    print(f"\n{value}'s count: {frequencies[value-1]}")
16.5 绘制直方图
from datetime import date
from os import name
import plotly.graph_objects as go
from die import Die


results = []

die = Die()

for i in range(100):
    result = die.roll()
    results.append(result)
    print(results)

frequencies = []
for value in range(1, die.number+1):
    frequencie = results.count(value)
    frequencies.append(frequencie)


# 可视化
fig = go.Figure()
fig.add_trace(go.Bar(
    name='D6',
    x=list(range(1, die.number+1)), y=frequencies
))

fig.update_layout(barmode='group')
fig.show()
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

登高·

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值