《Python编程从入门到实践》——精华知识点总结

第一章 起步

python是解释型语言

pycharm自动对齐代码:ctrl + alt + L

第二章 变量和简单数据类型

值得说的内容太少了:

python的变量应该也是弱类型,不用在前边加数据类型。python语言的包袱非常轻,一句后面不用加 ; 并且字符串单引号和双引号都可以

python也是一个完全面向对象的语言,一切都视为对象。

2.1 变量和字符串

有关字符串的几个方法:

#title()方法的作用:首字母大写每个单词
name = "yang jiaxing"
print(name.title()) # Yang Jiaxing

print(name.upper())  #将name字符串转化为大写
print(name.lower())  #将name字符串转化为小写

# 在字符串中使用变量:f字符串:f是format的简写,python通过把花括号内的变量替换为其值来设置字符串的格式

first_name = "yang"
last_name = "jiaxing"
full_name = f"{first_name}{last_name}"
print(full_name)   #yangjiaxing
print(f"Hello,{full_name.title()}")   # Hello,Yangjiaxing

有关删除空白的几个方法:

# 要想确保字符串末尾没有空白,可使用方法rstip()
name = 'yangjiaxing '
real_name = name.rstrip()
print(real_name)  # 输出结果会删除最后一个空格

# 删除字符串开头的空白 lstrip()  删除两边的空白 strip()

本节练习题:

# 练习 2-3
name = "yangjiaxing"
print(f"hello {name},would you like to learn some python?")

# 练习 2-4
name = "yang jiaxing"
print(name.lower())
print(name.upper())
print(name.title())

# 练习 2-5
name = "yang jiaxing"
print(f'{name} once said,"A person is A person"')

# 练习 2-6
famous_name = "yang jiaxing"
message = f'{famous_name} once said,"A person is A person"'
print(message)

# 练习 2-7
name = "\tyang jiaxing\n"
print(name)
print(name.rstrip())  # 去除右边空白
print(name.lstrip())  # 去除左边空白
print(name.strip())   # 去除两侧空白

2.2 整数、浮点数、常量、注释、禅

在python中,整数和c相同,2*3=6 2**3=8 两个✖表示乘方运算

浮点数和c也是基本相同,将任意两个数相除时,得到的数一定是浮点数 4/2 = 2.0 这和c是不一样的

只要有操作数是浮点数,结果也是浮点数,这和c相同

书写很大的数时,可以用下划线将数字分组:

universe_age=14_000_000_000 当你打印这个数时,不会显示下划线

python还支持同时给多给变量赋值:

x,y,z = 0, 0 ,0 只要变量和值的个数相同,就可以正确的关联起来,这一点比c强。

python没有内置的常量,只能取名字的时候取全大写字母,把某个变量视为常量。

# 练习2-8
print(5+3)
print(10-2)
print(2*4)
print(8/1)

# 练习2-8
favor_num=13
print(f"my favorite number is {favor_num}")

注释:单行注释:#

python之禅:

输入import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea – let’s do more of those!

第三章 列表简介

3.1 列表定义

列表用方括号[ ] 表示,并用逗号分隔其中的元素。可以将任何东西放到列表中,其中的元素可以没有任何关系。

# 列表示例
subject = ['chinese','math','english']
print(subject)  #['chinese', 'math', 'english']

# 访问某个列表元素,索引也是从0开始的
print(subject[0])           # chinese
print(subject[2].title())   # English
print(f"I like {subject[2].title()} very much")   # I like English very much

# python可以将索引指定为 -1,访问的是最后一个列表元素,-2 访问的是倒数第二个,以此类推
subject = ['chinese','math','english']
print(subject[-1])
print(subject[-2])

练习题:

# 练习 3-1
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
print(friends)        # ['yang jiaxing', 'luo xinjian', 'hu boyang', 'wang jingqi']

# 练习 3-2
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
print(f"I like {friends[0].title()} very much")
print(f"I like {friends[1].title()} very much")
print(f"I like {friends[2].title()} very much")
print(f"I like {friends[3].title()} very much")

# 练习 3-3
同上,不做了

3.2修改、添加、删除列表元素:

# 可以使用索引修改某个元素的值
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
friends[0] = 'liu zhaoyang'
print(friends)

# 在列表末尾添加元素 使用append方法,可以使用该方法,往空列表中添加元素以建立列表
friends.append('wang gaiyan')   # 在列表尾插入王改燕
print(friends)

# 在列表中插入元素,使用insert方法  
friends.insert(1,'wang haina')  # 在第二个位置插入王海娜
print(friends)

# 删除某一个位置的元素: del语句,删除后就无法再访问该元素
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
del friends[0]
print(friends)

# 删除元素时,如果想使用值,使用pop()方法,pop()可以删除任意位置的元素,不止尾端
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
poped_name = friends.pop()   # 把尾端的值弹出
print(friends)           # ['yang jiaxing', 'luo xinjian', 'hu boyang']
print(poped_name)        # wang jingqi

friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
poped_name = friends.pop(0)
print(f"{poped_name} is a handsome man")      # yangjiaxing is a handsome man

# 根据值删除列表元素,用remove(),此方法只删除第一个指定的值,想删除重复值得用循环
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
friends.remove("yang jiaxing")
print(friends)

练习题

# 练习3-4
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
print(f"{friends[0]}{friends[1]}{friends[2]}{friends[3]}welcome to have a dinner with me")

# 练习3-5
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
print(f"{friends[0]} {friends[1]} {friends[2]} {friends[3]}welcome to have a dinner with me")
print(f"{friends[0]} can't come here for dinner")
friends[0]="wang gaiyan"
print(f"{friends[0]} {friends[1]} {friends[2]} {friends[3]}welcome to have a dinner with me")

# 练习3-6
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
friends.insert(0,"wang gaiyan")
friends.insert(2,"wang haina")
friends.append("liu zhaoyang")
print(friends)

# 练习3-7
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
name = friends.pop()
print(f"sorry {name},you can't come this dinner")
del friends[0]
print(friends)

3.3 列表排序

python的排序:

# 使用 sort对列表进行永久排序,如果想顺序相反就要修改参数
cars = ['bwm','audi','toyota']
cars.sort()				# 字符串按照首字母顺序排列,而且没法恢复到原来的排列序列
print(cars)
cars.sort(reverse = True)   # 逆序排序
print(cars)

# 使用sorted对列表临时排序,可以让列表排序显示而不影响他们在列表中的原始排列顺序
cars = ['bwm','audi','toyota']
print(sorted(cars))    # 也可以修改参数倒着临时打印
print(cars)

# 倒着打印列表,注意:这不是逆序打印,没有排序这个操作,只是直接倒着打印列表  
cars = ['bwm','audi','toyota']
print(cars)

cars.reverse()
print(cars)

# 确定列表的长度
cars = ['bwm','audi','toyota']
print(len(cars))         # 3

练习题:

# 练习3-8
travel = ['beijing','haerbin','chongqing','shenzhen','kunming']
print(travel)
print(sorted(travel))
print(travel)
print(sorted(travel,reverse=True))
print(travel)
travel.reverse()
print(travel)
travel.reverse()
print(travel)
travel.sort()
print(travel)
travel.sort(reverse = True)
print(travel)

# 练习3-9
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
print(f"总共邀请了{len(friends)} 个朋友")

# 练习3-10
likes = ['wang gaiyan','ha erbin']
likes.append("wang zherongyao")
print(likes)
likes.insert(1,'python')
print(likes)
likes.sort()
print(likes)
lieks.sort(reverse = True)
print(likes)
likes.pop(0)
print(likes)
del likes[2]
print(likes)
print(len(likes))

第四章 遍历整个列表

4.1 遍历列表使用for循环:

# 一个简单的for循环示例,有点类似于java的迭代器。每次在列表中取出一个值放到fruit变量中打印出来。
fruits = ['apple','orange','banana']
for fruit in fruits:
    print(fruit)

# python中for循环依靠缩进来判断是不是属于for循环内部(毕竟没有括号)
fruits = ['apple','orange','banana']
for fruit in fruits:
    print(fruit)					# 两个打印语句将各执行3遍
    print(f"{fruit} is very good!")

fruits = ['apple','orange','banana']
for fruit in fruits:
    print(fruit)					
print(f"{fruit} is very good!")    # 这个打印语句只会执行一遍
 

常见的问题:

# 忘记缩进,如下所示就会报错
for fruit in fruits:
print(fruit)

# 忘记改缩进的没缩进就会造成逻辑错误,如这种
for fruit in fruits:
    print(fruit)					
print(f"{fruit} is very good!") 

# 不必要的缩进,如果你没事闲的瞎缩进,系统也会报错
	print("hello world")
    
# 遗漏了冒号,遗漏冒号的错误往往不容易发现   

练习:

# 练习 4-1 
pizzas = ['a','b','c']
for pizza in pizzas:
    print(pizza)
    print(f"I like {pizza} pizza")
print("I really love pizza")

# 练习 4-2
animals = ['dog','cat','pig']
for animal in animals:
   	print(f"A {animal} would make a great pet")
print("Any of these animals would make a great pet!")

4.2 创建数值列表、列表解析

函数range( )可以生成一系列数

# 使用 range 函数产生的数可以打印1,不能打印到5(左闭右开)
for value in range(1,5):
    print(value)    # 打印 1 2 3 4

# 使用range()创建数字列表   list()函数将range的结果直接转化为列表
numbers = list(range(1,6)) 
print(numbers)     #[1, 2, 3, 4, 5]

# 使用range函数时,还可以指定步长,使用第三个参数
even_numbers = list(range(2,11,2))  # 打印1到10之间的偶数;
print(even_numbers)

# 使用range()循环创建前10个整数的平方的列表
squares = []
for value in range(1,11):
    square = value**2            # 也可以不使用临时变量 square ,直接 squares。append(value ** 2)
    squares.append(square)    
print(squares)

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

digits = [1,2,3]
min(digits)    #1
max(digits)    #3
sum(digits)    #6

列表解析:将for循环和创建新元素的代码合并成一行,并自动附加新元素。

squares = []
for value in range(1,11):
    square = value**2            # 也可以不使用临时变量 square ,直接 squares。append(value ** 2)
    squares.append(square)    
print(squares)

# 这是之前的代码,比较长,下面是列表解析写法,for循环给前面的表达式 vallue**2提供值。再加上右方括号
squares = [value**2 for value in range(1,11)]    # 注意 for循环是没有冒号的
print(squares)

练习

# 练习 4-3
for num in range(1,21):
    print(num)
    
# 练习 4-4
big_num = [value for value in range(1,1000001)]   # 我使用的是列表解析的方式创建的,数太大了计算机受不了
print(big_num)

big_num = list(range(1,101))   # 这是使用list方式
print(big_num)

# 练习4-5
big_num = [value for value in range(1,1000001)] 
print(max(big_num))
print(min(big_num))
print(sum(big_num))

# 练习 4-6
numbers = []
for value in range(1,21,2):
    number = value
    numbers.append(number)
print(numbers)

# 练习 4-7


# 练习 4-8
tri_num = []
for value in range(1,11):
    num = value **3
    tri_num.append(num)
print(tri_num)

# 练习 4-9
tri_num = [value**3 for value in range(1,11)]
print(tri_num)

4.3 切片、拷贝列表

切片: 处理列表中的部分元素

# 切片也是左闭右开  如下所示
suaige = [‘a’,'b','yangjiaxing','d']
print(suaige[0:3])          # ['a', 'b', 'yangjiaxing']

suaige = [‘a’,'b','yangjiaxing','d']
print(suaige[1:4])          # ['b', 'yangjiaxing', 'd']

# 没有指定第一个索引就自动从开头开始,没有指定最后一个则到末尾结束,也可以从 -3开始到末尾,相当于输出后三个。
suaige = ['a','b','yangjiaxing','d']
print(suaige[:4])
print(suaige[2:])
print(suaige(-3:))
# ['a', 'b', 'yangjiaxing', 'd']
# ['yangjiaxing', 'd']
# ['b', 'yangjiaxing', 'd']


# 切片也可以用来遍历列表的部分元素,比较好用
suaige = ['a','b','yangjiaxing','d']
for shuai in suaige[:3]:   # 用来遍历前三帅
    print(shuai)


拷贝列表

# 使用不带索引的切片可以复制列表,原理是从原来的列表中创建一个切片作为副本,并赋给新列表
my_food = ['pizza','apple','banana']
friend_food = my_foods[:]

# 不可以直接将一个列表直接赋值给另一个
friend_food = my_foods    # 这将会让两个列表相当于同一个列表

练习:

# 练习 4-10
word = ['a','b','c','d','e']
print("The first three items in the list are:")
print(word[:3])
print("Three items from the middle of the list are:")
print(word[1:4])
print("The last three items in the list are:")
print(word[-3:])
 
# 练习 4-11
my_foods = ['pizza','apple','banana']
friend_foods = my_foods[:]
my_foods.append('peach')
friend_foods.append('watermelon')
print(my_foods)
print(friend_foods)

# 练习 4-12

4.4 元组和代码格式

元组和列表很像,专门用来存储不可变的元素,用()而不是[ ],是一种只读的列表

dimensions = (200,50)
print(dimensions[0])
demensions[0] = 250         # 错误写法,元组的元素不能改
for demension in demensions:         # 元组可以遍历
    print(demension)
demension = (400,100)       # 虽然不能修改元组的元素,但是可以修改整个元组变量
# 练习4-13
foods = ('a','b','c','d','e')
for food in foods:
    print(food)
# foods[0]='f'  报错代码
foos = ('e','f')

代码格式设置: 访问python网站搜索PEP 8

第五章 if语句

python里的if语句基本等同于c,不同就是没有大括号得依赖缩进

# if语句示例
cars = ['audi','bmw','subaru','toyota']
for car in cars:
    if car == 'bwm':
        print(car.upper())
        print(car)
    else:
        print(car.title())
   
#  关键字and,相当于与,c语言中的&& ,关键字 or 相当于或,c语言中的||


# 关键词 in,可以判断一个值是否包含在列表中
word = ['a','b','c','d']
'a' in word    #True
item = 'e'
if item not in word:
    print(f"{item} not in the list!")
    
   
# if-elif-else 结构    此语句中也可以没有else
alien_color = "green"
if aline_color=='green':
    print("you got 5 point")
elif aline_color=='yellow':
    print("you got 10 point")
else print("you got 20 point")

第六章 字典

6.1 字典定义

字典是一系列键值对,每个键都与一个值相关联,每个键的值唯一。

# 字典示例
aline_0 = {'color':'green','points':5}
print(aline_0['color'])    # 访问字典中的值需要使用键
print(aline_0['points'])

# 添加键值对
aline_0 = {'color':'green','points':5}
print(aline_0)
aline_0['x-position'] = 0      # 比较简单,直接写上就加上了
aline_0['y-position'] = 25
print(aline_0)
aline_0['color'] = 'yellow'    # 修改字典中的值

# 类似对象组成的字典的书写
favorite_languages = {
    'yang':'python',
    'wang':'c',
    'luo':'java',
}

# 使用 get()方法来访问,第一个参数用于指定键,第二个参数为指定的键不存在时要返回的值。如果指定的键有可能不存在,就考虑使用方法get(),python将返回None
aline_0 = {'color':'green','speed':'slow'}
# print(aline_0['points'])     #这样会报错,键值错误
point_value = aline_0.get('points','No point value assigned') 
print(point_value)

练习

# 练习 6-1
wanggaiyan = {
    'first_name':'wang',
    'last_name':'gaiyan',
    'age':'20',
    'city':'handan',
}
for key,value in wanggaiyan.items():
    print(f"key:{key}")
    print(f"value:{value}")

 
# 练习 6-2

6.2 遍历字典

# 遍历所有键值对:使用items()方法,他返回一个键值对列表,for循环将每个键值对赋值给指定的两个变量,变量名任意

wanggaiyan = {
    'first_name':'wang',
    'last_name':'gaiyan',
    'age':'20',
    'city':'handan',
}
for key,value in wanggaiyan.items():
    print(f"key:{key}")
    print(f"value:{value}")
    
   
# 只遍历键
wanggaiyan = {
    'first_name':'wang',
    'last_name':'gaiyan',
    'age':'20',
    'city':'handan',
}
# 方法1, 直接for循环
for key in wanggaiyan:
    print(key)
   
# 方法2   使用keys()方法,跟1效果一样,但是更有可读性,keys()将返回一个key的列表
for key in wanggaiyan.keys():
    print(key)
   

# 按照特定的顺序遍历字典中的所有键,使用sorted函数对产生的列表临时排序
wanggaiyan = {
    'first_name':'wang',
    'last_name':'gaiyan',
    'age':'20',
    'city':'handan',
}
for key in sorted(wanggaiyan.keys()):
    print(key)
    
# 遍历字典中的所有值,使用value()方法,这种方法产生的列表可能包含重复值,如果想要获得独一无二的数,可以使用集合(set),set是不重复的,不以特定顺序存储的集合
wanggaiyan = {
    'first_name':'wang',
    'last_name':'gaiyan',
    'age':'20',
    'city':'handan',
}
for value in wanggaiyan.values():
    print(value)
   
for value in set(wanggaiyan.values()):      # 以set的方式打印
    print(wanggaiyan.title())

练习:

# 练习 6-5
rivers = {
    'huang he':'china',
    'chang jiang':'china',
    'mixixibi':'usa',
}
for river,country in rivers.items():
    print(f"The {river.title()} runs through {country.title()} ")
for river in rivers.keys():
    print(river)
for country in set(rivers.values()):
    print(country)

6.3 字典嵌套

有很多种嵌套方法:字典列表、在字典中存储列表、在字典中存储字典

# 字典列表,如下有很多外星人的信息,一个外星人信息是一个字典,把他们都放到一个列表中
alien_0 = {'color':'green','point':5}
alien_1 = {'color':'yellow','point':10}
alien_2 = {'color':'red','point':15}

aliens = [alien_0,alien_1,alien_2]
for aline in aliens:
    print(aline)
    

# 在字典中存储列表,比如下面披萨里的配料就需要一个列表
pizza = {
    'crust':'thick',
    'toppings':['mushroom','extra cheese'],
}
print(f"You ordered a {pizza['crust']}-crust pizza"
     "with the following toppings:")
for topping in pizza['toppings']:
    print('\t'+topping)
    
# 在字典中存储字典,如下面两个用户使用两个字典装在一个大字典中,请让每个用户的字典具有相同的结构保证内部逻辑不是特别复杂。
users = {
    'gushidexiaohuanghua':{
        'first':'yang',
        'last':'jiaxing',
        'location':'haerbin',
    },
    'haina':{
        'first':'wang',
        'last':'gaiyan',
        'location':'handan',
    },
}

练习:

# 练习6-7
wanggaiyan = {
    'first_name':'wang',
    'last_name':'gaiyan',
    'age':'20',
    'city':'handan',
}
yangjiaxing = {
    'first_name':'yang',
    'last_name':'jiaxing',
    'age':'23',
    'city':'haerbin',
}
people = [wanggaiyan,yangjiaxing]
print(people)

# 练习6-8
pets = []
for pet_num in range(20):
    if(pet_num % 3 == 0):
        new_pet = {"host":"yang","type":'cat'}
    elif(pet_num % 3 == 1):
        new_pet = {"host":"wang","type":"dog"}
    else:
        new_pet = {"host":"zhang","type":'pig'}
    pets.append(new_pet)
for pet in pets:
    print(pet)

第七章 用户输入和while循环

7.1 用户输入

函数input( )让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其赋值给一个变量

name = input("Please enter you name:")     # input括号内的内容用于提示
print(f"\nHello {name}!")
 
# 可以使用+拼接字符串
prompt = “dear mr yang".title()           
prompt+="do you like me : "

name = input(prompt)
print(f"\n Hello,{name}")

# 但是需要注意,input()函数,python会将用户的输入视为字符串,如果遇到输入数字,正常打印是没问题的,但要是当成数字使用就要用int转化
age = input("How old are you? ")
age = int(age)
if age >=18:
    print("you are an adult!")

练习:

# 练习 7-1
car = input("What car do you want to find? ")
print(f"Let me see if I can find you a {car}")

# 练习 7-2
order_people = input("How much people want to order a dinner? ")
if int(order_people) > 8:
    print("we don't have a rest table!")
else :
    print("we have a rest table!")
   
# 练习 7-3
num = input("Please enter a number: ")
if int(num)%10 == 0:
    print("Yes")
else :
    print("No")
    

7.2 while循环

python的while循环也是靠缩进来充当括号的

# 一个简单的while循环
cur_num=1
while cur_num <=5:
    print(cur_num)
    cur_num +=1
   
# 使用一个标志位来控制循环
active = True
while active:
    message = input("please enter a number")
    
    if message == 'quit':
        active = False
    else:
        print(message)
  
# 也有 break 和 continue语句,同c语言

练习:

# 练习 7-4
while True:
    topping = input("please add a toppoing: ")
    if(topping == 'quit'):
        break
    else:
        print(f"I will take {topping} into this pizza! ")
        
# 练习 7-5

  

使用while循环处理列表: for循环遍历比较方便,while循环比较适合修改

# 把列表的元素移动到另一个列表中,使用while循环
word = ['a','b','c']
new_word = []
while word:
    cur_word = new_word.pop()
    print(cur_word)
    new_word.append(cur_word)
   
print('\n')
for wr in new_word:
    print(wr)
    
# 删除为特定值的所有列表元素,因为 remove方法只能一次删除一个
word = ['a','b','c','a','a']
print(word)
while 'a' in word:
    pets.remove('a')
print(word)


# 使用用户输入来填充字典
responses ={}
tag = True
while tag:
    name = input("\n What is your name? ")
    response = input("which mountain would you like to climb someday?")
    
    responses[name] = response
    repeat = input("would you like to let another person respond?")
    if repeat == 'no':
        tag = False
for name,response in  responses.items():
    print(f"{name} would like to climb {response}")
   
    

第八章 函数

8.1 函数以及实参传递

形参、实参等等跟c语言相差无几:

# 一个函数的简单示例:   三个双引号是文档字符串的注释,描述函数是做什么的
def greet_user():
    """显示简单的问候语"""
    print("Hello")
   
greet_user()

# 传递实参的两种方式:
# 1、位置实参,就是之前c语言的方式,实参的位置要对应形参的位置
def pet(animal_type,pet_name):
    """显示宠物信息"""
    print(f"You have a {animal_type},name is {pet_name}")
  
pet('dog','wang gaiyan')

# 2、关键字实参:直接在实参中,将名称和值关联起来,位置不对应也没事
def pet(animal_type,pet_name):
    """显示宠物信息"""
    print(f"You have a {animal_type},name is {pet_name}")
  
pet(pet_name = 'dog',animal_type = 'wang gaiyan')

# 给形参设置默认值,再调用函数时就可以不用提供这种信息。要注意现在的第一个参数还是位置实参

def pet(animal_type,pet_name = 'wang gaiyan'):
    """显示宠物信息"""
    print(f"You have a {animal_type},name is {pet_name}")

    
pet('dog')


练习:

# 练习 8-3
def make_shirt(size,word):
    print(f"The shirt print a {word} with {size} size ")
   
make_shirt('small','I love you')


# 函数的返回值
def get_full_name(first_name,last_name):
    """返回整洁的姓名"""
    full_name = f"{first_name} {last_name}"
    return full_name.title()

player = get_full_name("kobe","bryant")
print(player)

# 让实参变成可选的,如有点人没有中间名,可填可不填,把中间名这个参数放到最后并放上默认值空字符
def get_full_name(first_name,last_name,middle_name =''):
    """返回整洁姓名"""
    if middle_name:
        full_name = f"{first_name} {middle_name} {last_name}"
    else:
        full_name = f"{first_name} {last_name}"
       

player = get_full_name('james','harden')
player = get_full_name('yang','xing','jia')

# 返回字典
def build_person(first_name,last_name):
    """返回一个字典,其中包含有关一个人的信息 """
    person = {'first': first_name, 'last': last_name}
    return person

player = build_person('jame','harden')
print(player)

8.2 列表和函数

# 用列表作为函数的参数

def greet_users(names):
    """向列表中每个用户发出简单的问候"""
    for name in names:
        msg = f"Hello, {name.title()}!"
        print(msg)
        
usernames = ['kobe','yang','wang']
greet_users(usernames)

# 在函数中修改列表,使用列表作为参数的话最终会改变列表的值,就像c中的数组一样

def print_models(unprinted_designs, complete_models):
    """
    模拟打印每个设计,直到没有未打印的设计为止
    打印每个设计后,都将其移到列表complete_models中。
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print(f"Printing model:{current_design}")
        complete_models.append(current_design)


def show_models(completed_models):
    """ 显示打印好的模型 """
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs = ['a','b','c']
completed_models = []

print_models(unprinted_designs, completed_models)
show_models(completed_models)

# 禁止函数修改列表,要想最终不修改列表就要将列表的副本传递给函数:
show_models(completed_models[:])
print_models(unprinted_design[:],completed_models)

# 传递任意数量的实参,参数中的*号会让python创建一个元组,并将收到的参数都放到这个元组中
def make_pizza(*topping):
    """打印顾客点的所有配料"""
    print(toppings)
    
make_pizza('a')
nake_pizza('a','b','c')

# 各种参数结合使用,要注意参数的位置摆放,如*什么的就放后面,放前面不就没完了嘛
def make_pizza(size,*toppings):
    """概述要制作的pizza"""
    print(f"\n Making a {size} pizza with the following toppings:")
    for topping in toppings:
        print(f" - {topping}")
        
     
make_pizza(16,'mushrooms','green peppers')

# 使用任意数量的关键字实参,**会让python创建一个名为 user_info的字典,将收到的名称值对都放到这个字典中

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

user_profile = buile_profile('kobe','byrant',
                            location = 'usa',
                            field = 'player')
print(user_profile)
# 练习 8-9 
word = ['a', 'b', 'c']


def show_messages(text):
    for value in text:
        print(value)


show_messages(word)


8.3 函数模块和起别名

模块是存储函数的独立文件,可将模块导入到主程序中

# pizza.py 这是一个模块
def make_pizza(size,*topping):
    """概述要制作的披萨"""
    print(f"\n Making a {size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f"-{topping}")
        
       
# 这是主程序,和模块文件在一个目录中,导入上面的模块
import pizza

pizza.make_pizza(16,'a')
pizza.make_pizza(12,'green peppers','mushrooms')

# 导入特定的函数:
from pizza import make_pizza

# 也可以引入多个函数: from module_name import function_0,function_1,function_2

# 使用as给函数起别名
from pizza import make_pizza as mp

mp(16,'mushrooms','green peppers')

# 使用as给模块起别名
import pizza as p
p.make_pizza(16,'pepperoni')

# 导入模块中的所有函数,这样导入就不用使用句点表示法了,但不推荐,怕函数太多重名了,所以尽量只导入需要的函数或使用句点表示法
from pizza import *

make_pizza(16,'mushrooms')

第九章 类

9.1 类和方法

简单的类示例:

# 下面第一个方法 __init__(),就是这种特定写法,开头和结尾各有两个下划线,self参数是必不可少的,他是一个指向实例本身的引用,让实例能够访问类中的属性和方法,所以成员方法中都有self这个参数

class Dog:
    """一次模拟小狗的尝试"""
    def __init__(self,name,age):    # 这相当于构造方法,很重要,属性在其中定义
        """初试化属性 name 和 age """
        self.name = name          # 这相当于给成员变量赋值,在python中这叫属性
        self.age = age
    
    def sit(self):
        """ 模拟小狗收到命令时蹲下 """
        print(f"{self.name} is now sitting.")
        
my_dog = Dog('wang gaiyan',6)            # 构造一个对象
print(f"My dog's name is {my_dog.name}")   # 通过对象访问一个属性
my_dog.sit()                                 # 通过对象调用方法


练习:

# 练习 9-1
class Restaurant:
    """ 描述餐馆的营业信息 """
    def __init__(self, restaurant_name, cuisine_type):
        """ 构造方法 """
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
    
    def descibe_restaurant(self):
        """ 描述餐馆的信息"""
        print(f"{restaurant_name} have a {cuisine_type}")
      
    def open_restaurant(self):
        """ 打印开业信息 """
        print("welcome to this restaurant")

kfc = Restaurant("KFC","chicken")
kfc.describe_restaurant()
kfc.open_restaurant()

关于类和属性的一系列操作:

class Car:
    """ 模拟汽车 """
    def __init__(self, make, model, year):
        """ 初始化汽车的属性 """
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0    # 给属性一个默认值

    def get_descriptive_name(self):
        """返回整洁的描述信息"""
        full_name = f"{self.year} {self.make} {self.model}"
        return full_name.title()

    def read_odometer(self):
        """打印汽车里程的消息"""
        print(f"This car has {self.odometer_reading} miles on it.")

    def update_odometer(self,mileage):         # 通过这个方法修改对象的属性
        """
        将里程表读数设置为指定的值
        禁止将里程表读数往回调
        """
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")

    def increment_odometer(self, miles):
        """将里程表读数增加指定的量"""
        self.odometer_reading += miles


my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())           # 修改对象的属性
my_new_car.odometer_reading = 23
my_new_car.read_odometer()

my_used_car = Car('subaru', 'outback', 2015)
my_used_car.update_odometer(23_500)
my_used_car.read_odometer()

my_used_car.increment_odometer(100)
my_used_car.read_odometer()

练习:

 
# 练习 9-4
class Restaurant:
    """ 描述餐馆的营业信息 """

    def __init__(self, restaurant_name, cuisine_type):
        """ 构造方法 """
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
        self.number_served = 0

    def describe_restaurant(self):
        """ 描述餐馆的信息"""
        print(f"{self.restaurant_name} have a {self.cuisine_type},there are {self.number_served} men")

    def open_restaurant(self):
        """ 打印开业信息 """
        print("welcome to this restaurant")


my_restaurant = Restaurant('kfc', 'chicken')
my_restaurant.describe_restaurant()

9.2 继承

# 子类电动车继承上文中的父类(上文省略了)
class ElectricCar(Car):
    """ 电动汽车的独特之处"""
    
    def __init__(self, make, model, year):
        """初始化父类的属性"""
        super().__init__(make, model, year)         # 要调用父类的构造方法,让子类包含这些属性,使用super()
        self.battery_size = 75          # 子类独有的属性
    
    def describe_battery(self):
        """打印一条描述电瓶容量的消息"""
        print(f"This car has a {self.battery_size}-kwh battery ")
        
    def read_odometer(self):            # 重写了父类的方法,相当于java中的覆盖重写,python直接写就完事了
        """重写父类的方法"""
        print(f"This electricCar has {self.odometer_reading} miles on it.")
    
    

9.3 模块导入类和python标准库

from car import Car    # 导入Car类
from car import Car,ElectricCar   # 从一个模块导入多个类
import car   # 导入整个模块
from car import *       # 导入模块中的每个类,不推荐,容易重名

from car import ElectricCar as EC       # 给导入的类起别名




# python标准库,是python自带的,直接引入即可
from random import randint # 随机数函数
randint(1,6)

练习:

# 练习9-13
from random import randint


class Die:
    """ 这是一个模拟骰子的类 """

    def __init__(self):
        """初始化骰子类"""
        self.sides = 6

    def roll_die(self):
        """随机转骰子"""
        print(f"The result of this {self.sides}-sides roll is {randint(1, 6)}")

    
die = Die()
for value in range(1,11):
    die.roll_die()

第十章 文件和异常

10.1 文件操作

文件操作:

# 文件操作, open()把其中的字符串转化为对象,python再把这个对象赋值给file_object,使用open后,python会自己确定什么时候调用close(),你无需关心。 read()方法:读取这个文件的全部内容。


with open('pi_digits.txt') as file_object:  # 在with语句缩进中的,才能进行文件的操作
    contents = file_object.read()
print(contents)        # 想要去除基本空白得调用 rsrip方法

# 文件路径:1、绝对路径:C:/path/to/file  使用斜杠而不是反斜杠,因为反斜杠会涉及转义,python是可以用斜杠的,尽管windows使用的是反斜杠。非要用反斜杠就用两个
# 2、相对路径:text_file/filename.txt   text_file再当前文件夹中

# 逐行读取
filename = 'pi_digits.txt'

with open(filename) as file_object:
    for line in file_object:
        print(line)
        
# 创建一个包含文件隔行内容的列表
filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()    # 把结果返回到一个列表中

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


写入文件和读文件:

# 跟c语言一样,对文件的操作有好几种模式,为open函数的第二个参数,w表示写入模式,会清空原来的内容再写,r为只读模式,不写这个参数也是只读模式,a是附加模式,可以在源文件的基础上加,r+是读写模式

filename = 'pi_digits.txt'

with open(filename, 'w') as file_object:     # 写模式,会清空源文件内容,没有这个文件时会自动创建
    file_object.write("I love Yang Jiaxing")

10.2 异常

# python中的异常和java中的差不多,使用的是 try except 语句,可能出问题的代码放在try中,结果办法放在except中

try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero! ") 
  
# 使用异常的好处太多了,可以处理意想不到的情况,当用户输入意想不到的数据程序出问题时,总不能让用户端报错把,既不美观又有潜在危险,而且程序会无法向后执行,所以可以捕捉异常,并给以温馨提示,程序还能接着往下运行。

# try except else 语言 , else 相当于java中的finally,当try中的没有引发异常的内容会执行else 后续代码
try :
    a = b / c
except ZeroDivisonError:
    print("you can't ...")
else:
    print(a)
    
# 还有读取文件异常
filename = 'pi_digits.txt'
try:
    with open(filename,encoding='utf-8') as f:
        contents = f.read()
except FileNotFoundError:
    print(f"Sorry,an mei zhao dao")
else:
    print('zhao dao le')

    
# 静默失败,如果想发生异常什么都不做的话,在except中使用 pass语句

10.3 存储数据

python中也常用json的格式来进行存储数据:

import json

numbers = [2, 3, 5, 7, 9]

filename = 'numbers.json'
with open(filename, 'w') as f:         # 向json文件中存数据,没有则将自动创建
    json.dump(numbers, f)
    

    # 先来个存入数据的文件,记录第一次用户输入姓名
import json

username = input("What's your name? ")

filename = 'username.json'
with open(filename,'w') as f:
    json.dump(username,f)
    print(f" we will remember you when you come back {username}")
    
# 来个查询的文件,使用了 load 方法查询 json文件:

import json


filename = 'username.json'
with open(filename,'w') as f:
   username = json.load(f)
   print(f"welcome back {username}")

10.4 重构代码

重构代码就是将可以正常运行的代码通过划分为一系列完成具体工作的函数,加以改进

# 这是一个实现问候用户功能的代码,使用了 try except else 语句
import json


def greet_user():
    """ 问候用户,并指出其名字 """
    filename = 'username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        username = input("What is your name?")
        with open(filename, 'w') as f:
            json.dump(username, f)
            print("We will remember you when you come back")
    else:
        print(f"Welcome back {username}")


greet_user()

# 下面将其进行重构,让这个函数的逻辑变得清晰了,拆分开了。

import json

# 只负责或者已经存储了的用户名
def get_stored_username():
    """ 如果存储了用户名,就获取它 """
    filename = 'username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        return None
    else:
        return username

# 只负责获取并存储新的用户名
def get_new_username():
    """提示用户输入用户名"""
    username = input("What's your name? ")
    filename = 'username.json'
    with open(filename, 'w') as f:
        json.dump(username, f)
    return username

# 要么欢迎老用户回来,要么问候新用户
def greet_user():
    """ 问候用户,并指出其名字 """
    username = get_stored_username()
    if username:
        print(f"welcome back,{username}!")
    else:
        username = get_new_username()
        print(f"We'll remember you when you come back,{username}")


greet_user()

第十一章 测试

11.1 测试函数

测试是为了添加新代码时不破坏原来的功能,首先来测试单个函数:

# 在 name_function文件中有这么一个函数,下面增添一个单元测试文件
def get_formatted_name(first, last):
    """生成整洁的姓名"""
    full_name = f"{first} {last}"
    return full_name.title()

# 单元测试文件
import unittest
from name_function import get_formatted_name   # 导入要测试的函数


class NamesTestCase(unittest.TestCase):   # 要继承类 unittst.TestCase
    """测试name_function.py"""

    def test_first_last(self):
        """试试可不可以处理没有中间名的人"""
        formatted_name = get_formatted_name('james', 'harden')
        self.assertEqual(formatted_name, 'James Harden')  # 这是断言,很重的部分,比较结果的,如果成功不做什么,要是失败的话就会报告,断言有很多方法的 


if __name__ == '__main__':  # 涉及测试框架的语句,算是固定写法
    unittest.main()

11.2 测试类

也可以对一个类进行测试:内容差不多,自己回顾书 p 197

第十四章 数据可视化

14.1 绘制简单的图

# 绘制折线图

import matplotlib.pyplot as plt

input_value = [1, 2, 3, 4, 5]   # 没这个就对不上,就变成从0开始的x轴了
squares = [1, 4, 9, 16, 25]

plt.style.use('seaborn')  # 使用主题
fig, ax = plt.subplots()    # 在一张图片里绘制多张表格或图片  fig是前者 ax是后者
ax.plot(input_value, squares, linewidth=3)

# 设置图标标题并给坐标轴加上标签
ax.set_title("平方数", fontsize=24, fontproperties="SimHei")  # 设置黑体,要不无法显示汉字
ax.set_xlabel("值", fontsize=14, fontproperties="SimHei")
ax.set_ylabel("值的平方", fontsize=14, fontproperties="SimHei")

# 设置刻度标记的大小
ax.tick_params(axis='both', labelsize=14)
plt.show()

# 绘制散点图
# 绘制一个点
import matplotlib.pyplot as plt

plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.scatter(2, 4, s=200)  # s是绘制点的尺寸
ax.set_title("平方数", fontsize=24, fontproperties="SimHei")  # 设置黑体,要不无法显示汉字
ax.set_xlabel("值", fontsize=14, fontproperties="SimHei")
ax.set_ylabel("值的平方", fontsize=14, fontproperties="SimHei")
ax.tick_params(axis='both', which='major', labelsize=14)

plt.show()


# 绘制一系列点,得使用两个列表记录xy的值
import matplotlib.pyplot as plt

x_value = [1, 2, 3, 4, 5]
y_value = [1, 4, 9, 16, 25]
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.scatter(x_value, y_value, s=100)
ax.set_title("平方数", fontsize=24, fontproperties="SimHei")  # 设置黑体,要不无法显示汉字
ax.set_xlabel("值", fontsize=14, fontproperties="SimHei")
ax.set_ylabel("值的平方", fontsize=14, fontproperties="SimHei")
ax.tick_params(axis='both', which='major', labelsize=14)

plt.show()

# 自动生成 1000个点

import matplotlib.pyplot as plt

x_values = range(1, 1001)
y_values = [x**2 for x in x_values]
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.scatter(x_values, y_values, c='red', s=10)   # c为修改颜色,也可以使用三元组表示法
ax.set_title("平方数", fontsize=24, fontproperties="SimHei")  # 设置黑体,要不无法显示汉字
ax.set_xlabel("值", fontsize=14, fontproperties="SimHei")
ax.set_ylabel("值的平方", fontsize=14, fontproperties="SimHei")
ax.tick_params(axis='both', which='major', labelsize=14)
ax.axis([0, 1100, 0, 1100000])

plt.show()
# 使用颜色映射:y值大的蓝色深,y值小的蓝色浅

import matplotlib.pyplot as plt

x_values = range(1, 1001)
y_values = [x**2 for x in x_values]
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, s=10)
ax.set_title("平方数", fontsize=24, fontproperties="SimHei")  # 设置黑体,要不无法显示汉字
ax.set_xlabel("值", fontsize=14, fontproperties="SimHei")
ax.set_ylabel("值的平方", fontsize=14, fontproperties="SimHei")
ax.tick_params(axis='both', which='major', labelsize=14)
ax.axis([0, 1100, 0, 1100000])

plt.show()


# 自动保存图表,使用下面这句替换了plt.show()就行

plt.savefig('square_plot.png', bbox_inches='tight')  # 以s。。名称存储, 把多余空白区域剪掉

14.2 随机漫步

# 创建随机漫步类
from random import choice

class RandomWalk:
    """生成随机漫步数据的类"""

    def __init__(self, num_points = 5000):
        """初始化随机漫步的属性"""
        self.num_points = num_points

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

    def fill_walk(self):
        """计算随机漫步包含的所有点。"""
    
        while len(self.x_values) < self.num_points:
            
            # 不断漫步,直到列表达到指定的长度
            x_direction = choice([1, -1])
            x_distance = choice([0, 1, 2, 3, 4])
            x_step = x_direction * x_distance
    
            y_direction = choice([1, -1])
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_direction * y_distance
    
            # 拒绝原地踏步
            if x_step == 0 and y_step == 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)
            
#  多次画图

import matplotlib.pyplot as plt

from RandomWalk import RandomWalk

import matplotlib.pyplot as plt
from RandomWalk import RandomWalk

# 只要程序处于活动状态,就不停的模拟随机漫步
while True:

    # 创建一个RandomWalk实例
    rw = RandomWalk()
    rw.fill_walk()

    # 将所有的点都描绘出来
    plt.style.use('classic')
    fig, ax = plt.subplots()
    point_numbers = range(rw.num_points)
    ax.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues,
               edgecolors='none', s=15)   # 使用蓝色y

    # 突出起点和重点
    ax.scatter(0, 0, c='green', edgecolors='none', s=100)
    ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)
    plt.show()
    keep_running = input("Make another walk? (y/n): ")
    if keep_running == 'n':
        break

14.3 使用plotly掷骰子

from random import randint


class Die:
    """表示一个掷骰子的类"""

    def __init__(self, num_sides=6):
        """骰子默认为6面"""
        self.num_sides = num_sides

    def roll(self):
        """返回一个位于1和骰子面数之间的随机值"""
        return randint(1, self.num_sides)

    
    
from plotly.graph_objs import Bar, Layout
from plotly import offline

from die import Die

# 创建一个D6
die = Die()

# 投掷几次骰子并将结果储存到一个列表中
results = []
for roll_num in range(1000):
    result = die.roll()
    results.append(result)

# 分析结果
frequencies = []
for value in range(1, die.num_sides+1):
    frequency = results.count(value)
    frequencies.append(frequency)

# 对结果进行可视化
x_values = list(range(1, die.num_sides+1))
data = [Bar(x=x_values, y=frequencies)]

x_axis_config = {'title': '结果'}
y_axis_config = {'title': '结果的频率'}
my_layout = Layout(title='投掷一个D6,1000次的结果',
                   xaxis=x_axis_config, yaxis=y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, filename='d6.html')    
    
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值