第1章 搭建Python编程
第2章 变量和简单数据类型
2.2 变量
变量名能以字母或下划线打头,但不能以数字打头
2.3 字符串
# 其中的引号可以是单引号也可以是双引号
print('我说:“你很厉害"')
print("我说你很厉害")
# 使用方法修改字符串大小写
name = "aBc"
print("name.title()") # 以首字母大写,其他字母小写的方式显示每个单词
print("name.upper()") # 将字符串全部大写
print("name.lower()") # 将字符串全部小写
# 在字符串中使用变量
first_name = "ada"
last_name = "love"
full_name = f"{first_name} {last_name}"
print(full_name)
print(full_name.title()) # 使用f可以同时完成很多任务
# 添加空白
print("这里有:\n\t苹果\n\t香蕉")
# 删除空白
favorite_language = " python "
favorite_language.rstrip() # 删除右边空白
favorite_language.lstrip() # 删除左边空白
favorite_language.strip() # 同时删除两边空白
2.4 数
Python使用两个乘号表示乘方运算 **
书写很大的数时,可使用下划线将其中的数字分组,Python不会打印下划线 14_000_000_000
可以同时给多个变量赋值 x, y, z = 0, 0, 0
Python程序员会使用全大写来指出应将某个变量视为常量 MAX_CONNECTIONS = 5000
第3章 列表简介
3.1 列表定义
# 用方括号[]表示列表
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
# 索引从0开始,可从后往前输出
print(bicycles[1]) # 输出cannondale
print(bicycles[-1]) # 输出specialized
3.2 列表元素
# 修改元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
# 添加元素
motorcycles.append('ducati') # 添加到末尾
motorcycles.insert(0, 'ducati') # 插入到索引0处
# 删除元素
del motorcycles[0] # 删除位置0的列表元素
motorcycles.pop() # 删除列表末尾元素
popped_motorcycles = motorcycles.pop() # 可以记录末尾元素
motorcycles.pop(1) # 可以删除任何位置处的元素
motorcycles.remove('ducati') #删除第一个指定的值
3.3 组织列表
# 使用方法sort()对列表永久排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort() # 按字典序排序
cars.sort(reverse=True) # 逆序
# 使用函数sorted()对列表临时排序
print(sorted(cars))
print(cars) # cars列表元素的排列顺序没有变
# 倒着打印列表
cars.reverse()
print(cars)
# 确定列表的长度
len(cars)
第4章 操作列表
4.3 数值列表
# 使用函数range()
for value in range(1, 5):
print(value) # 输出1到4不包括5
# 使用range()创建数字列表
numbers = list(range(1, 6)) # list()将数组转换为列表
print(numbers) # 输出[1, 2, 3, 4, 5]
even_numbers = list(range(2, 12, 2)) # 从2开始数,然后不断加2
print(even_numbers) # 输出[2, 4, 6, 8, 10]
# 对数值列表执行简单的统计计算
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
min(digits) # 输出0
max(digits) # 输出9
sum(digits) # 输出45
# 列表解析
squares = [value**2 for value in range(1, 7)]
print(squares) # 输出[1, 4, 9, 16, 25, 36]
4.4 列表切片
# 切片
players = ['charcles', 'martina', 'michael', 'florence', 'eli']
print(player[1:3]) # 输出['martina', 'michael']
print(player[:4]) # 输出['charcles', 'martina', 'michael', 'florence']
print(player[2:]) # 输出['michael', 'florence', 'eli']
print(player[-3:]) # 输出['michael', 'florence', 'eli']
# 遍历切片
for player in players[:3]:
print(player.title())
# 复制列表
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:] # 将my_foods的副本赋给friend_food;
friend_foods = my_foods # 不可行,这是将friend_food关联到my_foods
4.5 元组
不能修改值得列表被称为元组,用圆括号来标识 dimensions = (200, 50)
严格地说,元组是由逗号标识得,如果只包含一个元素 my_t = (3,)
可以将一个新元组关联到变量 dimensions = (400, 100)
元组中的元素值是不允许修改的,但我们可以对元组进行连接组合
第5章 if语句
5.4 使用if语句处理列表
# 判断列表是否为空
requested_toppings = []
if reuested_toppings:
print("no")
第6章 字典
6.2 使用字典
字典用防止花括号{ }中得一系列键值对表示 alien_0 = {‘color’: ‘green’, ‘points’: 5}
键和值之间用冒号隔,而键值对之间用逗号隔开
# 添加键值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y.position'] = 25
print(alien_0) # 输出{'color': 'green', 'points': 5, 'x_position': 0, 'y.position': 25}
# 创建一个空字典
alien_0 = {}
alien_0['color'] = green
alien_0['points'] = 5
# 删除键值对
del alien_0['points']
print(alien_0) # 输出{'color': 'green'}
# 另一种书写格式
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python', # 注意最后一个要加,
}
# 使用get()来访问值
point_value = alien_0.get('points', 'No point value assigned.') # 有就获得与之相关联的值
6.3 遍历字典
# 遍历所有键值对
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.item():
print(f"\nKey: {key}")
print(f"Value: {value}")
# 遍历字典中的所有键
for name in favorite_languages.keys():
print(name.title())
for name in favorite_languages:
print(name.title()) # 两种写法都可以
# 按特定顺序遍历字典中的所有键
for name in sorted(favorite_languages.key()):
print(name.title()) # 按字典序顺序排序
# 遍历字典中的所有值
for languages in favorite_languages.value():
print(languages.title())
# 使用集合set
for languages in set(favorite_languages.value()):
print(languages.title()) # 提取favorite_languages.value()中不同的语言
languages = {'python', 'ruby', 'python', 'c'} # 当花括号内没有键值对时,定义的很可能是集合
6.4 嵌套
# 在列表中存储字典
aliens = []
for alien_number in range(30):
new_alien = {'color': 'green', 'point': 5,'speed': 'slow'}
aliens.append(new_alien)
# 在字典中存储列表
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese']
}
for topping in pizza['toppings']:
print("\t" + topping)
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name,languages in favorite_languages.items():
print(f"\n{name.title()}'s favorite languages are:")
for language in languages:
print(f"\t{language.title()}")
# 在字典中存储字典
users = {
'atinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
}
}
for username, user_info in users.items():
print(f"\nUsername: {username}")
print(user_info['first'])
print(user_info['last'])
print(user_info['location'])
第7章 用户输入和while循环
7.1 函数input()
接受一个参数——向用户显示的提示(prompt)后说明 message = input(“Tell me:”)
试图将输入用于数值比较时,可使用函数int() age=int(input(“How old are you?”))
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
第8章 函数
8.1 定义函数
def greet_user(username):
'''显示简单的问候语'''
print(f"Hellow, {username}")
greet_user('jesse')
8.2 传递实参
# 关键字实参
def describe_pet(animal_type, pet_name):
'''显示宠物的信息'''
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name if {pet_name.title()}.")
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster') # 两种方法等效
# 默认值
def describe_pet(pet_name, animal_type='dog'): # 有默认值要写在后面
'''显示宠物的信息'''
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name if {pet_name.title()}.")
describe_pet(pet_name='willie')
8.3 返回值
# 返回字典
def build_person(first_name, last_name, age=None):
'''返回一个字典,其中包含有关一个人的信息'''
person = {'first':first_name, 'last':last_name}
if age:
person['age'] = age
return person
musician = build_person('jimi', 'hendrix', age=27)
print(musician)
8.4 传递链表
# 函数中对列表所作的任何修改都是永久性的
def print_models(unprinted_designs, completed_models): #参数可以和实参不一样
while unprinted_designs:
current_design = unprinted_designs.pop()
print(f"Printing model: {current_design}")
completed_models.append(current_design)
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(u, v)
for complted_model in completed_models:
print(completed_model)
# 禁止函数修改列表
function_name(list_name[:]) # 切片表示法[:]创建列表的副本
print_models(unprinted_designs[:], completed_models)
8.5 传递任意数量的实参
形参名*toppings中的星号让Python创建一个名为toppings的空元组
def make_pizza(size, *toppings):
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
新参**user_info中的两个星号让Python创建一个名为user_info的空字典
def build_profile(first, last, **user_info):
'''创建一个字典,其中包含我们知道的有关用户的一切'''
user_info['first_name'] = first
user_info['last_name'] = lase
return user_info
user_profile = build_profile('albert', 'einstein',
lovation='princeton',
field='physics')
print(user_profile)
8.6 将函数存储在模块中
import语句允许在当前运行的程序文件中使用模块中的代码
模块是扩展名为.py的文件,包含要导入到程序中的代码
# 将8.5第一条代码取名为pizza并除函数make_pizza()部分全删除,在同目录中创建
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# 代码行import pizza让Python打开文件pizza.py,并将其中的所有函数都复制到这个程序中
# 可以使用下面的语法来使用其中任何一个函数 module_name.function_name
# 导入特定的函数
from module_name import function_name
from module_name import function_0, function_1, function_2 # 可以此导入任意数量的函数
# 使用这种语法时,调用函数无需使用句号,调用时只需指定其名称即可
# 使用as给函数指定别名
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
import pizza as p # 给模块指定别名
# 导入模块中的所有函数
from pizza import *
第9章 类
9.1 创建和使用类
# 创建类
class Dog:
'''一次模拟小狗的简单尝试'''
def __init__(self, name, age): # 注意各边都是两个_
# 类中的函数成为方法,每当创建新实例时,Python都会自动运行方法_init_()
self.name = name
self.age = age
# 以self为前缀的变量可供类中的所有方法使用,可通过实例来访问的变量称为属性
def sit(self):
print(f"{self.name} is now sitting.")
def roll_over(self):
print(f"{self.name} rolled over!")
9.2 使用类和实例
# 修改属性的值
my_dog = Dog('audi', 3)
my_dog.age = 23 # 直接修改
class Dog:
---snip---
def update_age(self, age): # 通过方法修改
self.age=age
my_dog.update_age(23)
9.3 继承
# 子类的方法__init__()
class Car: # 父类必须写在子类前面
---snip---
class ElectricCar(Car):
def __init__(self, make, model, year):
# 可在子类中定义一个与要重写的父类方法同名的方法来覆盖这个父类方法
super().__init__(make, model, year) # super()是一个特殊函数,能够调用父类的方法
self.battery_size = 75 # 给子类定义属性和方法
# 将实例用作属性
class Car:
--snip--
class Battery:
def __init__(self, battery_size=75):
self.battery_size = battery_size
def describe_battery(self):
print(f"This car has a {self.battery_sizze}")
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery = Battery() # 将类的一部分提取出来作为一个独立的类
my_tesla = ElectricCar('tesla', 'model s', 2019)
my_tesla.battery.describe_battery() # 让实例my_tesla调用属性battery中的Battery实例调用方法
9.5 Python标准库
# 模块random
from random import randint, choice
randint(1, 6) # 生成一个位于1和6之间的随机整数
players = ['charles', 'martina', 'michael', 'florence', 'eli']
first_up = choice(players) # 将列表或元组作为参数,并随机返回其中的一个元素
第10章 文件和异常
10.1 从文件中读取数据
# 读取整个文件
with open('ca.txt') as file_object: # 这里open()返回的文件对象旨在with代码块内可用
contents = file_object.read()
print(contents.rstrip())
# 文件路径
with open('text_files\filename.txt') as file_object: # 到当前文件夹下的text_files中查找
file_path = '\home\ehmatthes\other_files\text_files\filename.txt' # 绝对文件路径
with open(file_path) as file_object:
# 逐行读取
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()
pi_string = ''
for line in lilnes:
pi_string += line.rstrip()
10.2 写入文件
# 写入空文件
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_objext.write("I love programming.")
读取模式(‘r’)、写入模式(‘w’)、附加模式(‘a’)或读写模式(‘r+’),Python默认只读模式
Python只能将字符串写入文本文件
附加模式将内容附加到文件末尾,而不是覆盖文件原来的内容
10.3 异常
# 使用try-except代码块
try:
print(5/0)
except ZeroDivisionError: # 如果是异常对象
print("You can't divide by zero!")
else: # 使用else代码块
print(answer)
# 处理FileNotFoundError异常
filename = 'alice.txt'
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError: # Python找不到文件时创建的异常
print(f"Sorry, the file {filename} does not exist.")
# 分析文本
def count_words(filename):
--snip--
filenames = ['allice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_words(filename) # 如果其中有文件不存在也不会影响该程序处理其他文件
# 静态失败
try:
--snip--
except FileNotFoundError:
pass # 如果异常Python什么都不做
10.4 存储数据
# 使用json.dump()
# 函数json.dump接受两个实参:要存储的数据和可用于存储数据的文件对象
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json' # 存储到指定扩展名为.json的文件
with open(filename, 'w') as f: # 写入模式打开文件
json.dump(numbers, f) # 使用json.dump()将数字列表存储到文件中
# 使用json.load()
import json
filename = 'numbers.json'
with open(filename) as f:
numbers = json.load(f) # 使用json.load()加载存储在文件中的信息
第11章 测试代码
11.1 测试函数
import unittest # 导入了模块unittest
from name_function import get_formatted_name # 导入了要测试的函数
class NameTextCase(unittest.TestCase): # 创建了一个继承unittest.TestCase的类
'''测试name_function.py'''
def test_first_last_name(self): # 所有以test_打头的方法都将自动运行
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin') # 比较两个字符串是否相同
if __name__ == '__main__': # 特殊变量__name__如果这个文件作为主程序执行它将被设置为__main__
unittest.main()
11.2 测试类
方法 | 用途 |
---|---|
assertEqual(a, b) | 核实a == b |
assertNotEqual(a, b) | 核实 a!=b |
assertTrue(x) | 核实 x 为 True |
assertFalse(x) | 核实 x 为False |
assertIn(item, list) | 核实 item在 list中 |
assertNotIn(item, list) | 核实 item不在list中 |
import unittest
from survey import AnonymousSurvey # 导入要测试的类AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
def test_store_single_response(self):
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.store_response('English')
self.assertIn('English', my_survey.responses)
if __name__ == '__main__':
unittest.main()
# 方法setUp()
# 如果TestCase类中包含了方法setUp(),Python将先运行它
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
def setUp(self):
question = "What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.responses = ['English', 'Spanish', 'Mandarin']
--snip--