Python学习笔记之Python Crash Course

以下内容为Python Crash Course: A Hands-On, Project-Based Introduction to Programming一书的摘录。
此书不需要编程基础,极易上手(对有编程基础的朋友可能过于简单,但代码中仍有许多值得借鉴的地方),代码示例绝大多数为现实生活中鲜活的例子,读来兴味盎然。

目录

  • Zen of Python(python之禅)
  • Chapter 2:变量与简单数据类型
    • 字符串的大小写
    • 字符串中的变量使用
      • 1. F-strings(python 3.6+)
      • 2. format()方法 (python 3.5-)
    • 其他函数
    • 数字相关
      • 整数:指数运算(**)
      • 除法默认返回浮点数
      • 在数字中使用下划线(python 3.6+)
      • 多变量一行内赋值
      • 常量声明:全部大写
    • 关于注释
  • Chapter 3:List
    • 改变,增加,删除元素
      • GET
      • ADD
      • DELETE
    • 组织List
      • 排序
      • 倒序打印
      • 序列长度
  • Chapter 4:Working with Lists
    • for循环
    • 数字序列
      • range
      • min, max, sum
    • 列表解析(List Comprehensions)
    • 对列表中一部分进行操作
    • 复制List
    • 元组(tuples)
  • Chapter 5:If Statements
    • if-elif-else
    • 多条件 - 多if
    • List相关
  • Chapter 6:Dictionaries
    • 一个简单的字典
    • 向字典添加元素
    • 改变键对应的值
    • 删除键值对
    • 包含同类物体的字典
    • 使用get()访问元素值
    • 遍历键/值
      • 遍历所有键值对
      • 遍历键:keys()
      • 遍历值:values()
      • 以特定次序遍历
    • 嵌套(Nesting)
      • 字典嵌套于列表
      • 列表嵌套于字典
      • 字典嵌套于字典
  • Chapter 7:User Input and While Loops
    • 普通字符串输入
    • 数字输入
    • while循环
      • 基础代码
      • while循环用于list和dictionaries
        • 从一个List向另一个List转移元素
        • 将所有特定值从List中删除
        • 将用户输入放入字典
  • Chapter 8:Functions
    • 参数(Arguments)
      • 必备/位置参数(Positional Arguments)
      • 关键字参数(Keyword Arguments)
      • 默认值(Default Values)
    • 返回值(Return Values)
    • List作为参数传递
      • 函数内修改List(Modifying a List in a Function)
    • 传递任意个参数
      • 混用位置参数和任意参数(Mixing Positional and Arbitrary Arguments)
      • 使用任意关键字参数(Using Arbitrary Keyword Arguments)
    • 将函数存储在模块中(Storing Your Functions in Modules)
      • 导入一整个模块(Importing an Entire Module)
      • 导入特定函数(Importing Specific Functions)
      • 用as给函数起别名(Using as to Give a Function an Alias)
      • 用as给模块起别名(Using as to Give a Module an Alias)
      • 导入模块内的所有函数(Importing All Functions in a Module)
    • 风格化函数(Styling Functions)
  • Chapter 9:Classes
    • 类和实例的用法(Working with Classes and Instances)
    • 继承(Inheritance)
    • 导入类(Importing Classes)
      • 导入一个类(Importing a single class)
      • 模块里放多个类(Storing multiple classes in a module)
      • 从一个模块中导入多个类(Importing multiple classes from a module)
      • 导入一整个模块(Importing an entire module)
      • 导入模块里的所有类(Importing all classes from a module)
      • 从一个模块导入另一个模块(Importing a module into a module)
      • 使用别名(Using aliases)

Zen of Python(python之禅)

Python学习笔记之Python Crash Course_第1张图片

Chapter 2:变量与简单数据类型

字符串的大小写

① 首字母大写,其他位置小写:title()函数

message = "i lOVE you"
print(message.title())
运行结果:
I Love You

② 全部大写/小写:upper()和lower()

message = "i lOVE you"
print(message.upper())
print(message.lower())
运行结果:
I LOVE YOU
i love you

字符串中的变量使用

1. F-strings(python 3.6+)

first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name)
print(f"Hello, {full_name.title()}!") #python 3.6
运行结果:
ada lovelace
Hello, Ada Lovelace!

2. format()方法 (python 3.5-)

full_name = "{} {}".format(first_name, last_name)

其他函数

① 除去字符串一侧/两边的whitespace(无法打印的字符:空格,tab,结束符等)

s = ' p ' 
print(len(s.rstrip()))
print(len(s.lstrip()))
print(len(s.strip()))
运行结果:2, 2, 1

数字相关

整数:指数运算(**)

print(2 ** 3)
运行结果:8

除法默认返回浮点数

print(4 / 2)
运行结果:2.0

在数字中使用下划线(python 3.6+)

universe_age = 14_000_000_000
print(universe_age)
运行结果:14000000000

多变量一行内赋值

x, y, z = 0, 0, 0

常量声明:全部大写

MAX_CONNECTIONS = 5000

关于注释

If you don’t have anything specific to write because your programs are too simple at this point, just add your name and the current date at the top of each program file. Then write one sentence describing what the program does.

养成写注释的好习惯,即使程序很简单,也尽量写上自己的名字、日期以及程序的作用。

Chapter 3:List

改变,增加,删除元素

GET

① 取最后一个元素:index = -1(可扩展至index = -2…)

bicycles = ['trek', 'cannnondale', 'redline', 'specialized']
print(bicycles)
print(bicycles[0])
print(bicycles[-1])  #取最后一个元素
message = f"My first bicycle was a {bicycles[0].title()}."
print(message)
运行结果:
['trek', 'cannnondale', 'redline', 'specialized']
trek
specialized
My first bicycle was a Trek.

ADD

① 在list末尾添加元素:append(value)

motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.append('ducati')
print(motorcycles)
运行结果:
['honda', 'yamaha', 'suzuki', 'ducati']

向空的list添加元素:

motorcycles = []

motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')

print(motorcycles)
运行结果:
['honda', 'yamaha', 'suzuki']

② 向list指定位置插入元素:insert(index, value)

motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
运行结果:
['ducati', 'honda', 'yamaha', 'suzuki']

DELETE

① 删除指定位置元素,且不再使用:del

motorcycles = ['honda', 'yamaha', 'suzuki']
del motorcycles[0]
print(motorcycles)
运行结果:
['yamaha', 'suzuki']

② 取出最后一个元素的值并删除:pop()

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

popped_motorcycle = motorcycles.pop()
print(motorcycles)

print(popped_motorcycle)
运行结果:
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki

③ 删除指定位置元素,且需要使用:pop(index)

motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print(f"The first bicycle I owned was a {first_owned.title()}.")
运行结果:
The first bicycle I owned was a Honda.

④ 按值删除元素(不知道下标):remove(value)

motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)

motorcycles.remove('ducati')
print(motorcycles)
运行结果:
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']

注意:remove仅仅移除第一个出现的值元素,如果要确保全部删除,应使用loop。

组织List

排序

以下两种方法均区分大小写。

① permanent sort:sort()(改变原序列)

cars = ['bmw', 'audi', 'toyota', 'subaru']

cars.sort()
print(cars)

cars.sort(reverse=True)		#设置reverse=True逆序排列
print(cars)
运行结果:
['audi', 'bmw', 'subaru', 'toyota']
['toyota', 'subaru', 'bmw', 'audi']

② temporal sort:sorted(list) (不改变原序列)

cars = ['bmw', 'audi', 'toyota', 'subaru']

print("Here is the original list:")
print(cars)

print("\nHere is the sorted list:")
print(sorted(cars))

print("\nHere is the original list again:")
print(cars)
运行结果:	
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']

Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']

Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']

倒序打印

reverse()方法。

cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)

cars.reverse()
print(cars)
运行结果:
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']

序列长度

len()方法。

cars = ['bmw', 'audi', 'toyota', 'subaru']
print(len(cars))
运行结果:
4

Chapter 4:Working with Lists

for循环

magicians = ['alice', 'david', 'carolina']
for magician in magicians:  
	print(f"{magician.title()}, that was a great trick!") 	#intended
	print(f"I can't wait to see your next trick, {magician.title()}.\n")

print("Thank you, everyone. That was a great magic show!")
运行结果:
Alice, that was a great trick!
I can't wait to see your next trick, Alice.

David, that was a great trick!
I can't wait to see your next trick, David.

Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.

Thank you, everyone. That was a great magic show!

数字序列

range

① 连续数字:range(start, end)

for value in range(1, 5):
	print(value)
运行结果:
1
2
3
4	

range(index):单参数从0开始

for value in range(5):
	print(value)
运行结果:
0
1
2
3
4

range(start, end, step):3参数加入步长

for value in range(1, 5, 2):
	print(value)
运行结果:
1
3

② range转list

numbers = list(range(1, 6))
print(numbers)
运行结果:
[1, 2, 3, 4, 5]

③ range的应用:打印平方数

#打印平方数
squares = []

for value in range(1, 11):
	squares.append(value ** 2)

print(squares)
运行结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

min, max, sum

#min, max, sum
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits), max(digits), sum(digits))
运行结果:
0 9 45

列表解析(List Comprehensions)

squares = [value**2 for value in range(1, 11)]
print(squares)
运行结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

对列表中一部分进行操作

players = ['charles', 'martina', 'michael', 'florence', 'eli']

print(players[0:3]) 	#取出前3项
print(players[:3])		#与上述代码结果相同
print(players[2:]) 		#省略第二个下标号,默认一直到最后一项
print(players[-3:])		#取出列表的最后3项
print(players[0:3:2])	#第3个参数,表明步长

#对列表一部分循环操作
print("Here are the first three players on my team:")
for player in players[:3]:
	print(player.title())
运行结果:
['charles', 'martina', 'michael']
['charles', 'martina', 'michael']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']
['charles', 'michael']
Here are the first three players on my team:
Charles
Martina
Michael

复制List

要注意使用[:] slice操作,否则直接赋值将起不到复制出一个新的list的效果。

my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]	#复制整个list

my_foods.append('cannoli')
friend_foods.append('ice cream')

print("My favorite foods are:")
print(my_foods)

print("\nMy friend's favorite foods are:")
print(friend_foods)
运行结果:
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli']

My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']

错误示例:

my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods		#共享同一块存储空间

my_foods.append('cannoli')
friend_foods.append('ice cream')

print("My favorite foods are:")
print(my_foods)

print("\nMy friend's favorite foods are:")
print(friend_foods)
运行结果:
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']

My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']

元组(tuples)

tuples指值不可更改的list(immutable list)。

dimensions = (200, 50)	#tuple使用括号	
print(dimensions[0])	#下标访问
print(dimensions[1])

for dimension in dimensions:	#tuple的循环值访问
	print(dimension)

注意:定义只含一个元素的tuple时要加逗号,如my_t = (200,)

tuple的更改只能通过tuple整体赋值得到。

dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
 	print(dimension)

dimensions = (400, 100)		#整体赋值
print("\nModified dimensions:")
for dimension in dimensions:
	print(dimension)
运行结果:
Original dimensions:
200
50

Modified dimensions:
400
100

Chapter 5:If Statements

部分语法:
① 且:age_0 >= 21 and age_1 >= 21
② 检查元素是否在list中,使用关键词in/not in:
if element in list:
if element not in list:

if-elif-else

age = 12

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.")
运行结果:
Your admission cost is $25.

一个更好的版本:

age = 12

if age < 4:
	price = 0
elif age < 18:
	price = 25
else:
	price = 40

#在此情况下,若需改变输出的text,只需要改动一次
print(f"Your admission cost is ${price}.")

万全之策:不在最后使用else
在有明确的匹配范围时,全程使用elif有以下好处:
1.可读性强;
2.明确的elif可以防止接收恶意值(e.g.在此例子中,age=1_000可以被else接收)

age = 12

if age < 4:
	price = 0
elif age < 18:
	price = 25
elif age >= 18:
	price = 40

#在此情况下,若需改变输出的text,只需要改动一次
print(f"Your admission cost is ${price}.")

多条件 - 多if

requested_toppings = ['mushrooms', 'extra cheese']

if 'mushrooms' in requested_toppings:
	print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
	print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
	print("Adding extra cheese.")

print("\nFinished making your pizza!")
运行结果:
Adding mushrooms.
Adding extra cheese.

Finished making your pizza!

List相关

① 检查list是否非空

requested_toppings = []

if requested_toppings:		#检查list是否非空
	for requested_topping in requested_toppings:
			print(f"Adding {requested_topping}.")
	print("\nFinished making your pizza!")
else:
	print("Are you sure you want a plain pizza?")

② 多List操作

available_toppings = ['mushrooms', 'olives', 'green peppers',
					  'pepperoni', 'pineapple', 'extra cheese']

requested_toppings = ['mushrooms', 'french fries', 'extra cheese']

for requested_topping in requested_toppings:
	if requested_topping in available_toppings:
		print(f"Adding {requested_topping}.")
	else:
		print(f"Sorry, we don't have {requested_topping}.")

print("\nFinished making your pizza!")
运行结果:
Adding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese.

Finished making your pizza!	

Chapter 6:Dictionaries

字典:键值对的集合。

一个简单的字典

alien_0 = {'color': 'green', 'points': 5}

print(alien_0['color'])
print(alien_0['points'])
运行结果:
green
5

向字典添加元素

alien_0 = {'color': 'green', 'points': 5}

#添加两个属性
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

print(alien_0)

改变键对应的值

alien_0 = {'color': 'green'}
print(f"The alien is {alien_0['color']}.")

alien_0['color'] = 'yellow'		#改变value
print(f"The alien is now {alien_0['color']}.")
运行结果:
The alien is green.
The alien is now yellow.
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print(f"Original position: {alien_0['x_position']}")

# Move the alien to the right.
# Determine how far to move the alien based on its current speed.
if alien_0['speed'] == 'slow':
	x_increment = 1
elif alien_0['speed'] == 'medium':
	x_increment = 2
else:
	# This must be a fast alien.
	x_increment = 3

# The new position is the old position plus the increment.
alien_0['x_position'] = alien_0['x_position'] + x_increment

print(f"New position: {alien_0['x_position']}")
运行结果:
Original position: 0
New position: 2

删除键值对

alien_0 = {'color': 'green', 'points': 5}
print(alien_0)

#删除points
del alien_0['points']
print(alien_0)
运行结果:
{'color': 'green', 'points': 5}
{'color': 'green'}

包含同类物体的字典

favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
	}

language = favorite_languages['sarah'].title()
print(f"Sarah's favorite language is {language}.")
运行结果:
Sarah's favorite language is C.

使用get()访问元素值

避免使用[key]方法访问不存在的键值对,导致KeyError。

alien_0 = {'color': 'green', 'speed': 'slow'}

#第2个参数(optional)可以用来存放参数不存在的返回信息,不填写则返回None
point_value = alien_0.get('points', 'No point value assigned.')
print(point_value)
运行结果:
No point value assigned.

遍历键/值

遍历所有键值对

user_0 = {
	'username': 'efermi',
	'first': 'enrico',
	'last': 'fermi',
}

for k, v in user_0.items():	#用.items()取键值对	
	print(f"Key: {k}")
	print(f"Value: {v}\n")
运行结果:
Key: username
Value: efermi

Key: first
Value: enrico

Key: last
Value: fermi		
favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
	}

for name, language in favorite_languages.items():	#用.items()取键值对	
	print(f"{name.title()}'s favorite language is {language.title()}.")
运行结果:
Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.	

遍历键:keys()

favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
	}

for name in favorite_languages.keys():	#用.keys()取键,也可以省略.keys()	
	print(name.title())
运行结果:
Jen
Sarah
Edward
Phil

遍历值:values()

favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
	}

print("The following languages have been mentioned:")
for language in favorite_languages.values():	#遍历value
	print(language.title())
运行结果:
The following languages have been mentioned:
Python
C
Ruby
Python

使用set()可避免重复。

for language in set(favorite_languages.values()):	#遍历value,不重复
	print(language.title())
运行结果:
The following languages have been mentioned:
Python
Ruby
C

set()的定义。

languages = {'python', 'ruby', 'python', 'c'}
print(languages)
运行结果:
{'c', 'ruby', 'python'}

以特定次序遍历

favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
	}

#对键值进行排序
for name in sorted(favorite_languages.keys()):
	print(f"{name.title()}, thank you for taking the poll.")
运行结果:
Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.

嵌套(Nesting)

字典嵌套于列表

alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}

aliens = [alien_0, alien_1, alien_2]

for alien in aliens:
	print(alien)
运行结果:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
# Make an empty list to store aliens.
aliens = []

# Make 30 green aliens.
for alien_number in range(30):
	new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
	aliens.append(new_alien)

# Show the first 5 aliens.
for alien in aliens[:5]:
	print(alien)
print("...")

# Show how many aliens have been created.
print(f"Total number of aliens: {len(aliens)}")
运行结果:
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens: 30

列表嵌套于字典

# Store information about a pizza being ordered.
pizza = {
	'crust': 'thick',
	'toppings': ['mushrooms', 'extra cheese'],
	}

# Summarize the order.
print(f"You ordered a {pizza['crust']}-crust pizza "
	"with the following toppings:")

for topping in pizza['toppings']:
	print("\t" + topping)
运行结果:
You ordered a thick-crust pizza with the following toppings:
	mushrooms
	extra cheese

字典嵌套于字典

#人名缩写+具体信息
#嵌套字典尽量设置结构一致
users = {
	'aeinstein':{
		'first': 'albert',
		'last': 'einstein',
		'location': 'princeton',
	},

	'mcurie':{
		'first': 'marie',
		'last': 'curie',
		'location': 'paris',
	},

}

for username, user_info in users.items():
	print(f"Username: {username}")
	full_name = f"{user_info['first']} {user_info['last']}"
	location = user_info['location']

	print(f"\tFull name: {full_name.title()}")
	print(f"\tLocation: {location.title()}\n")
运行结果:
Username: aeinstein
	Full name: Albert Einstein
	Location: Princeton

Username: mcurie
	Full name: Marie Curie
	Location: Paris

Chapter 7:User Input and While Loops

普通字符串输入

name = input("Please enter your name: ")
print(f"\nHello, {name}!")
运行结果:
Please enter your name: Charlene

Hello, Charlene!
# 提示多于一行
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "

name = input(prompt)
print(f"Hello, {name}!")
运行结果:
If you tell mus who you are, we can personalize the messages you see.
What is your first name? Charlene
Hello, Charlene!	

数字输入

height = input("How tall are you, in inches? ")
height = int(height)	#类型转换

if height >= 48:
	print("\nYou're tall enough to ride!")
else:
	print("\nYou'll be able to ride when you're a little older.")
运行结果:
How tall are you, in inches? 15

You'll be able to ride when you're a little older.

while循环

基础代码

current_number = 1

while current_number <= 5:
	print(current_number)
	current_number += 1
# Letting the user choose when to quit
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."

message = ""
while message != 'quit':
	message = input(prompt)
	print(message)
# using a flag
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."

active = True
while active:
	message = input(prompt)

	if message == 'quit':
		active = False
	else:
		print(message)
# using 'break' to exit a loop
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(enter 'quit' when you are finished.)"

while True:
	city = input(prompt)

	if city == 'quit':
		break
	else:
		print(f"I'd love to go to {city.title()}!")
# using 'continue' in a loop
current_number = 0
while current_number < 10:
	current_number += 1
	if current_number % 2 == 0:
		continue

	print(current_number)

while循环用于list和dictionaries

使用for循环时修改list可能会导致顺序追踪list中元素时(items方法)产生异常。因此,尽量使用while循环。

从一个List向另一个List转移元素
# Start with users that need to be verified,
# and an empty list to hold confirmed users.
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

# Verify each user until there are no more unconfirmed users.
# Move each verified user into the list of confirmed users.
while unconfirmed_users:
	current_user = unconfirmed_users.pop()

	print(f"Verifying user: {current_user.title()}")
	confirmed_users.append(current_user)

# Display all confirmed users.
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
	print(confirmed_user.title())
运行结果:
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

The following users have been confirmed:
Candace
Brian
Alice
将所有特定值从List中删除
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
	pets.remove('cat')

print(pets)
运行结果:
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
将用户输入放入字典
responses = {}

# Set a flag to indicate that polling is active.
polling_active = True

while polling_active:
	# Prompt for the person's name and response.
	name = input("\nWhat is your name? ")
	response = input("Which mountain would you like to climb someday? ")

	# Store the response in the dictionary.
	responses[name] = response

	# Find out if anyone else is going to take the poll.
	repeat = input("Would you like to let another person respond? (yes/ no) ")
	if repeat == 'no':
		polling_active = False

# Polling is complete. Show the results.
print("\n--- Poll Results ---")
for name, response in responses.items():
	print(f"{name} would like to climb {response}.")
运行结果:

What is your name? Charlene`在这里插入代码片`
Which mountain would you like to climb someday? yellow mountain
Would you like to let another person respond? (yes/ no) yes

What is your name? Bob
Which mountain would you like to climb someday? Fuji mountain
Would you like to let another person respond? (yes/ no) no

--- Poll Results ---
Charlene would like to climb yellow mountain.
Bob would like to climb Fuji mountain.

Chapter 8:Functions

使用docstring简述函数功能。

def greet_user():
	"""Display a simple greeting"""		
	print("Hello!")

greet_user()

带参数的函数。

def greet_user(username):
	"""Display a simple greeting"""		
	print(f"Hello, {username.title()}!")

greet_user('jesse')

参数(Arguments)

必备/位置参数(Positional Arguments)

def describe_pet(animal_type, pet_name):
	"""Display information about a pet"""
	print(f"\nI have a {animal_type}.")
	print(f"My {animal_type}'s name is {pet_name.title()}.")

describe_pet('hamster', 'harry')	# The order matters.
运行结果:

I have a hamster.
My hamster's name is Harry.

关键字参数(Keyword Arguments)

def describe_pet(animal_type, pet_name):
	"""Display information about a pet"""
	print(f"\nI have a {animal_type}.")
	print(f"My {animal_type}'s name is {pet_name.title()}.")

describe_pet(animal_type='hamster', pet_name='harry') # The order does not matter.
describe_pet(pet_name='harry', animal_type='hamster') # Equivalent

默认值(Default Values)

# Default values must be placed backwords,
# so that Python can interpret positional arguments correctly.
def describe_pet(pet_name, animal_type='dog'):	
	"""Display information about a pet"""
	print(f"\nI have a {animal_type}.")
	print(f"My {animal_type}'s name is {pet_name.title()}.")

describe_pet(pet_name='willie')

返回值(Return Values)

def get_formatted_name(first_name, last_name):
	"""Return a fill name, neatly formatted"""
	full_name = f"{first_name} {last_name}"
	return full_name.title()

musician = get_formatted_name('jimi', 'hendrix')
print(musician)
运行结果:Jimi Hendrix
def get_formatted_name(first_name, last_name, middle_name=''):	# Making an Argument Optional
	"""Return a fill name, neatly formatted"""
	if middle_name:
		full_name = f"{first_name} {last_name} {middle_name}"
	else:
		full_name = f"{first_name} {last_name}"
	return full_name.title()

musician = get_formatted_name('jimi', 'hendrix')
print(musician)

musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
运行结果:
Jimi Hendrix
John Hooker Lee
def build_person(first_name, last_name, age=None): 	# placeholder
	"""Return a dictionary of information about a person."""
	person = {'first': first_name, 'last': last_name}
	if age:
		person['age'] = age
	return person

musician = build_person('jimi', 'hendrix', age=27)
print(musician)
运行结果:{'first': 'jimi', 'last': 'hendrix', 'age': 27}

List作为参数传递

def greet_users(names):
	"""Print a simple greeting to each user in the list"""
	for name in names:
		msg = f"Hello, {name.title()}!"
		print(msg)

usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
运行结果:
Hello, Hannah!
Hello, Ty!
Hello, Margot!

函数内修改List(Modifying a List in a Function)

List内容被永久改变:
print_models(unprinted_designs, completed_models)
List内容不变:
print_models(unprinted_designs[:], completed_models)

# In function print_models, completed_models(List) changes permanently.
def print_models(unprinted_designs, completed_models):
	"""
	Simulate printing each design, until none are left.
	Move each design to completed_models after printing.
	"""
	while unprinted_designs:
		current_design = unprinted_designs.pop()
		print(f"Printing model: {current_design}")
		completed_models.append(current_design)

def show_completed_models(completed_models):
	"""Show all the models that were printed."""
	print("\nThe following models have been printed:")
	for completed_model in completed_models:
		print(completed_model)

unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []

"""
By using
print_models(unprinted_designs[:], completed_models),
the original list remains intact.
But it is not recommended to avoid excessive time and memory.
"""
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
运行结果:
Printing model: dodecahedron
Printing model: robot pendant
Printing model: phone case

The following models have been printed:
dodecahedron
robot pendant
phone case			

传递任意个参数

*toppings tells python to make an empty tuple called toppings and pack whatever values it receives into this tuple.

def make_pizza(*toppings):
	"""Print the list of toppings that have been requested."""
	print(toppings)

make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
运行结果:
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')
def make_pizza(*toppings):
	"""Summarize the pizza we are about to make"""
	print("\nMaking a pizza with the following toppings:")
	for topping in toppings:
		print(f"- {topping}")

make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
运行结果:

Making a pizza with the following toppings:
- pepperoni

Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

混用位置参数和任意参数(Mixing Positional and Arbitrary Arguments)

函数定义时,Arbitrary Arguments要放在最后。
在匹配参数时,Python总是先匹配 Positional & Keyword Arguments,然后再到Arbitrary Arguments。

def make_pizza(size, *toppings):
	"""Summarize the pizza we are about to make"""
	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')
运行结果:

Making a 16-inch pizza with the following toppings:
- pepperoni

Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

You’ll often see the generic parameter name *args, which collects arbitrary positional arguments like this.

使用任意关键字参数(Using Arbitrary Keyword Arguments)

**user_info tells python to create an empty dictionary called user_info and pack whatever name-value pairs it receives into this dictionary.

def build_profile(first, last, **user_info):
	"""Build a dictionary containing everything we know about a user."""
	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)
运行结果:
{'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}

You’ll often see the parameter name **kwargs used to collect non-specific keyword arguments.

将函数存储在模块中(Storing Your Functions in Modules)

Module是一个独立的.py文件。
将函数存储在另一个文件中,需要时import到主函数即可。

导入一整个模块(Importing an Entire Module)

import整个模块:import module_name
调用模块中的函数:module_name.function_name()

#  pizza.py
def make_pizza(size, *toppings):
	"""Summarize the pizza we are about to make"""
	print(f"\nMaking a {size}-inch pizza with the following toppings:")
	for topping in toppings:
		print(f"- {topping}")
# main.py
import pizza

pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(21, 'mushrooms', 'green peppers', 'extra cheese')

导入特定函数(Importing Specific Functions)

import模块中的某个函数:from module_name import function_name
import模块中的多个函数:from module_name import function0, function1, function2

from pizza import make_pizza

make_pizza(16, 'pepperoni')
make_pizza(21, 'mushrooms', 'green peppers', 'extra cheese')

用as给函数起别名(Using as to Give a Function an Alias)

from module_name import function_name as fn

from pizza import make_pizza as mp

mp(16, 'pepperoni')
mp(21, 'mushrooms', 'green peppers', 'extra cheese')

用as给模块起别名(Using as to Give a Module an Alias)

import module_name as mn

import pizza as p

p.make_pizza(16, 'pepperoni')
p.make_pizza(21, 'mushrooms', 'green peppers', 'extra cheese')

导入模块内的所有函数(Importing All Functions in a Module)

from module_name import *

from pizza import *

make_pizza(16, 'pepperoni')
make_pizza(21, 'mushrooms', 'green peppers', 'extra cheese')

尽量不要使用此方法,因为可能造成module中的函数与主函数重名导致的错误。最好的方法是import你所需的函数。

风格化函数(Styling Functions)

  1. 命名法则:小写字母+下划线
  2. 函数用途用注释标明

Chapter 9:Classes

  1. Python通常用大写字母来命名class.
  2. __init__() 方法在创建实例时自动被调用。
  3. 与实例相关联的每个方法调用都会自动传递self,这是对实例本身的引用。 它使单个实例可以访问类中的属性和方法。
  4. 任何以self.为前缀的变量在所有类方法中均可用,也可被所有类实例调用。
class Dog:		
	"""A simple attempt to model a dog"""

	def __init__(self, name, age):
		"""Initialize name and age attributes."""
		self.name = name
		self.age = age

	def sit(self):
		"""Simulate a dog sitting in response to a command."""
		print(f"{self.name} is now sitting.")

	def roll_over(self):
		"""Simulate rolling over in response to a command."""
		print(f"{self.name} rolled over!")

my_dog = Dog('Willie', 6)

# Accessing attributes
print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")

# Calling methods
my_dog.sit()
my_dog.roll_over()

# Creating mutiple instances
your_dog = Dog('Lucy', 3)

print(f"\nYour dog's name is {your_dog.name}.")
print(f"Your dog is {your_dog.age} years old.")

your_dog.sit()
your_dog.roll_over()
运行结果:
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.
Willie rolled over!

Your dog's name is Lucy.
Your dog is 3 years old.
Lucy is now sitting.
Lucy rolled over!

类和实例的用法(Working with Classes and Instances)

class Car:
	"""A simple attempt to represent a car."""

	def __init__(self, make, model, year):
		"""Initialize attributes to describe a car."""
		self.make = make
		self.model = model
		self.year = year
		self.odometer_reading = 0	# Set a default value for an attribute

	def get_descriptive_name(self):
		"""Return a neatly formatted descriptive name."""
		long_name = f"{self.year} {self.make} {self.model}"
		return long_name.title()

	def read_odometer(self):
		"""Print a statement showing the car's mileage."""
		print(f"This car has {self.odometer_reading} miles on it.")

	def update_odometer(self, mileage):
		"""
		Set the odometer reading to the given value.
		Reject the change if it attempts to roll the odometer back.
		"""
		if mileage >= self.odometer_reading:
			self.odometer_reading = mileage
		else:
			print("You can't roll back an odometer!")

	def increment_odometer(self, miles):
		"""Add the given amount to the odometer reading."""
		self.odometer_reading += miles


my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())

# Modifying an attribute's value
my_new_car.odometer_reading = 23
my_new_car.read_odometer()

# Modifying an attribute's value through a method
my_new_car.update_odometer(20)
my_new_car.read_odometer()

# Incrementing an attribute's value through a method
my_used_car = Car('subaru', 'outback', 2015)
print(my_used_car.get_descriptive_name())

my_used_car.update_odometer(23_500)
my_used_car.read_odometer()

my_used_car.increment_odometer(100)
my_used_car.read_odometer()
运行结果:
2019 Audi A4
This car has 23 miles on it.
You can't roll back an odometer!
This car has 23 miles on it.
2015 Subaru Outback
This car has 23500 miles on it.
This car has 23600 miles on it.

继承(Inheritance)

class Car:
	"""A simple attempt to represent a car."""

	def __init__(self, make, model, year):
		"""Initialize attributes to describe a car."""
		self.make = make
		self.model = model
		self.year = year
		self.odometer_reading = 0	# Set a default value for an attribute

	def get_descriptive_name(self):
		"""Return a neatly formatted descriptive name."""
		long_name = f"{self.year} {self.make} {self.model}"
		return long_name.title()

	def read_odometer(self):
		"""Print a statement showing the car's mileage."""
		print(f"This car has {self.odometer_reading} miles on it.")

	def update_odometer(self, mileage):
		"""
		Set the odometer reading to the given value.
		Reject the change if it attempts to roll the odometer back.
		"""
		if mileage >= self.odometer_reading:
			self.odometer_reading = mileage
		else:
			print("You can't roll back an odometer!")

	def increment_odometer(self, miles):
		"""Add the given amount to the odometer reading."""
		self.odometer_reading += miles


class Battery:
	"""A simple attempt to model a battery for an electric car."""

	def __init__(self, battery_size=75):
		"""Initialize the battery's attributes."""
		self.battery_size = battery_size

	def describe_battery(self):
		"""Print a statement describing the battery size."""
		print(f"This car has a {self.battery_size}-kWh battery.")

	def get_range(self):
		"""Print a statement about the range this battery provides."""
		if self.battery_size == 75:
			range = 260
		elif self.battery_size == 100:
			range = 315

		print(f"This car can go about {range} miles on a full charge.")


class ElectricCar(Car):
	"""Represent aspects of a car, specific to electric vehicles."""

	def __init__(self, make, model, year):
		"""
		Initialize attributes of the parent class.
		Then initialize atrributes specific to an alectric car.
		"""
		super().__init__(make, model, year)
		self.battery = Battery()	# Instances as attributes
	

my_tesla = ElectricCar('tesla', 'model s', 2019)

print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
运行结果:
2019 Tesla Model S
This car has a 75-kWh battery.
This car can go about 260 miles on a full charge.

导入类(Importing Classes)

导入一个类(Importing a single class)

car.py

class Car:
	"""A simple attempt to represent a car."""

	def __init__(self, make, model, year):
		"""Initialize attributes to describe a car."""
		self.make = make
		self.model = model
		self.year = year
		self.odometer_reading = 0	# Set a default value for an attribute

	def get_descriptive_name(self):
		"""Return a neatly formatted descriptive name."""
		long_name = f"{self.year} {self.make} {self.model}"
		return long_name.title()

	def read_odometer(self):
		"""Print a statement showing the car's mileage."""
		print(f"This car has {self.odometer_reading} miles on it.")

	def update_odometer(self, mileage):
		"""
		Set the odometer reading to the given value.
		Reject the change if it attempts to roll the odometer back.
		"""
		if mileage >= self.odometer_reading:
			self.odometer_reading = mileage
		else:
			print("You can't roll back an odometer!")

	def increment_odometer(self, miles):
		"""Add the given amount to the odometer reading."""
		self.odometer_reading += miles

my_car.py

from car import Car 

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()
运行结果:
2019 Audi A4
This car has 23 miles on it.

模块里放多个类(Storing multiple classes in a module)

car.py

class Car:
	--snip--

class Battery:
	--snip--

class ElectricCar(Car):
	--snip--

my_electric_car.py

from car import ElectricCar 

my_tesla = ElectricCar('tesla', 'model s', 2019)

print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
运行结果:
2019 Tesla Model S
This car has a 75-kWh battery.
This car can go about 260 miles on a full charge.

从一个模块中导入多个类(Importing multiple classes from a module)

my_cars.py

from car import Car, ElectricCar 

my_beetle = Car('volkswagen', 'beetle', 2019)
print(my_beetle.get_descriptive_name())

my_tesla = ElectricCar('tesla', 'roadster', 2019)
print(my_tesla.get_descriptive_name())
运行结果:
2019 Volkswagen Beetle
2019 Tesla Roadster

导入一整个模块(Importing an entire module)

my_cars.py

from car 

my_beetle = Car('volkswagen', 'beetle', 2019)
print(my_beetle.get_descriptive_name())

my_tesla = ElectricCar('tesla', 'roadster', 2019)
print(my_tesla.get_descriptive_name())

导入模块里的所有类(Importing all classes from a module)

from module_name import *

不推荐使用这种import方法。
如果需要从一个模块中导入许多类,则最好导入整个模块并使用module_name.ClassName语法。

从一个模块导入另一个模块(Importing a module into a module)

electric_car.py

"""A set of classes that can be used to represent electric cars."""

from car import Car

class Battery:
	---snip---

class ElectricCar:
	---snip---

car.py

"""A class that can be used to represent a car."""

class Car:
	---snip---

my_car.py

from car import Car 
from electric_car import ElectricCar

my_beetle = Car('volkswagen', 'beetle', 2019)
print(my_beetle.get_descriptive_name())

my_tesla = ElectricCar('tesla', 'roadster', 2019)
print(my_tesla.get_descriptive_name())
运行结果:
2019 Volkswagen Beetle
2019 Tesla Roadster

使用别名(Using aliases)

from electric_car import ElectricCar as EC
my_tesla = EC('tesla', 'roadster', 2019)

你可能感兴趣的:(python)