源自《Python编程:从入门到实践》
作者: Eric Matthes
01 变量和数据类型
1.1 字符串string
字符串大小写
name.lower()
name.upper()
name.title()
在字符串中使用变量
f 字符串
a='amy'
b='li'
c=f'{a} {b}'
>>> print(c)
amy li
f 字符串套用
a='amy'
b='li'
c=f'{a} {b}'
>>> print(f'Hello!{c.title()}')
Hello!Amy Li
制表符或换行符添加空白
>>> print('\tPython')
Python
>>> print('a\nb\nc')
a
b
c
删除空白
a='python '
>>> a.rstrip() #暂时删除
'python'
a.lstrip 左
a.rstrip 右
a.strip 两端
删除前缀
url='http://baidu.com'
>>> url.removeprefix('http://')
'baidu.com'
1.2 数
整数 int 浮点数 float 常量 全大写 多变量赋值 x,y,z=1,2,3
02 列表
2.1 列表简介
访问列表元素
元素索引:从0开始;负数表示从右往左数
A=['a','b','c']
>>> print(A[0]) #从0开始
a
>>> print(A[1].upper())
B
>>> print(A[-1]) #负数表示从右往左数
c
>>> print(f'My name is {A[2]}')
My name is c
修改、添加、删除元素
A.append( '元素' )
A.insert( 索引 , '元素' )
A=['a','b','c']
A[0]='d' #修改 A=['d','b','c']
A.append('e') #末尾添加 A=['d','b','c','e']
A.append(1,'f') #插入元素 A=['d','f','b','c','e']
del A[ 索引 ]
A.pop()
A.pop( 索引 )
A.remove( '元素' )
remove只删除第一个指定的值
A=['a','b','c','d','e']
del A[3] # del语句根据位置删除元素
>>> print(A)
['a','b','c','e']
word=A.pop()
>>> print(A) #A.pop() 弹出末尾元素
['a','b','c']
>>> print(word) #被弹出的元素储存在word中
e
first=A.pop(0)
>>> print(A) #A.pop() 弹出指定位置元素
['b','c']
>>> print(f'The first word is {first}') #被弹出的元素储存在first中
The first word is a
A.remove( 'b' ) #A.remove() 根据值删除元素
>>> print(A)
['c']
管理列表
A.sort() 永久排序
sorted(A) 临时排序
A.reverse() 永久反转列表排序
len(A) 列表长度
cars=['bmw','audi','toyota','subaru']
>>> print(cars.sort())
['audi','bmw','subaru','toyota']
>>> print(cars.sort(reverse=True))
['toyota','subaru','bmw','audi']
cars=['bmw','audi','toyota','subaru']
>>> print(sorted(cars))
['audi','bmw','subaru','toyota']
>>> print(cars)
['bmw','audi','toyota','subaru']
cars=['bmw','audi','toyota','subaru']
>>> print(cars.reverse)
['subaru','toyota','audi','bmw']
2.2 操作列表
遍历列表 for循环
students=['Amy','Eric','Cindy']
for student in students:
print(student)
print(f'{student},You are the best student')
>>>
Amy
Amy,You are the best student
Eric
Eric,You are the best student
Cindy
Cindy,You are the best student
创建数值列表
range(num1,num2)
生成一系列数,从num1到num2,包括num1,但不包括num2
list(range(num1,num2)) 数值列表
for value in range(1,5):
print(value)
>>>
1
2
3
4
>>> print(list(range(2,11,2)))
[2,4,6,8,10]
数值列表统计计算
min()
max()
sum()
digits=[1,2,3,4,5]
>>> min(digits)
1
>>> max(digits)
5
>>> sum(digits)
15
列表推导式
>>> squares=[value**2 for value in range(1,4)]
[1,4,9]
列表切片
students=['Amy','Tom','Cindy','Poppy']
>>> print(students[0:3])
['Amy','Tom','Cindy']
>>> print(students[-3:])
['Tom','Cindy','Poppy']
2.3 元组
元组:不可变的列表
无法修改元组中的元素,但可以给表示元组的变量赋值
dimensions=(200,50)
dimensions[0]=250 #不可修改!!!
dimensions=(400,100) #可以给表示元组的变量赋值
03 if语句
3.1 if-elif-else
cars=['audi','bmw','subaru','toyota']
for car in cars:
if car=='bmw':
print(car.upper())
elif car=='audi':
print(car.title())
else:
print(car)
>>>
Audi
BMW
subaru
toyota
3.2 检验条件
检验多个条件
and:同时满足条件
or:满足其中一个条件
检验特定值是否在列表中
in
not in
3.3 确定列表非空
在if语句中将列表名用作条件表达式时,Python将在列表至少包含一个元素时返回True,在列表为空时返回False
students=[]
if students:
for student in students:
print(f'Adding {student}')
else:
print('There is no student')
>>>
There is no student
04 字典
4.1 使用字典
字典形式
一系列键值对:与键关联的值可以为数 、字符串、列表、字典等任意Python对象
alien={'color':'green','points':5}
>>> alien['color']
green
>>> alien['points']
5
添加/修改 键值对
字典名 [ '键' ] = 值
alien={'color':'green','points':5}
alien['color']='yellow' # 修改
alien['x_position']=0 # 添加
alien['y_position']=25
>>> print(alien)
{'color':'yellow','points':5,'x_position':0,'y_position':25}
删除键值对
del 字典名[ '键' ]
alien={'color':'green','points':5}
del alien['points']
>>> print(alien)
{'color':'green'}
使用 get() 访问值
字典名.get( '指定键' , '当指定键不存在时返回的值' )
alien={'color':'green','speed':'slow'}
point_value=alien.get('point','No point value assigned')
>>> print(point_value)
No point value assigned
4.2 遍历字典
遍历所有键值对
字典名.items()
返回键值对列表
languages={
'Amy':'Python',
'Cindy':'C',
'Eric':'rust',
}
for name,language in languages.items() #items()返回一个键值对列表
print(f"{name}'s language is {language}")
>>>
Amy's language is Python
Cindy's language is C
Eric's language is rust
遍历所有键
字典名.keys()
返回包含所有键的列表
languages={
'Amy':'Python',
'Cindy':'C',
'Eric':'rust',
}
friends=['Amy','Eric']
for name in languages.keys() #keys()返回键列表
print(f"Hi,{name}")
if name in friends:
language=luanguages[name]
print(f'\t{name},I see you love {language}')
>>>
Hi,Amy
Amy,I see you love Python
Hi,Cindy
Hi,Eric
Eric,I see you love rust
按特定顺序遍历所有键
languages={
'Amy':'Python',
'Cindy':'C',
'Eric':'rust',
}
for name in sorted(languages.keys())
print(f"Hi,{name}")
遍历所有值
字典名.values()
languages={
'Amy':'Python',
'Cindy':'C',
'Eric':'rust',
}
for language in languages.values()
print(language)
>>>
Python
C
rust
05 while循环
不断运行,直到指定条件不再满足
5.1 break退出循环
while True:
city=input()
if city=='quit':
break
else:
print(city)
5.2 continue
返回循环开头
number=0
while number<10:
number += 1
if number % 2 =0:
continue
print(number)
>>>
1
3
5
7
9
06 函数
6.1 定义函数
def greet_user(user): #user:形参
print(f'Hello!{user.title()}!')
>>> greet_user('amy') #amy:实参
Hello!Amy!
6.2 传递实参
位置实参
基于实参顺序关联
def pet(type,name):
print('I have a {type}')
print("It's name is {name.title}")
>>> pet('dog','joe')
I have a dog
It's name is Joe
关键字实参
def pet(type,name):
print('I have a {type}')
print("It's name is {name.title}")
>>> pet(type='dog',name='joe')
I have a dog
It's name is Joe
默认值
def pet(name,type='dog'): #默认类型为dog
print('I have a {type}')
print("It's name is {name.title}")
>>> pet(name='joe')
>>> pet('joe') #只给出name,默认type为dog
I have a dog
It's name is Joe
>>> pet(name='joe',type='cat')
>>> pet('joe','cat') #给出name和type,忽略默认值
I have a cat
It's name is Joe
6.3 返回值
返回简单的值
def get_name(first_name,last_name)
full_name=f'{first_name} {last_name}'
return full_name.title()
>>> print(get_name('jimi','liu'))
Jimi Liu
返回字典
def get_person(first_name,last_name)
person={'first':first_name,'last':last_name}
return person
>>>print(get_person('jimi','liu'))
{'first':'jimi','last':'liu'}
结合while循环
def get_person(first_name,last_name)
full_name=f'{first_name} {last_name}'
return full_name.title()
>>>
while True:
print('请输入您的姓名:')
print('输入q随时退出')
f_name=input('first name:')
if f_name=='q':
break
l_name=input('last name:')
if l_name=='q':
break
name=get_person(f_name,l_name)
print('Hello!{name}')
6.4 传递任意数量实参
*形参名 元组
*toppings 创建一个名为toppings的元组,该元组包含函数收到的一系列值
def pizza(size,*toppings):
print('Making a {size}-inch pizza with the following toppings:')
for topping in toppings:
print('- {topping}')
>>> pizza(12,'mushrooms','green peppers','cheese')
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- cheese
**形参名 字典
def profile(first,last,**user_info)
user_info['first_name']=first
user_info['last_name']=last
return user_info
>>> user_profile=profile('jimi','liu',location='Shanghai',field='computer')
>>> print(user_profile)
{'location':'Shanghai','field':'computer','first_name':'jimi','last_name':'liu'}
6.5 将函数储存到模块中
将函数储存在称为模块的独立文件中
再将模块import导入主程序
#创建文件pizza.py
def make_pizza(size,*toppings):
print('Making a {size}-inch pizza with the following toppings:')
for topping in toppings:
print('- {topping}')
#在pizza.py所在目录创建文件making_pizzas.py,导入模块并调用函数
import pizza
pizza.make_pizza(12,'mushrooms','green peppers','cheese')
>>>
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- cheese
导入特定函数:
from module_name import function_name
使用as指定别名:
from module_name import function_name as fn
import module_name as mn
07 类class
面向对象(object)编程 OOP
7.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')
def roll_over(self): #模拟小狗收到命令时打滚
print(f'{self.name} rolled over')
_init_()方法
每当根据类创建新实例时都会运行_init_()
形参self必须位于最前面
以self为前缀的变量可供类中所有方法使用(self.name)
根据类创建实例
my_dog=Dog('peter',6)
print(f"My dog's name is {my_dog.name}")
print(f"My dog is {my_dog.age} years old")
>>>
My dog's name is peter
My dog is 6 years old
调用方法
my_dog=Dog('peter',6)
my_dog.sit()
my_dog.roll_over()
>>>
peter is now sitting
peter rolled over
7.2 使用类和实例
class car:
def _init_(self,make,model,year):
self.make=make
self.model=model
self.year=year
def get_descriptive_name(self):
long_name=f"{self.year} {self.make} {self.model}"
return long_time.title()
my_car=car('audi','a4','2024')
print(my_car.get_descriptive_name())
>>>
2024 Audi A4
默认属性值/修改属性值
直接修改属性的值
class car:
def _init_(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.mile=0 #设定mile默认值为0
def get_descriptive_name(self):
long_name=f"{self.year} {self.make} {self.model}"
return long_time.title()
def get_mile(self):
print(f'This car has {self.mile} miles on it')
my_car=car('audi','a4','2024')
print(my_car.get_descriptive_name())
my_car.mile=23 #直接修改属性的值
my_car.get_mile()
>>>
2024 Audi A4
This car has 23 miles on it
通过方法修改属性的值
class car:
def _init_(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.mile=0 #设定mile默认值为0
def get_descriptive_name(self):
long_name=f"{self.year} {self.make} {self.model}"
return long_time.title()
def get_mile(self):
print(f'This car has {self.mile} miles on it')
def update(self,mileage) #通过方法修改属性的值
self.mile=mileage
my_car=car('audi','a4','2024')
print(my_car.get_descriptive_name())
my_car.update(23)
my_car.get_mile()
>>>
2024 Audi A4
This car has 23 miles on it
通过方法修改属性的值
class car:
def _init_(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.mile=0 #设定mile默认值为0
def get_descriptive_name(self):
long_name=f"{self.year} {self.make} {self.model}"
return long_time.title()
def get_mile(self):
print(f'This car has {self.mile} miles on it')
def update(self,mileage) #通过方法修改属性的值
self.mile=mileage
def adding(self,add)
self.mile+=add
my_car=car('audi','a4','2024')
print(my_car.get_descriptive_name())
my_car.update(23)
my_car.get_mile()
my_car.adding(2)
my_car.get_mile()
>>>
2024 Audi A4
This car has 23 miles on it
This car has 25 miles on it
7.3 继承
子类的_init_()方法
创建ElectricCar作为car的子类,继承car类的所有功能
class car:
def _init_(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.mile=0 #设定mile默认值为0
def get_descriptive_name(self):
long_name=f"{self.year} {self.make} {self.model}"
return long_time.title()
def get_mile(self):
print(f'This car has {self.mile} miles on it')
def update(self,mileage) #通过方法修改属性的值
self.mile=mileage
def adding(self,add)
self.mile+=add
class ElectricCar(car):
def _init_(self,make,model,year):
super()._init_(make,model,year)
my_leaf=ElectricCar('nissan','leaf',2024)
print(my_leaf.get_descriptive_name)
>>>
2024 Nissan Leaf
给子类定义属性和方法
class car:
def _init_(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.mile=0 #设定mile默认值为0
def get_descriptive_name(self):
long_name=f"{self.year} {self.make} {self.model}"
return long_time.title()
def get_mile(self):
print(f'This car has {self.mile} miles on it')
def update(self,mileage) #通过方法修改属性的值
self.mile=mileage
def adding(self,add)
self.mile+=add
class ElectricCar(car):
def _init_(self,make,model,year):
super()._init_(make,model,year)
self.battery=40
def describe_battery(self):
print(f'The car has a {self.battery}-kwh battery')
my_leaf=ElectricCar('nissan','leaf',2024)
print(my_leaf.get_descriptive_name)
my_leaf.describe_battery
>>>
2024 Nissan Leaf
The car has a 40-kwh battery
重写父类中的方法
在子类定义一个与要重写的父类同名的方法,Python会忽略父类方法
将实例用作属性
class car:
def _init_(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.mile=0 #设定mile默认值为0
def get_descriptive_name(self):
long_name=f"{self.year} {self.make} {self.model}"
return long_time.title()
def get_mile(self):
print(f'This car has {self.mile} miles on it')
def update(self,mileage) #通过方法修改属性的值
self.mile=mileage
def adding(self,add)
self.mile+=add
class E_Battery:
def _init_(self,battery=40):
self.battery=battery
def describe_battery(self):
print(f'The car has a {self.battery}-kwh battery')
class ElectricCar(car):
def _init_(self,make,model,year):
super()._init_(make,model,year)
self.battery=E_Battery()
my_leaf=ElectricCar('nissan','leaf',2024)
print(my_leaf.get_descriptive_name)
my_leaf.battery.describe_battery
>>>
2024 Nissan Leaf
The car has a 40-kwh battery
7.4 导入类
将Car、ElectricCar类存储在名为car.py的模块中:
from car import Car,ElectricCar
导入整个模块:
import car
导入模块中所有类:
from car import *
08 文件和异常
8.1 读取文件
读取文件全部内容
from pathlib import Path
path=Path('pi_digits.txt')
contents=path.read_text
print(contents)
pathlib.Path
read_text()
访问文件中各行
from pathlib import Path
path=Path('pi_digits.txt')
contents=path.read_text
lines=contents.splitlines()
for line in lines:
print(line)
8.2 写入文件
写入一行
from pathlib import Path
path=Path('programming.txt')
path.write_text('I love you')
# 只能将字符串写入文本文件
write_text()
写入多行
from pathlib import Path
contents='I Love You\n'
contents+='You Love Me\n'
path=Path('programming.txt')
path.write_text(contents)
8.3 异常
try-except-else-finally
try:正常情况下,程序计划执行的语句
except:程序异常是执行的语句
else:程序无异常即try段代码正常执行后会执行该语句
finally:不管有没有异常,都会执行的语句
8.4 存储数据
使用模块json存储数据,将Python数据结构转换为JSON格式字符串
json.dumps() 和 json.loads()
json.dumps() 存储
from pathlib import Path
import json #导入模块json
numbers=[2,3,5,7,11,13] #创建数值列表
path=Path('numbers.json') #指定将列表存储到哪个文件
contents=json.dumps(numbers) #生成字符串
path.write_text(contents)
json.loads() 读取
from pathlib import Path
import json #导入模块json
path=Path('numbers.json') #指定读取哪个文件
contents=path.read_text()
numbers=json.load(contents)
print(numbers)
09 测试代码
9.1 pytest
pip 安装 pytest
在cmd输入以下指令:
$ python -m pip install --user pytest
同理可安装其他第三方包:将pytest替换为其他第三方包package_name
测试函数
from name_function import get_formatted_name
def test_name:
formatted_name=get_formatted_name('jimi','liu')
assert formatted_name=='Jimi Liu'
测试类
要测试的类
class AnnonymousSurvey:
def _init_(self,question):
self.question=question
self.responses=[]
def show_question(self):
print(self.question)
def store_responses(self,new_response):
self.responses.append(new_response)
def show_results(self):
print('Survery results:')
for response in self.responses:
print(f"-{response}")
from survey import AnnonymousSurvey
question = 'What language did you first learn'
language_survey=AnnonymousSurvey(queation)
language_survey.show_question()
print('输入q随时退出')
while True:
response=input('Language:')
if response=='q':
break
language_survey.store_response(response)
language_survey.show_results()
测试类
from survey import AnnonymousSurvey
def test_store_response():
question = 'What language did you first learn'
language_survey=AnnonymousSurvey(queation)
language_survey.store_responses('English')
assert 'English' in language_survey.responses