第一章 起步
python是解释型语言
pycharm自动对齐代码:ctrl + alt + L
第二章 变量和简单数据类型
值得说的内容太少了:
python的变量应该也是弱类型,不用在前边加数据类型。python语言的包袱非常轻,一句后面不用加 ; 并且字符串单引号和双引号都可以
python也是一个完全面向对象的语言,一切都视为对象。
2.1 变量和字符串
有关字符串的几个方法:
name = "yang jiaxing"
print(name.title())
print(name.upper())
print(name.lower())
first_name = "yang"
last_name = "jiaxing"
full_name = f"{first_name}{last_name}"
print(full_name)
print(f"Hello,{full_name.title()}")
有关删除空白的几个方法:
name = 'yangjiaxing '
real_name = name.rstrip()
print(real_name)
本节练习题:
name = "yangjiaxing"
print(f"hello {name},would you like to learn some python?")
name = "yang jiaxing"
print(name.lower())
print(name.upper())
print(name.title())
name = "yang jiaxing"
print(f'{name} once said,"A person is A person"')
famous_name = "yang jiaxing"
message = f'{famous_name} once said,"A person is A person"'
print(message)
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没有内置的常量,只能取名字的时候取全大写字母,把某个变量视为常量。
print(5+3)
print(10-2)
print(2*4)
print(8/1)
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)
print(subject[0])
print(subject[2].title())
print(f"I like {subject[2].title()} very much")
subject = ['chinese','math','english']
print(subject[-1])
print(subject[-2])
练习题:
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
print(friends)
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.2修改、添加、删除列表元素:
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
friends[0] = 'liu zhaoyang'
print(friends)
friends.append('wang gaiyan')
print(friends)
friends.insert(1,'wang haina')
print(friends)
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
del friends[0]
print(friends)
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
poped_name = friends.pop()
print(friends)
print(poped_name)
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
poped_name = friends.pop(0)
print(f"{poped_name} is a handsome man")
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
friends.remove("yang jiaxing")
print(friends)
练习题
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")
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")
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)
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的排序:
cars = ['bwm','audi','toyota']
cars.sort()
print(cars)
cars.sort(reverse = True)
print(cars)
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))
练习题:
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)
friends = ['yang jiaxing','luo xinjian','hu boyang','wang jingqi']
print(f"总共邀请了{len(friends)} 个朋友")
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循环:
fruits = ['apple','orange','banana']
for fruit in fruits:
print(fruit)
fruits = ['apple','orange','banana']
for fruit in fruits:
print(fruit)
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")
练习:
pizzas = ['a','b','c']
for pizza in pizzas:
print(pizza)
print(f"I like {pizza} pizza")
print("I really love pizza")
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( )可以生成一系列数
for value in range(1,5):
print(value)
numbers = list(range(1,6))
print(numbers)
even_numbers = list(range(2,11,2))
print(even_numbers)
squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(squares)
对数字列表执行简单的统计计算
digits = [1,2,3]
min(digits)
max(digits)
sum(digits)
列表解析:将for循环和创建新元素的代码合并成一行,并自动附加新元素。
squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(squares)
squares = [value**2 for value in range(1,11)]
print(squares)
练习
for num in range(1,21):
print(num)
big_num = [value for value in range(1,1000001)]
print(big_num)
big_num = list(range(1,101))
print(big_num)
big_num = [value for value in range(1,1000001)]
print(max(big_num))
print(min(big_num))
print(sum(big_num))
numbers = []
for value in range(1,21,2):
number = value
numbers.append(number)
print(numbers)
tri_num = []
for value in range(1,11):
num = value **3
tri_num.append(num)
print(tri_num)
tri_num = [value**3 for value in range(1,11)]
print(tri_num)
4.3 切片、拷贝列表
切片: 处理列表中的部分元素
suaige = [‘a’,'b','yangjiaxing','d']
print(suaige[0:3])
suaige = [‘a’,'b','yangjiaxing','d']
print(suaige[1:4])
suaige = ['a','b','yangjiaxing','d']
print(suaige[:4])
print(suaige[2:])
print(suaige(-3:))
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
练习:
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:])
my_foods = ['pizza','apple','banana']
friend_foods = my_foods[:]
my_foods.append('peach')
friend_foods.append('watermelon')
print(my_foods)
print(friend_foods)
略
4.4 元组和代码格式
元组和列表很像,专门用来存储不可变的元素,用()而不是[ ],是一种只读的列表
dimensions = (200,50)
print(dimensions[0])
demensions[0] = 250
for demension in demensions:
print(demension)
demension = (400,100)
foods = ('a','b','c','d','e')
for food in foods:
print(food)
foos = ('e','f')
代码格式设置: 访问python网站搜索PEP 8
第五章 if语句
python里的if语句基本等同于c,不同就是没有大括号得依赖缩进
cars = ['audi','bmw','subaru','toyota']
for car in cars:
if car == 'bwm':
print(car.upper())
print(car)
else:
print(car.title())
word = ['a','b','c','d']
'a' in word
item = 'e'
if item not in word:
print(f"{item} not in the list!")
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',
}
aline_0 = {'color':'green','speed':'slow'}
point_value = aline_0.get('points','No point value assigned')
print(point_value)
练习
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 遍历字典
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',
}
for key in wanggaiyan:
print(key)
for key in wanggaiyan.keys():
print(key)
wanggaiyan = {
'first_name':'wang',
'last_name':'gaiyan',
'age':'20',
'city':'handan',
}
for key in sorted(wanggaiyan.keys()):
print(key)
wanggaiyan = {
'first_name':'wang',
'last_name':'gaiyan',
'age':'20',
'city':'handan',
}
for value in wanggaiyan.values():
print(value)
for value in set(wanggaiyan.values()):
print(wanggaiyan.title())
练习:
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',
},
}
练习:
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)
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:")
print(f"\nHello {name}!")
prompt = “dear mr yang".title()
prompt+="do you like me : "
name = input(prompt)
print(f"\n Hello,{name}")
age = input("How old are you? ")
age = int(age)
if age >=18:
print("you are an adult!")
练习:
car = input("What car do you want to find? ")
print(f"Let me see if I can find you a {car}")
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!")
num = input("Please enter a number: ")
if int(num)%10 == 0:
print("Yes")
else :
print("No")
7.2 while循环
python的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)
练习:
while True:
topping = input("please add a toppoing: ")
if(topping == 'quit'):
break
else:
print(f"I will take {topping} into this pizza! ")
使用while循环处理列表: for循环遍历比较方便,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)
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()
def pet(animal_type,pet_name):
"""显示宠物信息"""
print(f"You have a {animal_type},name is {pet_name}")
pet('dog','wang gaiyan')
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')
练习:
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)
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)
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')
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)
word = ['a', 'b', 'c']
def show_messages(text):
for value in text:
print(value)
show_messages(word)
8.3 函数模块和起别名
模块是存储函数的独立文件,可将模块导入到主程序中
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 pizza import make_pizza as mp
mp(16,'mushrooms','green peppers')
import pizza as p
p.make_pizza(16,'pepperoni')
from pizza import *
make_pizza(16,'mushrooms')
第九章 类
9.1 类和方法
简单的类示例:
class Dog:
"""一次模拟小狗的尝试"""
def __init__(self,name,age):
"""初试化属性 name 和 age """
self.name = name
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()
练习:
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()
练习:
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)
self.battery_size = 75
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print(f"This car has a {self.battery_size}-kwh battery ")
def read_odometer(self):
"""重写父类的方法"""
print(f"This electricCar has {self.odometer_reading} miles on it.")
9.3 模块导入类和python标准库
from car import Car
from car import Car,ElectricCar
import car
from car import *
from car import ElectricCar as EC
from random import randint
randint(1,6)
练习:
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 文件操作
文件操作:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
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())
写入文件和读文件:
filename = 'pi_digits.txt'
with open(filename, 'w') as file_object:
file_object.write("I love Yang Jiaxing")
10.2 异常
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero! ")
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')
10.3 存储数据
python中也常用json的格式来进行存储数据:
import json
numbers = [2, 3, 5, 7, 9]
filename = 'numbers.json'
with open(filename, 'w') as f:
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}")
import json
filename = 'username.json'
with open(filename,'w') as f:
username = json.load(f)
print(f"welcome back {username}")
10.4 重构代码
重构代码就是将可以正常运行的代码通过划分为一系列完成具体工作的函数,加以改进
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 测试函数
测试是为了添加新代码时不破坏原来的功能,首先来测试单个函数:
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):
"""测试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]
squares = [1, 4, 9, 16, 25]
plt.style.use('seaborn')
fig, ax = plt.subplots()
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)
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()
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()
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)
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()
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.savefig('square_plot.png', bbox_inches='tight')
14.2 随机漫步
from random import choice
class RandomWalk:
"""生成随机漫步数据的类"""
def __init__(self, num_points = 5000):
"""初始化随机漫步的属性"""
self.num_points = num_points
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 = 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:
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)
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
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')
|