【笔记】Python编程:从入门到实践(第2版) - 埃里克·马瑟斯

第一部分 基础知识

第1章 安装Python

第2章 变量中存储信息

name = "ada lovelace"
name.title() # 首字母大写的方式显示每个单词
						# Ada Lovelace
print(name.upper()) # 全部大写 ADA LOVELACE
print(name.lower()) # 全部小写 ada lovelace

# 在字符串中插入变量的值,前引号前加上字母f
# f字符串是Python 3.6引入的**
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name)
# ada lovelace

# Python 3.5或更早的版本,需要使用format()方法
full_name = "{} {}".format(first_name, last_name)

print("\tPython") # 制表符\t
# Python
print("Languages:\nPython\nC") # 换行符\n
# Languages:
# Python
# C


favorite_language = ' python '>>> favorite_language.rstrip() # 删除末尾空白
' python'>>> favorite_language.lstrip() # 删除开头空白
'python '>>> favorite_language.strip() # 删除两边空白
'python'

>>> 2 + 3
5
>>> 3 - 2
1
>>> 2 * 3
6
>>> 3 / 2
1.5
# ========================
>>> 3 ** 2
9
>>> 3 ** 3
27
# ========================
>>> 2 + 3*4
14
>>> (2 + 3) * 4    # 使用圆括号来修改运算次序,
20
# ========================
>>> 0.2 + 0.1      # 结果包含的小数位数可能是不确定
0.30000000000000004
# ========================
>>> 4/2            # 任意两个数相除时,结果总是浮点数,
2.0
# ========================下述,只有Python 3.6和更高的版本支持。
# 书写很大的数时,可使用下划线将其中的数字分组,使其更清晰易读:
>>> universe_age = 14_000_000_000
>>> print(universe_age)  # 打印这种使用下划线定义的数时,Python不会打印其中的下划线:
14000000000
# 这是因为存储这种数时,Python会忽略其中的下划线。
# 在Python看来,1000与1_000没什么不同,1_000与10_00也没什么不同。
# ========================
>>> x, y, z = 0, 0, 0   # 同时给多个变量赋值
# ========================
# Python程序员会使用全大写来指出应将某个变量视为常量,其值应始终不变:
MAX_CONNECTIONS = 5000

第3章和第4章 列表、元组

在Python中,用方括号 [ ] 表示列表,并用逗号分隔其中的元素。
索引从0开始
Python通过将索引指定为-1,可让Python返回最后一个列表元素

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
# ['trek', 'cannondale', 'redline', 'specialized']print(bicycles[0]) # 访问列表元素
# trek

print(bicycles[-1])
# specialized
# ========================【1】修改列表元素
❶ motorcycles = ['honda', 'yamaha', 'suzuki'] # 例子1
print(motorcycles)
# ['honda', 'yamaha', 'suzuki']
❷ motorcycles[0] = 'ducati' # 【1】修改列表元素
print(motorcycles)
# ['ducati', 'yamaha', 'suzuki']
# ========================【2】列表中添加元素
motorcycles = ['honda', 'yamaha', 'suzuki'] # 例子2
print(motorcycles)
# ['honda', 'yamaha', 'suzuki']
❶ motorcycles.append('ducati') # 【2.1】列表末尾添加元素
print(motorcycles)
# ['honda', 'yamaha', 'suzuki', 'ducati']
# ========================
motorcycles = ['honda', 'yamaha', 'suzuki']# 例子3
❶ motorcycles.insert(0, 'ducati') #【2.2】列表中插入元素 insert()
print(motorcycles)
# ['ducati', 'honda', 'yamaha', 'suzuki']
# ========================【3】列表中删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']# 例子4
print(motorcycles)
# ['honda', 'yamaha', 'suzuki']del motorcycles[0] # 【3.1】列表中删除(指定元素)用 del
print(motorcycles)
# ['yamaha', 'suzuki']
# ========================
motorcycles.pop() # 删除列表末尾的元素 pop()
motorcycles.pop(0) # 指定要删除元素的索引
motorcycles.remove('ducati')  # 根据值删除元素
# ========================# ========================
cars.sort() # 对列表进行排序(正序)
cars.sort(reverse=True) # 列表按与字母顺序(反序)
sorted(cars) # 按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。
cars.reverse() # 倒着打印列表
len(cars) # 确定列表的长度
# ========================# ========================
❶ magicians = ['alice', 'david', 'carolina']for magician in magicians: # 遍历整个列表print(magician)
# ========================# ========================
for value in range(1, 5):
print(value)
# 1
# 2
# 3
# 4
numbers = list(range(1, 6)) # 使用range()创建数字列表
print(numbers)
# [1, 2, 3, 4, 5]

range(2, 11, 2)
从2开始数,然后不断加2,直到达到或超过终值(11)
[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

输出名单上的最后三名队员,可使用切片players[-3:]

元组

创建一系列不可修改的元素,元组可以满足这种需求。
Python将不能修改的值称为不可变的,而不可变的列表被称为元组
使用( ),而非 [ ] 来标识。

第5章 使用if语句。

cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:if car == 'bmw':
		print(car.upper())
	else:
		print(car.title())>>> car == 'bmw'
True

检查多个条件

>>> age_0 >= 21 and age_1 >= 21
False>>> age_0 >= 21 or age_1 >= 21
True

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

>>> 'mushrooms' in requested_toppings
Trueif user not in banned_users:
	print(f"{user.title()}, you can post a response if you wish.")

if

if-else语句

if age >= 18:
	print("You are old enough to vote!")
	print("Have you registered to vote yet?")
else:
	print("Sorry, you are too young to vote.")
	print("Please register to vote as soon as you turn 18!")

if-elif-else结构

if age < 4:
	print("Your admission cost is $0.")
elif age < 18:
	print("Your admission cost is $25.")
.............
else:
	print("Your admission cost is $40.")

if-elif结构

else是一条包罗万象的语句,只要不满足任何if或elif中的条件测试,其中的代码就会执行。
这可能引入无效甚至恶意的数据。
如果知道最终要测试的条件,应考虑使用一个elif代码块来代替else代码块。

第6章 字典

alien_0 = {'color': 'green', 'points': 5} # 字典
print(alien_0['color']) # 访问字典中的值
print(alien_0['points'])

❶ alien_0['x_position'] = 0 # 添加键值对/修改字典中的值
alien_0 = {} # 创建一个空字典del alien_0['points'] # 删除键值对

# 使用 get() 来访问值
'''第一个参数用于指定键,是必不可少的;
第二个参数为指定的键不存在时要返回的值,'''
point_value = alien_0.get('points', 'No point value assigned.')
print(point_value)

# 遍历所有键值对
user_0 = {
	'username': 'efermi',
	'first': 'enrico',
	'last': 'fermi',
}
for key, value in user_0.items():
	print(f"\nKey: {key}")
	print(f"Value: {value}")

for name, language in favorite_languages.items():
	print(f"{name.title()}'s favorite language is {language.title()}.")

for name in favorite_languages.keys(): # 遍历字典中的所有键
	print(name.title())
for language in favorite_languages.values(): # 遍历字典中的所有值
	print(language.title())

pizza = {
	'crust': 'thick',
	'toppings': ['mushrooms', 'extra cheese'], # 在字典中存储列表
}

users = {
	'aeinstein': {                             # 在字典中存储字典
		'first': 'albert',
		'last': 'einstein',
		'location': 'princeton',
	},
	'mcurie': {
		'first': 'marie',
		'last': 'curie',
		'location': 'paris',
	},
}

第7章 获取输入、while循环

name = input("Please enter your name: ")
print(f"\nHello, {name}!")

height = input("How tall are you, in inches? ")
height = int(height)


求模运算符 %

>>> 4 % 3
1
>>> 5 % 3
2
>>> 6 % 3
0
>>> 7 % 3
1

while循环

使用break退出循环
使用continue…

current_number = 1
while current_number <= 5:
	print(current_number)
	current_number += 1

while True:
	city = input(prompt)
	if city == 'quit':
		break
	else:
		print(f"I'd love to go to {city.title()}!")

第8章 函数

def greet_user(username):
	"""显示简单的问候语。"""
	print(f"Hello, {username.title()}!")
	
greet_user('jesse')


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

传递任意数量的实参

形参名*toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中。函数体内的函数调用print()通过生成输出,证明Python能够处理使用一个值来调用函数的情形,也能处理使用三个值来调用函数的情形。它以类似的方式处理不同的调用。
注意,Python将实参封装到一个元组中,即便函数只收到一个值:

def make_pizza(*toppings):
	"""打印顾客点的所有配料。"""
	print(toppings)
	
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
# ('pepperoni',)
# ('mushrooms', 'green peppers', 'extra cheese')

使用任意数量的关键字实参

形参**user_info中的两个星号让Python创建一个名为user_info的空字典,并将收到的所有名称值对都放到这个字典中。
在这个函数中,可以像访问其他字典那样访问user_info中的名称值对。

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)

导入整个模块

# pizza.py
def make_pizza(size, *toppings):
	"""概述要制作的比萨。"""
	print(f"\nMaking a {size}-inch pizza with the following toppings:")
	for topping in toppings:
		print(f"- {topping}")
		
# making_pizzas.py
import pizza
pizza.make_pizza(16, 'pepperoni')

导入特定的函数

使用 as 给函数指定别名

from module_name import function_name
from module_name import function_name as mp # 使用 as 给函数指定别名
from pizza import * # 导入模块中的所有函数

第9章 类

init() 是一个特殊方法,每当你根据Dog类创建新实例时,Python
都会自动运行它。
包含三个形参:self、name和age。
形参self必不可少,而且必须位于其他形参的前面。

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!")

# 根据类创建实例
my_dog = Dog('Willie', 6) 

my_dog.name #访问属性
my_dog.sit() #调用方法

继承

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):
		long_name = f"{self.year} {self.make} {self.model}"
		return long_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
		
class ElectricCar(Car):
	"""电动汽车的独特之处。"""
	def __init__(self, make, model, year):
		"""初始化父类的属性。"""
		super().__init__(make, model, year) # super() 让能够调用父类的方法。
		my_tesla = ElectricCar('tesla', 'model s', 2019)
		print(my_tesla.get_descriptive_name())
>>> from random import randint
>>> randint(1, 6) # 生成一个位于1和6之间的随机整数
3

第10章 文件、如何处理错误(Python异常)

读取整个文件

with open('pi_digits.txt') as file_object:
	contents = file_object.read()
	
print(contents)

文件路径

Windows系统使用反斜杠(\)

with open('text_files/filename.txt') as file_object:

逐行读取

filename = 'pi_digits.txt'
with open(filename) as file_object:
	for line in file_object:
		print(line)

3.1415926535
8979323846
2643383279

要消除这些多余的空白行,可在函数调用print()中使用rstrip()

filename = 'pi_digits.txt'
with open(filename) as file_object:
	for line in file_object:
		print(line.rstrip())

3.1415926535
8979323846
2643383279

使用文件的内容

filename = 'pi_digits.txt'
with open(filename) as file_object:
	lines = file_object.readlines()

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

第11章 测试

相关推荐

  1. Python编程入门实践3

    2024-06-08 07:42:04       6 阅读
  2. 练习12.5_按键_Python编程入门实践3

    2024-06-08 07:42:04       32 阅读
  3. Python编程:入门实践(第二)

    2024-06-08 07:42:04       27 阅读
  4. 功能开发 -- 向隆·学习任务分解

    2024-06-08 07:42:04       38 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-08 07:42:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-08 07:42:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-08 07:42:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-08 07:42:04       20 阅读

热门阅读

  1. 开源日志分析平台ELK实战应用

    2024-06-08 07:42:04       7 阅读
  2. Mysql基础教程(14):UNION

    2024-06-08 07:42:04       6 阅读
  3. vue3 + vite 中使用 svg-icon 的图标

    2024-06-08 07:42:04       8 阅读
  4. WinRAR安装教程

    2024-06-08 07:42:04       6 阅读
  5. win setup kafka 3.6.2 Step-by-Step Guide

    2024-06-08 07:42:04       10 阅读
  6. 【实用技巧】Unity的InputField组件实用技巧

    2024-06-08 07:42:04       10 阅读
  7. Docker 部署 OCRmyPDF、提取PDF内容

    2024-06-08 07:42:04       9 阅读