Python语法基础(条件测试、if语句、字典和嵌套)

此篇为Python语法基础的接续篇,便于日后知识点回顾。


四、if语句

在Python中,if 语句让你能够检查程序的当前状态,并据此采取相应的措施。每条if 语句的核心都是一个值为True 或False 的表达式,这种表达式被称为条件测试 。

4.1条件测试

Python根据条件测试的值为True还是False来决定是否执行if语句中的代码。
若条件测试的值为True ,Python就执行紧跟在if 语句后面的代码;
若条件测试的值为False ,Python就忽略这些代码。

#遍历一个列表,将'bmw'大写打印 ,其余以首字母大写方式打印
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
  if car == 'bmw':
    print(car.upper())
  else:
	print(car.title())
#输出结果:
Audi
BMW
Subaru
Toyota

#检查是否相等
>>> car = 'bmw'
>>> car == 'bmw'
True
>>> car = 'audi'
>>> car == 'bmw'
False
#这里的“=”与“==”的含义和C语言中的含义类似。“=”为赋值,“==”为判断是否相等。

#在Python中检查是否相等时区分大小写
>>> car = 'Audi'
>>> car == 'audi'
False
#可将变量的值转换为小写,再进行比较
>>> car = 'Audi'
>>> car.lower() == 'audi'
True
#函数lower()不会修改存储在变量car中的值
>>> car = 'Audi'
>>> car.lower() == 'audi'
True
>>> car
'Audi'

#判断是否不等
animal_pet='cat'
if animal_pet!='dog':
  print("Catch the dog!")
#输出结果
Catch the dog!

Python中的其余判断(<=、>=、>、<)与!=的使用方法类似。

#检查多个条件
#使用and检查多个条件
>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 and age_1 >= 21
False
>>> age_1 = 22
>>> age_0 >= 21 and age_1 >= 21
True
#也可加上括号增强可读性
(age_0 >= 21) and (age_1 >= 21)
#可使用or检查多个条件,用法类似于C语言中的||(或运算),即仅当两个测试都没有通过时,使用or的表达式才为False 。

#可使用关键字in来判断特定的值是否已包含在列表中。
>>> animals=['cat','dog','cow','rabit']
>>> print('cat' in animals)
True
>>> print('snake' in animals)
False

#可使用关键字not in检查特定值是否不包含在列表中
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
	print(user.title() + ", you can post a response if you wish.")
#运行结果:
Marie, you can post a response if you wish.

4.2布尔表达式

布尔表达式为条件测试的别名,与条件表达式一样,布尔表达式的结果要么为True ,要么为False 。
示例如下:

#布尔值通常用于记录条件,如游戏是否正在运行,或用户是否可以编辑网站的特定内容:
game_active = True
can_edit = False

#可自己编写类似的条件测试
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False.")
print(car == 'audi')
#运行结果:
Is car == 'subaru'? I predict True.
True

Is car == 'audi'? I predict False.
False

4.3 If 语句

if 语句有很多种,选择使用哪种取决于需要测试的条件数。在if 语句中,缩进的作用与for 循环中相同。如果测试通过了,将执行if 语句后面所有缩进的代码行,否则将忽略它们。

#简单的if语句
if conditional_test:
	do something
#在if语句后面的代码块中,可根据需要包含任意数量的代码行。
age = 19
if age >= 18:
	print("You are old enough to vote!")
	print("Have you registered to vote yet?")
#运行结果:
You are old enough to vote!
Have you registered to vote yet?

#if-else 语句
#if-else 结构非常适合用于要让Python执行两种操作之一的情形
age = 17
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!")
#输出结果:
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!

#if-elif-else 结构
#Python只执行if-elif-else 结构中的一个代码块。
#依次检查每个条件测试,直到遇到通过了的条件测试。测试通过后,Python将执行紧跟在它后面的代码,并跳过余下的测试。
age = 12
if age < 4:
	print("Your admission cost is $0.")
elif age < 18:
	print("Your admission cost is $5.")
else:
	print("Your admission cost is $10.")
#输出结果:
Your admission cost is $5.

#使用多个elif代码块
age = 12
if age < 4:
	price = 0
elif age < 18:
	price = 5
elif age < 65:
	price = 10
else:
	price = 5
print("Your admission cost is $" + str(price) + ".")

#也可省略else代码块
age = 12
if age < 4:
	price = 0
elif age < 18:
	price = 5
elif age < 65:
	price = 10
elif age >= 65:
	price = 5
print("Your admission cost is $" + str(price) + ".")

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

#测试多个条件
#当检查所有条件时,可使用一系列不包含elif和else代码块的简单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!

综上,若只执行一个代码块,使用if-elif-else结构;若需运行多个代码块,可使用一系列独立的if语句。

4.4使用if 语句处理列表

#检查特殊元素
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
	if requested_topping == 'green peppers':
		print("Sorry, we are out of green peppers right now.")
	else:
		print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
#输出结果:
Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.
Finished making your pizza!

#确定列表非空
requested_toppings = []
if requested_toppings:
	for requested_topping in requested_toppings:
		print("Adding " + requested_topping + ".")
	print("\nFinished making your pizza!")
else:
	print("Are you sure you want a plain pizza?")
#输出结果:
Are you sure you want a plain pizza?

#使用多个列表
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("Adding " + requested_topping + ".")
	else:
		print("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!

在设置 if 语句的格式时,PEP 8(Python Enhancement Proposal,即Python改进提案。PEP 8是最古老的PEP之一)提供的建议是,在诸如== 、>= 和<= 等比较运算符两边各添加一个空格。

五、字典

5.1使用字典

在Python中,字典是一系列键—值对 。每个键都与一个值相关联,可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值。在Python中,字典用放在花括号{} 中的一系列键—值对表示。

#一个简单的字典,存储了有关特定外星人的信息
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
#输出结果
green
5

#访问字典中的值,需依次指定字典名和放在方括号内的键
alien_0 = {'color': 'green'}
print(alien_0['color'])
#输出结果:
green

#字典中可包含任意数量的键—值对
alien_0 = {'color': 'green', 'points': 5}
new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")
#输出结果:
You just earned 5 points!

#添加键——值对
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}
{'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}

#创建空字典
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
#输出结果:
{'color': 'green', 'points': 5}

#修改字典中的值
alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")
#输出结果:
The alien is green.
The alien is now yellow.

#删除键—值对(使用del语句)
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
#输出结果:
{'color': 'green', 'points': 5}
{'color': 'green'}

#由类似对象组成的字典
favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
}
print("Sarah's favorite language is " +
favorite_languages['sarah'].title() +
".")
#输出结果:
Sarah's favorite language is C.

5.2遍历字典

字典可用于以各种方式存储信息,因此有多种遍历字典的方式:可遍历字典的所有键—值对、键或值。

#遍历所有的键—值对(使用方法items())
user_0 = {
	'username': 'efermi',
	'first': 'enrico',
	'last': 'fermi',
}
for key, value in user_0.items():
	print("\nKey: " + key)
	print("Value: " + value)
#输出结果:
Key: last
Value: fermi

Key: first
Value: enrico

Key: username
Value: efermi

#遍历字典中的所有键(使用方法keys())
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():
	print(name.title())
#输出结果:
Jen
Sarah
Phil
Edward

#方法keys()还可用于返回一个包含字典中所有键的列表
favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
}
if 'erin' not in favorite_languages.keys():
	print("Erin, please take our poll!")
#输出结果:
Erin, please take our poll!

#按顺序遍历字典中的所有键(使用函数sorted())
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
print(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.

#遍历字典中的所有值(使用方法values())
favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
}
print("The following languages have been mentioned:")
for language in favorite_languages.values():
	print(language.title())
#输出结果:
The following languages have been mentioned:
Python
C Python
Ruby

#使用集合(set)可剔除重复项
#集合类似于列表,但每个元素都必须是独一无二的
favorite_languages = {
	'jen': 'python',
	'sarah': 'c',
	'edward': 'ruby',
	'phil': 'python',
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
	print(language.title())
#输出结果:
The following languages have been mentioned:
Python
C 
Ruby

5.3嵌套

嵌套是指将一系列字典存储在列表中,或将列表作为值存储在字典中。也可在字典中嵌套字典。

#字典列表(在列表中嵌套字典)
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}

#可搭配range()使用
people=[]
for people_number in range(0,30):
  new_people={'name':'Rick','sex':'male','home':'china'}
  people.append(new_people)

for peopl in people[0:3]:
  if peopl['name']=='Rick':
    peopl['name']='Morty'
    peopl['sex']='famale'
    peopl['home']='America'

for peopl in people[0:5]:
  print(peopl)
print("...")
#输出结果:
{'name':'Morty','sex':'famale','home':'America'}
{'name':'Morty','sex':'famale','home':'America'}
{'name':'Morty','sex':'famale','home':'America'}
{'name':'Rick','sex':'male','home':'china'}
{'name':'Rick','sex':'male','home':'china'}

#在字典中存储列表
favorite_languages = {
	'jen': ['python', 'ruby'],
	'sarah': ['c'],
	'edward': ['ruby', 'go'],
	'phil': ['python', 'haskell'],
	}
for name, languages in favorite_languages.items():
	print("\n" + name.title() + "'s favorite languages are:")
	 for language in languages:
		print("\t" + language.title())
#输出结果:
Jen's favorite languages are:
	Python
	Ruby
	
Sarah's favorite languages are:
	C
	
Phil's favorite languages are:
	Python
	Haskell
	
Edward's favorite languages are:
	Ruby
	Go

#在字典中存储字典
users = {
	'aeinstein': {
	'first': 'albert',
	'last': 'einstein',
	'location': 'princeton',
		},
	'mcurie': {
	'first': 'marie',
	'last': 'curie',
	'location': 'paris',
		},
	}
for username, user_info in users.items():
	print("\nUsername: " + username)
	full_name = user_info['first'] + " " + user_info['last']
	location = user_info['location']
	print("\tFull name: " + full_name.title())
	print("\tLocation: " + location.title())	
#输出结果:
Username: aeinstein
Full name: Albert Einstein
Location: Princeton

Username: mcurie
Full name: Marie Curie
Location: Paris

六、用户输入和while循环

这一部分学习如何接受用户输入,让程序能够对其进行处理;学习如何让程序不断地运行,让用户能够根据需要输入信息,并在程序中使用这些信息。

6.1函数input()

#函数input()让程序暂停运行,等待用户输入一些文本。
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
#输出结果:
Tell me something, and I will repeat it back to you: Hello everyone!
Hello everyone!

#使用函数input() 时,都应指定清晰而易于明白的提示
name = input("Please enter your name: ")
print("Hello, " + name + "!")
#输出结果:
Please enter your name: Eric
Hello, Eric!

#创建多行字符串
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("\nHello, " + name + "!")
#输出结果:
If you tell us who you are, we can personalize the messages you see.
What is your first name? Eric

Hello, Eric!

这个示例演示了一种创建多行字符串的方式。第1行将消息的前半部分存储在变量prompt 中;在第2行中,运算符+= 在存储在prompt 中的字符串末尾附加一个字符串。最终的提示横跨两行,并在问号后面包含一个空格。

#使用int()来获取数值输入
>>> age = input("How old are you? ")
How old are you? 21
>>> age
'21'

#函数int()将数字的字符串表示转换为数值表示
>>> age = input("How old are you? ")
How old are you? 21
>>> age = int(age)
>>> age >= 18
True

6.2求模运算符

#求模运算符(%)将两个数相除并返回余数
>>> 4 % 3
1 
>>> 5 % 3
2
>>> 6 % 3
0 
>>> 7 % 3
1

#可使用求模运算符来判断一个数的奇偶性
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
	print("\nThe number " + str(number) + " is even.")
else:
	print("\nThe number " + str(number) + " is odd.")
#输出结果:
Enter a number, and I'll tell you if it's even or odd: 42

The number 42 is even.

6.3while 循环

for循环用于针对集合中的每个元素都一个代码块,而while循环不断地运行,直到指定的条件不满足为止。

#使用while循环来数数
current_number = 1
while current_number <= 5:
	print(current_number)
	current_number += 1
#输出结果:
1
2
3
4
5
#用户选择何时退出
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)
#输出结果:
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello everyone!
Hello everyone!

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello again.
Hello again.

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit
quit

#使用标志
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)
#输出结果:
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello everyone!
Hello everyone!

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello again.
Hello again.

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit

#使用break退出循环
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("I'd love to go to " + city.title() + "!")
#输出结果:
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) New York
I'd love to go to New York!

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) San Francisco
I'd love to go to San Francisco!

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) quit

在任何Python循环中都可使用break 语句。例如,可使用break 语句来退出遍历列表或字典的for 循环。要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue 语句。

#在循环中使用continue
current_number = 0
while current_number < 10:
	 current_number += 1
	if current_number % 2 == 0:
		continue
	print(current_number)
#输出结果:
1
3
5
7
9

6.4使用while 循环来处理列表和字典

for 循环是一种遍历列表的有效方式,但在for 循环中不应修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while 循环。通过将while 循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看和显示。

# 在列表之间移动元素
# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# 验证每个用户,直到没有未验证用户为止
# 将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:
	current_user = unconfirmed_users.pop()
	print("Verifying user: " + current_user.title())
	confirmed_users.append(current_user)
# 显示所有已验证的用户
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

# 删除包含特定值的所有列表元素
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 = {}
# 设置一个标志,指出调查是否继续
polling_active = True
while polling_active:
# 提示输入被调查者的名字和回答
 	name = input("\nWhat 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? (yes/ no) ")
	if repeat == 'no':
		polling_active = False
# 调查结束,显示结果
print("\n--- Poll Results ---")
 for name, response in responses.items():
	print(name + " would like to climb " + response + ".")
#输出结果:
What is your name? Eric
Which mountain would you like to climb someday? Denali
Would you like to let another person respond? (yes/ no) yes

What is your name? Lynn
Which mountain would you like to climb someday? Devil's Thumb
Would you like to let another person respond? (yes/ no) no

--- Poll Results ---
Lynn would like to climb Devil's Thumb.
Eric would like to climb Denali.

七、函数和类

函数是带名字的代码块,用于完成具体的工作。

7.1定义函数

#使用关键字def定义函数
def greet_user():
	"""显示简单的问候语"""
	print("Hello!")
greet_user()
#用三引号括起的为文档字符串
#输出结果:
Hello!

#向函数传递信息
def greet_user(username):
	"""显示简单的问候语"""
	print("Hello, " + username.title() + "!")
greet_user('jesse')
#输出结果:
Hello, Jesse!

7.2传递实参

鉴于函数定义中可能包含多个形参,因此函数调用中也可能包含多个实参。向函数传递实参的方式很多,可使用位置实参 ,这要求实参的顺序与形参的顺序相同;也可使用关键字实参 ,其中每个实参都由变量名和值组成;还可使用列表和字典。

7.2.1位置实参

调用函数时,Python必须将函数调用中的每个实参都关联到函数定义中的一个形参。为此,最简单的关联方式是基于实参的顺序。这种关联方式被称为位置实参 。

#显示宠物信息
def describe_pet(animal_type, pet_name):
	"""显示宠物的信息"""
	print("\nI have a " + animal_type + ".")
	print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('hamster', 'harry')
#输出结果:
I have a hamster.
My hamster's name is Harry.

#多次调用函数
def describe_pet(animal_type, pet_name):
	"""显示宠物的信息"""
	print("\nI have a " + animal_type + ".")
	print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')
#输出结果:
I have a hamster.
My hamster's name is Harry.

I have a dog.
My dog's name is Willie.

位置实参的顺序很重要,函数调用中实参的顺序与函数定义中形参的顺序应当保持一致。

7.2.2关键字实参

关键字实参 是传递给函数的名称—值对。你直接在实参中将名称和值关联起来了,因此向函数传递实参时不会混淆。关键字实参无需考虑函数调用中的实参顺序,还清楚地指出了函数调用中各个值的用途。

#使用关键字实参来调用describe_pet()
def describe_pet(animal_type, pet_name):
	"""显示宠物的信息"""
	print("\nI have a " + animal_type + ".")
	print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(animal_type='hamster', pet_name='harry')
#以下两种调用方法等效
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster')

7.2.3默认值

def describe_pet(pet_name, animal_type='dog'):
	"""显示宠物的信息"""
	print("\nI have a " + animal_type + ".")
	print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')
#输出结果:
I have a dog.
My dog's name is Willie.

使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的实参。这让Python依然能够正确地解读位置实参。

#等效函数调用
def describe_pet(pet_name, animal_type='dog'):
# 一条名为Willie的小狗
describe_pet('willie')
describe_pet(pet_name='willie')
# 一只名为Harry的仓鼠
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name='harry')

7.3返回值

#返回简单值
def get_formatted_name(first_name, last_name):
	"""返回整洁的姓名"""
	full_name = 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=''):
"""返回整洁的姓名"""
	if middle_name:
		full_name = first_name + ' ' + middle_name + ' ' + last_name
	else:
		full_name = 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 Lee Hooker

#返回字典
def build_person(first_name, last_name):
	"""返回一个字典,其中包含有关一个人的信息"""
	person = {'first': first_name, 'last': last_name}
	return person
musician = build_person('jimi', 'hendrix')
print(musician)
#返回结果:
{'first': 'jimi', 'last': 'hendrix'}

#扩展函数
def build_person(first_name, last_name, age=''):
	"""返回一个字典,其中包含有关一个人的信息"""
	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}

#结合使用函数和while循环
def get_formatted_name(first_name, last_name):
	"""返回整洁的姓名"""
	full_name = first_name + ' ' + last_name
	return full_name.title()
while True:
	print("\nPlease tell me your name:")
	print("(enter 'q' at any time to quit)")
	f_name = input("First name: ")
	if f_name == 'q':
		break
	l_name = input("Last name: ")
	if l_name == 'q':
		break
	formatted_name = get_formatted_name(f_name, l_name)
	print("\nHello, " + formatted_name + "!")
#输出结果:
Please tell me your name:
(enter 'q' at any time to quit)
First name: eric
Last name: matthes

Hello, Eric Matthes!

Please tell me your name:
(enter 'q' at any time to quit)
First name: q

7.4传递列表

将列表传递给函数后,函数就能直接访问其内容。将列表传递给函数后,函数就可对其进行修改。在函数中对这个列表所做的任何修改都是永久性的,因此能够高效地处理大量的数据。

def greet_users(names):
	"""向列表中的每位用户都发出简单的问候"""
	for name in names:
		msg = "Hello, " + name.title() + "!"
		print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
#输出结果:
Hello, Hannah!
Hello, Ty!
Hello, Margot!

# 首先创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
# 模拟打印每个设计,直到没有未打印的设计为止
# 打印每个设计后,都将其移到列表completed_models中
while unprinted_designs:
	current_design = unprinted_designs.pop()
#模拟根据设计制作3D打印模型的过程
	print("Printing model: " + current_design)
	completed_models.append(current_design)
# 显示打印好的所有模型
print("\nThe following models have been printed:")
for completed_model in completed_models:
	print(completed_model)
#输出结果:
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case

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

# 在函数中修改列表
def print_models(unprinted_designs, completed_models):
	"""
	模拟打印每个设计,直到没有未打印的设计为止
	打印每个设计后,都将其移到列表completed_models中
	"""
	while unprinted_designs:
		current_design = unprinted_designs.pop()
# 模拟根据设计制作3D打印模型的过程
		print("Printing model: " + current_design)
		completed_models.append(current_design)
def show_completed_models(completed_models):
	"""显示打印好的所有模型"""
	print("\nThe following models have been printed:")
	for completed_model in completed_models:
		print(completed_model)
		unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
#主程序
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []

print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)

首先创建了一个未打印的设计列表,还创建了一个空列表,用于存储打印好的模型。由于已经定义了两个函数,因此只需调用它们并传入正确的实参即可。接着调用print_models() 并向它传递两个列表;print_models() 模拟打印设计的过程。接下来,调用show_completed_models() ,并将打印好的模型列表传递给它,让其能够指出打印了哪些模型。

7.5禁止函数修改列表

可向函数传递列表的副本而不是原件;这样函数所做的任何修改都只影响副本,而丝毫不影响原件。

#将列表的副本传递给函数
function_name(list_name[:])
#切片表示法[:] 创建列表的副本。
print_models(unprinted_designs[:], completed_models)

这样函数print_models() 依然能够完成其工作,因为它获得了所有未打印的设计的名称,但它使用的是列表unprinted_designs 的副本,而不是列表unprinted_designs 本身。像以前一样,列表completed_models 也将包含打印好的模型的名称,但函数所做的修改不会影响到列表unprinted_designs 。
虽然向函数传递列表的副本可保留原始列表的内容,但除非有充分的理由需要传递副本,否则还是应该将原始列表传递给函数,因为让函数使用现成列表可避免花时间和内存创建副本,从而提高效率,在处理大型列表时尤其如此。

7.6传递任意数量的实参

Python允许函数从调用语句中收集任意数量的实参。

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

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

('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')

也可将上述print语句替换为一个循环:

def make_pizza(*toppings):
	"""概述要制作的比萨"""
	print("\nMaking a pizza with the following toppings:")
	for topping in toppings:
		print("- " + 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
#结合使用位置实参和任意数量实参
def make_pizza(size, *toppings):
	"""概述要制作的比萨"""
	print("\nMaking a " + str(size) +
		"-inch pizza with the following toppings:")
	for topping in toppings:
		print("- " + 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

#使用任意数量的关键字实参
def build_profile(first, last, **user_info):
	"""创建一个字典,其中包含我们知道的有关用户的一切"""
	profile = {}
	profile['first_name'] = first
	profile['last_name'] = last
	for key, value in user_info.items():
		profile[key] = value
	return profile
user_profile = build_profile('albert', 'einstein',
							location='princeton',
							field='physics')
print(user_profile)
#输出结果:
{'first_name': 'albert', 'last_name': 'einstein',
'location': 'princeton', 'field': 'physics'}

编写函数时,可以以各种方式混合使用位置实参、关键字实参和任意数量的实参。

7.7将函数存储在模块中

可将函数存储在被称为模块 的独立文件中,再将模块导入到主程序中。import 语句允许在当前运行的程序文件中使用模块中的代码。

#创建模块
def make_pizza(size, *toppings):
	"""概述要制作的比萨"""
	print("\nMaking a " + str(size) +
	"-inch pizza with the following toppings:")
	for topping in toppings:
		print("- " + topping)
#将文件导入刚创建的模块
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

Python读取这个文件时,代码行import pizza 让Python打开文件pizza.py,并将其中的所有函数都复制到这个程序中。看不到复制的代码是因为这个程序运行时,Python在幕后复制这些代码。咱们只需知道,在making_pizzas.py中,可以使用pizza.py中定义的所有函数。
要调用被导入的模块中的函数,可指定导入的模块的名称pizza 和函数名make_pizza() ,并用句点分隔它们。这些代码的输出与没有导入模块的原始程序相同:

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

#可调用其中任何一个函数
module_name.function_name()

#导入模块中的特定函数
from module_name import function_name
#使用逗号分隔函数名
from module_name import function_0, function_1, function_2
#只导入需要使用的函数
from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

#使用as给函数指定别名(在import 语句中使用)
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
#给函数指定别名的通用语法
from module_name import function_name as fn

#使用as给模块指定别名
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
#给模块指定别名的通用语法
import module_name as mn

#使用星号(*)运算符可导入模块中的所有函数
from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

import 语句中的星号让Python将模块pizza中的每个函数都复制到这个程序文件中。Python可能遇到多个名称相同的函数或变量,进而覆盖函数,而不是分别导入所有的函数。

#给形参指定默认值时,等号两边不应有空格
def function_name(parameter_0, parameter_1='default value')
#函数调用中的关键字实参,等号俩边也不应有空格
function_name(value_0, parameter_1='value')

7.8 类

根据类来创建对象被称为实例化。在Python中,首字母大写的名称指的是类。

#创建Dog类
class Dog():
	"""一次模拟小狗的简单尝试"""
	def __init__(self, name, age):
		"""初始化属性name和age"""
		self.name = name
		self.age = age
	def sit(self):
		"""模拟小狗被命令时蹲下"""
		print(self.name.title() + " is now sitting.")
	def roll_over(self):
		"""模拟小狗被命令时打滚"""
		print(self.name.title() + " rolled over!")

方法__init__()是一个特殊的方法,每当根据Dog 类创建新实例时,Python都会自动运行它。在这个方法的名称中,开头和末尾各有两个下划线,这是一种约定,旨在避免Python默认方法与普通方法发生名称冲突。
这里将方法__init__() 定义成了包含三个形参:self 、name 和age 。在这个方法的定义中,形参self 必不可少,还必须位于其他形参的前面。因为Python调用这个__init__() 方法来创建Dog 实例时,将自动传入实参self 。每个与类相关联的方法调用都自动传递实参self ,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。创建Dog 实例时,Python将调用Dog 类的方法__init__() 。将通过实参向Dog() 传递名字和年龄;self 会自动传递,因此当我们根据Dog 类创建实例时,都只需给最后两个形参(name 和age )提供值。
以self 为前缀的变量都可供类中的所有方法使用,接着还可以通过类的任何实例来访问这些变量。self.name = name 获取存储在形参name 中的值,并将其存储到变量name 中,然后该变量被关联到当前创建的实例。self.age = age 的作用与此类似。像这样可通过实例访问的变量称为属性

7.8.1根据类创建实例

可将类视为有关如何创建实例的说明。Dog 类是一系列说明,让Python知道如何创建表示特定小狗的实例。

#表示特定小狗的实例
class Dog():
	--snip--
	my_dog = Dog('willie', 6)
	print("My dog's name is " + my_dog.name.title() + ".")
	print("My dog is " + str(my_dog.age) + " years old.")

Python使用实参’willie’ 和6 调用Dog 类中的方法__init__() 。方法__init__() 创建一个表示特定小狗的示例,并使用所提供的值来设置属性name 和age 。方法__init__() 并未显式地包含return 语句,但Python自动返回一个表示这条小狗的实例。接着将这个实例存储在变量my_dog 中。在这里,命名约定首字母大写的名称(如Dog )指的是类,而小写的名称(如my_dog )指的是根据类创建的实例。

#访问实例的属性
my_dog.name
#输出有关my_dog 的摘要
My dog's name is Willie.
My dog is 6 years old.

#使用句点表示法来调用类中定义的任何方法
class Dog():
	--snip--
my_dog = Dog('willie', 6)
my_dog.sit()
my_dog.roll_over()
#按命令执行
Willie is now sitting.
Willie rolled over!

#创建多个实例
class Dog():
	--snip--
my_dog = Dog('willie', 6)
your_dog = Dog('lucy', 3)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit()
print("\nYour dog's name is " + your_dog.name.title() + ".")
print("Your dog is " + str(your_dog.age) + " years old.")
your_dog.sit()
#执行结果:
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.

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

7.8.2使用类和实例

#car类
class Car():
	"""一次模拟汽车的简单尝试"""
	def __init__(self, make, model, year):
		"""初始化描述汽车的属性"""
		self.make = make
		self.model = model
		self.year = year
	def get_descriptive_name(self):
		"""返回整洁的描述性信息"""
		long_name = str(self.year) + ' ' + self.make + ' ' + self.model
		return long_name.title()
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())

方法__init__()的第一个形参为self,在这个方法中包含了另外三个形参:make 、model 和year 。方法__init__() 接受这些形参的值,并将它们存储在根据这个类创建的实例的属性中。调用方法get_descriptive_name()后输出:

2016 Audi A4

7.9继承

一个类继承另一个类时,它将自动获得另一个类的所有属性和方法。

#子类的方法__init__()
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 = str(self.year) + ' ' + self.make + ' ' + self.model
		return long_name.title()
	def read_odometer(self):
		print("This car has " + str(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)
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
#输出结果:
2016 Tesla Model S

#给子类定义属性和方法
class Car():
	--snip--
class ElectricCar(Car):
	"""Represent aspects of a car, specific to electric vehicles."""
	def __init__(self, make, model, year):
		"""
		电动汽车的独特之处
		初始化父类的属性,再初始化电动汽车特有的属性
		"""
		super().__init__(make, model, year)
		self.battery_size = 70
	def describe_battery(self):
		"""打印一条描述电瓶容量的消息"""
		print("This car has a " + str(self.battery_size) + "-kWh battery.")
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
#输出结果:
2016 Tesla Model S
This car has a 70-kWh battery.

#重写父类的方法fill_gas_tank()
def ElectricCar(Car):
	--snip--
	def fill_gas_tank():
		"""电动汽车没有油箱"""
		print("This car doesn't need a gas tank!")

#将实例用作属性(将一个Battery实例用作ElectricCar类的一个属性)
class Car():
	--snip--
class Battery():
	"""一次模拟电动汽车电瓶的简单尝试"""
	def __init__(self, battery_size=70):
		"""初始化电瓶的属性"""
		self.battery_size = battery_size
	def describe_battery(self):
		"""打印一条描述电瓶容量的消息"""
		print("This car has a " + str(self.battery_size) + "-kWh battery.")
class ElectricCar(Car):
	"""电动汽车的独特之处"""
	def __init__(self, make, model, year):
		"""
		初始化父类的属性,再初始化电动汽车特有的属性
		"""
		super().__init__(make, model, year)
		self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
#使用电动汽车的属性battery
my_tesla.battery.describe_battery()
#让Python在实例my_tesla 中查找属性battery ,并对存储在该属性中的Battery 实例调用方法describe_battery()
#输出结果:
2016 Tesla Model S
This car has a 70-kWh battery.

7.10导入类

Python允许将类存储在模块中,然后在主程序中导入所需的模块。

#导入单个类
"""一个可用于表示汽车的类"""
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 = str(self.year) + ' ' + self.make + ' ' + self.model
		return long_name.title()
	def read_odometer(self):
		"""打印一条消息,指出汽车的里程"""
		print("This car has " + str(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_car.py,在其中导入Car类并创建其实例:
from car import Car

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

my_new_car.odometer_reading = 23
my_new_car.read_odometer()
#输出结果:
2016 Audi A4
This car has 23 miles on it.

#从一个模块中导入多个类
from car import Car, ElectricCar
my_beetle = Car('volkswagen', 'beetle', 2016)
print(my_beetle.get_descriptive_name())

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

#导入整个模块
import car
my_beetle = car.Car('volkswagen', 'beetle', 2016)
print(my_beetle.get_descriptive_name())
my_tesla = car.ElectricCar('tesla', 'roadster', 2016)
print(my_tesla.get_descriptive_name())

#导入模块中的所有类
from module_name import *

#在一个模块中导入另一个模块(将Car类导入该模块中)
"""一组可用于表示电动汽车的类"""
from car import Car
class Battery():
	--snip--
class ElectricCar(Car):
	--snip--

7.11Python标准库

Python标准库 是一组模块,安装的Python都包含它。你现在对类的工作原理已有大致的了解,可以开始使用其他程序员编写好的模块了。可使用标准库中的任何函数和类,为此只需在程序开头包含一条简单的import 语句。

from collections import OrderedDict

favorite_languages = OrderedDict()

favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'

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

我们首先从模块collections 中导入了OrderedDict 类。接着,我们创建了OrderedDict 类的一个实例,并将其存储到favorite_languages 中。最后遍历favorite_languages输出结果:

Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.

在类中,可使用一个空行来分隔方法;而在模块中,可使用两个空行来分隔类。

可使用模块JSON来存储数据:

  • 将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据;
  • 还可使用JSON在Python程序之间分享数据;
  • JSON数据格式并非Python专用的,可将以JSON格式存储的数据与使用其他编程语言的人分享;
  • JSON(JavaScript Object Notation)格式最初是为JavaScript开发的,但随后成了一种常见格式,被包括Python在内的众多语言采用。

总结

本篇主要浅谈了if语句、条件测试、布尔表达式、字典、嵌套、用户输入、while循环、求模运算符、函数和类等相关基础知识。接下来还余文件和异常、测试代码两部分内容,会在后面的练习项目中加以学习、巩固。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值