第2章 变量和简单数据类型

2.1 运行hello_world.py时发生的情况

print("Hello Python world!")

2.2 变量

message="Hello Python world!"
print(message)
message="Hello Python Crash Course world!"
print(message)

2.3 字符串

2.3.1 使用方法修改字符串的大小写

name='ada lovelace'
print(name.title())
##输出:Ada Lovelace
---------------------
name='Ada Lovelace'
print(name.upper())
print(name.lower())
#ADA LOVELACE
#ada lovelace

2.3.2 合并(拼接)字符串

##拼接
first_name='ada'
last_name='lovelace'
full_name=first_name+" "+last_nameprint(full_name)
#输出为:ada lovelace
-----------------------------------
print("Hello, "+full_name.title()+"!")
#输出为:Hello, Ada Lovelace!
-----------------------------------
message="Hello, "+full_name.title()+"!"
print(message)
#输出为:Hello, Ada Lovelace!

2.3.3 使用制表符或换行符来添加空白

print("Python")
print("\tPython")
#Python
#   Python
------------------
print("Languages:\nPython\nC\nJavaScript")
#Languages:
#Python
#C
#JavaScript
'''
print("Languages:\n\tPython\n\tC\n\tJavaScript")
#Languages:
#   Python
#   C
#   JavaScript

2.3.4 删除空白

favorite_language='python '
favorite_language
favorite_language.rstrip()
favorite_language
#'python'
#'python '
#'python'
--------------------------
favorite_language='python '
favorite_language=favorite_language.rstrip()
favorite_language
#输出为:'python'
--------------------------
favorite_language=' python '
favorite_language.rstrip()
favorite_language.lstrip()
favorite_language.strip()
#输出为:' python'   'python '  'python'

2.4 数字

2.4.1 整数

2 + 3 = 5
3 - 2 = 1
2 * 3 = 6
3 / 2 = 1.5
3 ** 2 = 9
3 ** 3 = 27
10 ** 6 = 1000000
2 + 3 * 4 = 14
(2 + 3) * 4 =20

2.4.2 浮点数

0.1 + 0.1 = 0.2
0.2 + 0.2 = 0.4
2 * 0.1 = 0.2
2 * 0.2 = 0.4

2.4.3 使用函数str()避免类型错误

age=23
message="Happy "+str(age)+"rd Birthday!"
print(message)
Happy 23rd Birthday!

2.5 注释

2.5.1 如何编写注释

#向大家问好
print("Hello Python people!")

2.6 Python之禅

import this
The Zen of Python, by Tim PetersBeautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

第3章 列表简介

3.1 列表是什么

bicycles=['trek','cannondale','redline','specialized']
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']

3.1.1 访问列表元素

bicycles=['trek','cannondale','redline','specialized']
print(bicycles[0])
print(bicycles[0].title())
trek
Trek

3.1.2 索引从0而不是1开始

bicycles=['trek','cannondale','redline','specialized']
print(bicycles[1])
print(bicycles[2])
print(bicycles[3])
print(bicycles[-1])
print(bicycles[-2])
cannondale
redline
specialized
specialized
redline

3.1.3 使用列表中的各个值

bicycles=['trek','cannondale','redline','specialized']
message="My first bicycle was a "+bicycles[0].title()+"."
print(message)
My first bicycle was a Trek.

3.2 修改、添加和删除元素

3.2.1 修改列表元素

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

3.2.2 在列表中添加元素

1.在列表末尾添加元素

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

2.在列表中添加元素

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

3.2.3 从列表中删除元素

1. 使用del语句删除元素

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

2. 使用方法 pop() 删除元素

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

3. 弹出列表中任何位置处的元素

motorcycles=['honda','yamaha','suzuki']
first_owned=motorcycles.pop(0)
print('The first motorcycle I owned was a '+ first_owned.title() + '.')
The first motorcycle I owned was a Honda.

4.根据值删除元素

motorcycles=['honda','yamaha','suzuki','ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']
motorcycles=['honda','yamaha','suzuki','ducati']
print(motorcycles)
too_expensive='ducati'
motorcycles.remove(too_expensive)
print(motorcycles)
print("\nA "+too_expensive.title()+" is too expensive for me.")
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']A Ducati is too expensive for me.

3.3 组织列表

3.3.1 使用方法sort()对列表进行永久性排序

cars=['bmw','audi','toyota','subaru']
cars.sort()
print(cars)
cars=['bmw','audi','toyota','subaru']
cars.sort(reverse=True)
print(cars)
['audi', 'bmw', 'subaru', 'toyota']
['toyota', 'subaru', 'bmw', 'audi']

3.3.2 使用方法sorted()对列表进行临时排序

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:')
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:
['bmw', 'audi', 'toyota', 'subaru']

3.3.3 倒着打印列表

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

3.3.4 确定列表的长度

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

第4章 操作列表

4.1 遍历整个列表

magicians=['alice','david','carolina']
for magician in magicians:print(magician)
alice
david
carolina

4.1.1 深入地研究循环

for magician in magicians:
for cat in cats:
for dog in dogs:
for item in list_of_items:

4.1.2 在for循环中执行更多的操作

magicians=['alice','david','carolina']
for magician in magicians:print(magician.title()+', that was a great trick !')print("I can't wait to see your next trick, "+magician.title()+".\n")
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.

4.1.3 在for循环结束后执行一些操作

magicians=['alice','david','carolina']
for magician in magicians:print(magician.title()+', that was a great trick !')print("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 !

4.2 避免缩进错误

4.3 创建数字列表

4.3.1 使用函数range()

for value in range(1,5):print(value)
print("\n")
for value in range(1,6):print(value)
1
2
3
41
2
3
4
5

4.3.2 使用range()创建数字列表

numbers=list(range(1,6))
print(numbers)
even_numbers=list(range(2,11,2))
print(even_numbers)
print("\n")
squares=[]
for value in range(1,11):square=value**2squares.append(square)print(squares)
print("\n")
squares=[]
for value in range(1,11):squares.append(value**2)print(squares)
[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10][1, 4, 9, 16, 25, 36, 49, 64, 81, 100][1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

4.3.3 对数字列表执行简单的统计计算

digits=[1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))
0
9
45

4.3.4 列表解析

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

4.4 使用列表的一部分

4.4.1 切片

players=['charles','martina','michael','florence','eli']
print(players[0:3])
print(players[1:4])
print(players[:4])
print(players[2:])
print(players[-3:])
['charles', 'martina', 'michael']
['martina', 'michael', 'florence']
['charles', 'martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']

4.4.2 遍历切片

players=['charles','martina','michael','florence','eli']print("Here are the first three players on my team")
for player in players[0:3]:print(player.title())
Here are the first three players on my team
Charles
Martina
Michael

4.4.3 复制列表

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']My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']

4.5 元组

4.5.1 定义元组

dimensions=(200,50)
print(dimensions[0])
print(dimensions[1])
200
50

4.5.2 遍历元组中的所有值

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

4.5.3 修改元组变量

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
50Modified dimensions
400
100

第5章 if语句

5.1 一个简单示例

cars=['audi','bmw','subaru','toyota']
for car in cars:if car=='bmw':print(car.upper())else:print(car.title())
Audi
BMW
Subaru
Toyota

5.2 条件测试

5.2.1 检查是否相等

car='bmw'
print(car=='bmw')car='bmw'
print(car=='audi')
True
False

5.2.2 检查是否相等时不考虑大小写

car='Audi'
print(car=='audi')
car='Audi'
print(car.lower()=='audi')#lower()不改变原变量的值
print(car)
False
True
Audi

5.2.3 检查是否不相等

requested_topping='mushroom'if requested_topping!='anchovies':print("Hold the anchovies")
Hold the anchovies

5.2.4 比较数字

age=18
print(age==18)answer=17
if answer !=42:print("That is not the correct answer.Please try again!")age=19
print(age<21)
print(age<=21)
print(age>21)
print(age>=21)
True
That is not the correct answer.Please try again!
True
True
False
False

5.2.5 检查多个条件

1.使用and检查多个条件

age_0=22
age_1=18
print(age_0>=21 and age_1>=21)age_1=22
print(age_0>=21 and age_1>=21)
False
True

2.使用or检查多个条件

age_0=22
age_1=18
print(age_0>=21 or age_1>=21)age_0=18
print(age_0>=21 or age_1>=21)
True
False

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

requested_toppings=['mushrooms','onions','pineapple']
print('mushrooms' in requested_toppings)
print('pepperoni' in requested_toppings)
True
False

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

banned_user=['andrew','carolina','david']
user='marie'if user not in banned_user:print(user.title()+", you can post a response if you wish")
Marie, you can post a response if you wish

5.2.8 布尔表达式

game_active=True
can_edit=False

5.3 if语句

5.3.1 简单的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 ?

5.3.2 if-else语句

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 !

5.3.3 if-elif-else结构

age=12if age<4:print("Your admission cost is $0.")
elif age < 18:print("Your admission cost is $5.")
else:print("Your admission cost is $10.")age=12
if age<4:price=0
elif age<18:price=5
else:price=10
print("Your admission cost is $"+str(price)+".")
Your admission cost is $5.
Your admission cost is $5.

5.3.4 使用多个elif代码块

age=12
if age<4:price=0
elif age<18:price=5
elif age<65:price=10
else:price=5print("Your admission cost is $"+str(price)+".")
Your admission cost is $5.

5.3.5 省略else代码块

age=12if age<4:price=0
elif age<18:price=5
elif age<65:price=10
elif age>=65:price=5print("Your admission cost is $"+str(price)+".")
Your admission cost is $5.

5.3.6 测试多个条件

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 cheeseFinished making your pizza!

5.4 使用if语句处理列表

5.4.1 检查特殊元素

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 !

5.4.2 确定列表是不是空的

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 ?

5.4.3 使用多个列表

available_toppings=['mushrooms','olives','green peppers','prpperoni','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("We don't have  "+requested_topping + ".")
print("\nFinished making your pizza !")
Adding mushrooms.
We don't have  french fries.
Adding extra cheese.Finished making your pizza !

第6章 字典

6.1 一个简单的字典

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

6.2 使用字典

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

6.2.1 访问字典中的值

alien_0={'color':"green",'points':5}
print(alien_0['color'])
new_points=alien_0['points']
print("You just earned "+str(new_points)+" points")
green
You just earned 5 points

6.2.2 添加键-值对

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, 'x_position': 0, 'y_position': 25}

6.2.3 先创建一个空字典

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

6.2.4 修改字典中的值

alien_0={'color':'green'}
print("The alien is "+ alien_0['color'] +".")alien_0={'color':'yellow'}
print("The alien is now "+ alien_0['color'] +".")alien_0={'x_position':0,'y_position':25,'speed':'medium'}
print("Original x-position: "+str(alien_0['x_position']))#向右移动外星人
#据外星人当前速度决定将其移动多远
if alien_0['speed']=='slow':x_increment=1
elif alien_0['speed']=='medium':x_increment=2
else:# 这个外星人的速度一定很快x_increment=3
# 新位置等于老位置加上增量
alien_0['x_position']=alien_0['x_position']+x_increment
print("New x_position: "+str(alien_0['x_position']))
The alien is green.
The alien is now yellow.
Original x-position: 0
New x_position: 2

6.2.5 删除键-值对

alien_0={'color':"green",'points':5}
print(alien_0)del alien_0['points']
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green'}

6.2.6 由类似对象组成的字典

favorite_languages={'jen':'python','sarah':'c','edward':'ruby','phil':'python',
}
print("Sarah's favorite languages is "+favorite_languages['sarah'].title()+".")
Sarah's favorite languages is C.

6.3 遍历字典

6.3.1 遍历所有的键-值对

user_0={'username':'efermi','first':'enrico','last':'fermi',
}for key,value in user_0.items():print("\nKey: "+key)print("Value: "+value)print("\n")
favorite_languages={'jen':'python','sarah':'c','edward':'ruby','phil':'python',
}
for name,language in favorite_languages.items():print(name.title()+"'s favorite language is "+language.title()+".")
Key: username
Value: efermiKey: first
Value: enricoKey: last
Value: fermiJen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.

6.3.2 遍历字典中的所有键

favorite_languages={'jen':'python','sarah':'c','edward':'ruby','phil':'python',
}for name in favorite_languages.keys():print(name.title())
print("\n")friends=['phil','sarah']
for name in favorite_languages.keys():print(name.title())if name in friends:print(" Hi "+name.title()+", I see your favorite language is "+favorite_languages[name].title()+"!")
Jen
Sarah
Edward
PhilJen
SarahHi Sarah, I see your favorite language is C!
Edward
Phil
Hi Phil, I see your favorite language is Python!

6.3.3 按顺序遍历字典中的所有键

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.

6.3.4 遍历字典中的所有值

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())
print("\n")
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
PythonThe following languages have been mentioned:
Python
C
Ruby

6.4 嵌套

6.4.1 字典列表

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)
print("\n-----------------------------")# 创建一个用于存储外星人的空列表
aliens=[]
# 创建30个绿色的外星人
for alien_number in range(30):new_alien={'color':'green','points':5,'speed':'slow'}aliens.append(new_alien)
for alien in aliens[0:3]:if alien['color']=='green':alien['color']='yellow'alien['speed']='medium'alien['points']=10elif alien['color']== 'yellow':alien['color']='red'alien['speed']='fast'alien['points']=15
#显示前五个外星人
for alien in aliens[:5]:print(alien)
print(".....")
#显示创建了多少个外星人
print("Total number of aliens: "+str(len(aliens)))
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}-----------------------------
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
.....
Total number of aliens: 30

6.4.2 在字典中存储列表

# 存储所点比萨的信息
pizza={'crust':'thick','toppings':['mushrooms','extra cheese']
}#概述所点的比萨
print("You ordered a "+pizza['crust']+"-crust pizza "+"with the following toppings:")
for topping in pizza['toppings']:print("\t"+topping)
print("--------------------------")
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())
You ordered a thick-crust pizza with the following   toppings:mushroomsextra cheese
--------------------------Jen's favorite languages are:PythonRubySarah's favorite languages are:CEdward's favorite languages are:RubyGoPhil's favorite languages are:PythonHaskell

6.4.3 在字典中存储字典

users={'aeinstein':{'first':'albert','last':'aeinstein','location':'priceton',},'mcurie':{'first':'marie','last':'curie','location':'pairs',},
}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: aeinsteinFull name: Albert AeinsteinLocation: PricetonUsername: mcurieFull name: Marie CurieLocation: Pairs

第7章 用户输入和while循环

7.1 函数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!

7.1.1 编写清晰的程序

name=input("Please enter your name: ")
print("Hello, "+name+"!")
print("--------------------------------")
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+"!")
Please enter your name: Eric
Hello, Eric!
--------------------------------
If you tell us who you are,we can personalize the messages you see.
What is your first name?EricHello, Eric!

7.1.2 使用int()来获取数值输入

age=input("How old are you? ")
age=int(age)
print(age)
print(age>=18)
print("--------------")
height=input("How tall are you, in inches? ")
height=int(height)
if height>36:print("\nYou're tall enough to ride!")
else:print("\nYou'll be able to ride when you're a little older.")
How old are you? 22
22
True
--------------
How tall are you, in inches? 71You're tall enough to ride!

7.1.3 求模运算符

print(4%3)
print(5%3)
print(6%3)
print(7%3)
print("------------")
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.")
1
2
0
1
------------
Enter a number, and I'll tell you if it's even or odd:42The number 42 is even.

7.2 while循环简介

7.2.1 使用while循环

current_number=1
while current_number<=5:print(current_number)current_number+=1
1
2
3
4
5

7.2.2 让用户选择何时退出

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)if message!='quit':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 againTell me something, and I will repeat it back to you:
Enter 'quit' to end the program.quit

7.2.3 使用标志

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=Falseelse: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 againTell me something, and I will repeat it back to you:
Enter 'quit' to end the program.quit

7.2.4 使用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':breakelse: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

7.2.5 在循环中使用continue

current_number=0
while current_number<10:current_number+=1if current_number%2==0:continueprint(current_number)
1
3
5
7
9

7.2.6 避免无限循环

x=1
while x<=5:print(x)

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

7.3.1 在列表之间移动元素

#首先,创建一个待验证用户列表
#和一个用于存储已验证用户的空列表
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: AliceThe following users have been confirmed:
Candace
Brian
Alice

7.3.2 删除包含特定值的所有列表元素

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']

7.3.3 使用用户输入来填充字典

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 Result---")
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)yesWhat 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 Result---
Eric would like to climb Denali.
Lynn would like to climb Devil's Thumb.

第8章 函数

8.1 定义函数

def greet_user():'''显示简单的问候语'''print("Hello!")
greet_user()
Hello!

8.1.1 向函数传递信息

def greet_user(username):"""显示简单的问候语"""print("Hello, "+username.title()+"!")
greet_user("jeese")
Hello, Jeese!

8.1.2 实参和形参

def greet_user(username):##username:形参"""显示简单的问候语"""print("Hello, "+username.title()+"!")
greet_user("jeese")## jeese:实参

8.2 传递实参

8.2.1 位置实参

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.

1.调用函数多次

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.

2.位置实参的顺序很重要

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("harry",'hamster')
I have a harry.
My harry's name is Hamster.

8.2.2 关键字实参

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(pet_name="harry",animal_type='hamster')
I have a hamster.
My hamster's name is Harry.I have a hamster.
My hamster's name is Harry.

8.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')
describe_pet('willie')
I have a dog.
My dog's name is Willie.I have a dog.
My dog's name is Willie.

8.2.4 等效的函数调用

def describe_pet(pet_name,animal_type='dog'):"""显示宠物的信息"""print("\nI have a "+animal_type+".")print("My "+animal_type+"'s name is "+pet_name.title()+".")
#一条名为Willlie的小狗
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')
I have a dog.
My dog's name is Willie.I have a dog.
My dog's name is Willie.I have a hamster.
My hamster's name is Harry.I have a hamster.
My hamster's name is Harry.I have a hamster.
My hamster's name is Harry.

8.2.5 避免实参错误

8.3 返回值

8.3.1 返回简单值

def get_formatted_name(first_name,last_name):"""返回整洁的姓名"""full_name=first_name+' '+last_namereturn full_name.title()
musician=get_formatted_name('jimi','hendrix')
print(musician)
Jimi Hendrix

8.3.2 让实参变成可选的

def get_formatted_name(first_name,last_name,middle_name=''):"""返回整洁的姓名"""if middle_name:full_name=first_name+' '+middle_name+' '+last_nameelse:full_name=first_name+' '+last_namereturn 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

8.3.3 返回字典

def build_person(first_name,last_name,age=''):"返回一个字典,其中包含有关一个人的信息"person={'first':first_name,'last':last_name}if age:person['age']=agereturn person
musician=build_person('jimi','hendrix',age=27)
print(musician)
{'first': 'jimi', 'last': 'hendrix', 'age': 27}

8.3.4 结合使用函数和while循环

def get_formatted_name(first_name,last_name):"""返回整洁的姓名"""full_name=first_name+' '+last_namereturn 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':breakl_name=input("Last name: ")if l_name=='q':breakformatted_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: matthesHello, Eric Matthes!Please tell me your name:
(enter 'q' at any time to quit)
First name: q

8.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!

8.4.1 在函数中修改列表

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)
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone caseThe following models have been printed:
dodecahedron
robot pendant
iphone case

8.4.2 禁止函数修改列表

## 向函数传递列表的副本而不是原件;这样函数所做的任何修改都只影响副本,而丝毫不影响原件
function_name(list_name[:])
## 切片表示法[:]创建列表的副本

8.5 传递任意数量的实参

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:
-pepperoniMaking a pizza with the following toppings:
-mushrooms
-green peppers
-extra cheese

8.5.1 结合使用位置实参和任意数量实参

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 toppings')
Making a 16-inch pizza with the following toppings:
-pepperoniMaking a 12-inch pizza with the following toppings:
-mushrooms
-green peppers
-extra toppings

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

def build_profile(first,last,**user_info):"""创建一个字典,其中包含我们知道的有关用户的一切"""profile={}profile['first_name']=firstprofile['last_name']=lastfor key,value in user_info.items():profile[key]=valuereturn profile
user_profile=build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}

8.6 将函数存储在模块中

8.6.1 导入整个模块

def make_pizza(size,*toppings):"""概述要制作的比萨"""print("\nMaking a "+str(size)+"-inch pizza with the following toppings:")for topping in toppings:print("-"+topping)
#将上述代码命名为pizza.py的文件
#用import pizza导入
pizza.make_pizza(16,'pepperoni')
pizza.make_pizza(12,'mushrooms','green peppers','extra toppings')



8.6.2 导入特定的函数

导入方法的语法如下:

from module_name import function_name

若使用这种语法,调用函数时就无需使用句点

8.6.3 使用as给函数指定别名

from module_name import function_name as fn

8.6.4 使用as给模块指定别名

import module_name as mn

8.6.5 导入模块中的所有函数

from pizza import *

由于导入了每个函数,可通过名称来调用每个函数,而无需使用句点表示法。
然而,这种用法并不建议使用!!!
因为模块中有函数的名称与你的项目中使用的名称相同,可能导致意想不到的结果。

第9章 类

9.1 创建和使用类

9.1.1 创建Dog类

class Dog():'''一次模拟小狗的简单尝试'''def __init__(self,name,age):self.name=nameself.age=agedef sit(self):'''模拟小狗被命令时蹲下'''print(self.name.title()+" is now sitting.")def roll_over(self):'''模拟小狗被命令时打滚'''print(self.name.title()+" rolled over!")

9.1.2 根据类创建实例

class Dog():'''一次模拟小狗的简单尝试'''def __init__(self,name,age):self.name=nameself.age=agedef sit(self):'''模拟小狗被命令时蹲下'''print(self.name.title()+" is now sitting.")def roll_over(self):'''模拟小狗被命令时打滚'''print(self.name.title()+" rolled over!")
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.")
My dog's name is Willie.
My dog is 6 years old.

1.访问属性

my_dog.name
'willie'

2.调用方法

my_dog.sit()
my_dog.roll_over()
Willie is now sitting.
Willie rolled over!

3.创建多个实例

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.

9.2 使用类和实例

9.2.1 Car类

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

9.2.2 给属性指定默认值

class Car():'''一次模拟汽车的简单尝试'''def  __init__(self,make,model,year):'''初始化描述汽车的属性'''self.make=makeself.model=modelself.year=yearself.odometer_reading=0def get_descriptive_name(self):'''返回整洁的描述性信息'''long_name=str(self.year)+' '+self.make+' '+self.modelreturn long_name.title()def read_odometer(self):'''打印一条指出汽车里程的消息'''print("This car has "+str(self.odometer_reading)+" miles on it.")my_new_car=Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
2016 Audi A4
This car has 0 miles on it.

9.2.3 修改属性的值

1.直接修改属性的值

class Car():'''一次模拟汽车的简单尝试'''def  __init__(self,make,model,year):'''初始化描述汽车的属性'''self.make=makeself.model=modelself.year=yearself.odometer_reading=0def get_descriptive_name(self):'''返回整洁的描述性信息'''long_name=str(self.year)+' '+self.make+' '+self.modelreturn long_name.title()def read_odometer(self):'''打印一条指出汽车里程的消息'''print("This car has "+str(self.odometer_reading)+" miles on it.")my_new_car=Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
my_new_car.odometer_reading=23
my_new_car.read_odometer()
2016 Audi A4
This car has 0 miles on it.
This car has 23 miles on it.

2.通过方法修改属性的值

class Car():'''一次模拟汽车的简单尝试'''def  __init__(self,make,model,year):'''初始化描述汽车的属性'''self.make=makeself.model=modelself.year=yearself.odometer_reading=0def get_descriptive_name(self):'''返回整洁的描述性信息'''long_name=str(self.year)+' '+self.make+' '+self.modelreturn 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=mileageelse:print("You can't roll back an odometer!")
my_new_car=Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(23)
my_new_car.read_odometer()
my_new_car.update_odometer(13)
2016 Audi A4
This car has 23 miles on it.
You can't roll back an odometer!

3.通过方法对属性的值进行递增

class Car():'''一次模拟汽车的简单尝试'''def  __init__(self,make,model,year):'''初始化描述汽车的属性'''self.make=makeself.model=modelself.year=yearself.odometer_reading=0def get_descriptive_name(self):'''返回整洁的描述性信息'''long_name=str(self.year)+' '+self.make+' '+self.modelreturn 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=mileageelse:print("You can't roll back an odometer!")def increment_odometer(self,miles):'''将里程表读数增加指定的量'''self.odometer_reading+=miles
my_used_car=Car('subaru','outback',2013)
print(my_used_car.get_descriptive_name())my_used_car.update_odometer(23500)
my_used_car.read_odometer()my_used_car.increment_odometer(100)
my_used_car.read_odometer()
2013 Subaru Outback
This car has 23500 miles on it.
This car has 23600 miles on it.

9.3 继承

9.3.1 子类的方法__init__()

class Car():def  __init__(self,make,model,year):self.make=makeself.model=modelself.year=yearself.odometer_reading=0def get_descriptive_name(self):long_name=str(self.year)+' '+self.make+' '+self.modelreturn 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=mileageelse:print("You can't roll back an odometer!")def increment_odometer(self,miles):self.odometer_reading+=milesclass 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

9.3.2 Python2.7中的继承

9.3.3 给子类定义属性和方法

class Car():def  __init__(self,make,model,year):self.make=makeself.model=modelself.year=yearself.odometer_reading=0def get_descriptive_name(self):long_name=str(self.year)+' '+self.make+' '+self.modelreturn 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=mileageelse:print("You can't roll back an odometer!")def increment_odometer(self,miles):self.odometer_reading+=milesclass ElectricCar(Car):'''电动汽车的独特之处初始化父类的属性,再初始化电动汽车特有的属性'''def __init__(self,make,model,year):'''初始化父类的属性'''super().__init__(make,model,year)self.battery_size=70def 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.

9.3.4 重写父类的方法

class ElectricCar(Car):'''电动汽车的独特之处初始化父类的属性,再初始化电动汽车特有的属性'''def __init__(self,make,model,year):'''初始化父类的属性'''super().__init__(make,model,year)self.battery_size=70def describe_battery(self):"""打印一条描述电瓶容量的消息"""print("This car has a "+str(self.battery_size)+"-kwh battery.")def fill_gas_tank(self):'''电动汽车没有油箱'''print("This car does't need a gas tank")my_tesla=ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank()
2016 Tesla Model S
This car has a 70-kwh battery.
This car does't need a gas tank

9.3.5 将实例用作属性

class  Battery():"""一次模拟电动汽车电瓶的简单尝试"""def __init__(self,battery_size=70):"""初始化电瓶的属性"""self.battery_size=battery_sizedef describe_battery(self):"""打印一条描述电瓶容量的消息"""print("This car has a "+str(self.battery_size)+"-kwh battery.")def get_range(self):"""打印一条消息,指出电瓶的续航里程"""if self.battery_size==70:range=240elif self.battery_size==85:range=270message="This car can go approximately "+str(range)message+=" miles on a full charge"print(message)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()
my_tesla.battery.get_range()
2016 Tesla Model S
This car has a 70-kwh battery.
This car can go approximately 240 miles on a full charge

9.4 导入类

9.4.1 导入单个类

"""一个可用于表示汽车的类"""class Car():"""一次模拟汽车的简单尝试"""def __init__(self, make, model, year):"""初始化描述汽车的属性"""self.make = makeself.model = modelself.yaer = yearself.odometer_reading = 0def get_descriptive_name(self):"""返回整洁的描述性名称"""long_name = str(self.yaer) + ' ' + self.make + ' ' + self.modelreturn long_name.title()def read_odometer(self):"""打印一条消息,指出汽车的里程"""print("This car has " + str(self.odometer_reading) + " miles on it.")def upgrade_odometer(self, mileage):"""将里程表读数设置为指定的值拒绝将里程表往回拨"""if mileage >= self.odometer_reading:self.odometer_reading = mileageelse:print("You can't roll back an odometer!")def increment_odometer(self, miles):"""将里程表读数增加指定的量"""self.odometer_reading += miles

运行如下代码:

from car import Carmy_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())my_new_car.odometer_reading = 23
my_new_car.read_odometer()

运行结果如下:

9.4.2 在一个模块中存储多个类

"""一个可用于表示燃油汽车和电动汽车的类"""class Car():"""一次模拟汽车的简单尝试"""def __init__(self, make, model, year):"""初始化描述汽车的属性"""self.make = makeself.model = modelself.yaer = yearself.odometer_reading = 0def get_descriptive_name(self):"""返回整洁的描述性名称"""long_name = str(self.yaer) + ' ' + self.make + ' ' + self.modelreturn long_name.title()def read_odometer(self):"""打印一条消息,指出汽车的里程"""print("This car has " + str(self.odometer_reading) + " miles on it.")def upgrade_odometer(self, mileage):"""将里程表读数设置为指定的值拒绝将里程表往回拨"""if mileage >= self.odometer_reading:self.odometer_reading = mileageelse:print("You can't roll back an odometer!")def increment_odometer(self, miles):"""将里程表读数增加指定的量"""self.odometer_reading += milesclass Battery():"""一次模拟电动汽车电瓶的简单尝试"""def __init__(self, battery_size=70):"""初始化电瓶的属性"""self.battery_size = battery_sizedef describe_battery(self):"""打印一条描述电瓶容量的消息"""print("This car has a " + str(self.battery_size) + "-kwh battery.")def get_range(self):"""打印一条描述电瓶续航里程的消息"""if self.battery_size == 70:range = 240elif self.battery_size == 85:range = 270message = "This car can go approximately " + str(range)message += " miles on a full charge."print(message)class ElectricCar(Car):"""模拟电动汽车的独特之处"""def __init__(self,make,model,year):"""初始化父类的属性,再初始化电动汽车特有的属性"""super().__init__(make, model, year)self.battery=Battery()
from car import ElectricCarmy_tesla=ElectricCar('tesla','model s',2016)print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()

运行结果如下:

9.4.3 从一个模块导入多个类

from car import Car,ElectricCarmy_beetle=Car('volkswagen','bettle',2016)
print(my_beetle.get_descriptive_name())my_tesla=ElectricCar('tesla','roadster',2016)
print(my_tesla.get_descriptive_name())
2016 Volkswagen Bettle
2016 Tesla Roadster

9.4.4 导入整个模块

import carmy_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())
2016 Volkswagen Beetle
2016 Tesla Roadster

9.4.5 导入模块中的所有类

from module_name import *

9.4.6 在一个模块中导入另一个模块

9.5 Python标准库

from collections import OrderedDictfavorite_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()+'.')

9.5 Python标准库

from collections import OrderedDictfavorite_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()+'.')

第10章 文件和异常

10.1 从文件中读取数据

10.1.1 读取整个文件

with open('pi_digits.txt')as file_object:contents=file_object.read()print(contents)print(contents.rstrip())
3.1415926535
8979323846
26433832793.1415926535
8979323846
2643383279

10.1.2 文件路径

file_path='C:\Users\ehmatthes\other\files\text_files\filename.txt'
with open(file_path)as file_object:

10.1.3 逐行读取

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

10.1.4 创建一个包含文件各行内容的列表

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

10.1.5 使用文件的内容

filename='pi_digits.txt'with open(filename) as file_object:lines=file_object.readlines()pi_string_1=''
pi_string_2=''
for line in lines:pi_string_1+=line.rstrip()pi_string_2+=line.strip()print(pi_string_1)
print(len(pi_string_1))
print(pi_string_2)
print(len(pi_string_2))
3.1415926535  8979323846  2643383279
36
3.141592653589793238462643383279
32

10.1.6 包含一百万位的大型文件

filename='pi_million_digits.txt'
with open(filename)as file_object:lines=file_object.readlines()pi_string=''
for line in lines:pi_string+=line.strip()print(pi_string[:52]+"...")
print(len(pi_string))
3.14159265358979323846264338327950288419716939937510...
1000002

10.1.7 圆周率值中包含你的生日吗

filename='pi_million_digits.txt'
with open(filename)as file_object:lines=file_object.readlines()pi_string=''
for line in lines:pi_string+=line.strip()birthday=input("Enter your birthday,In the form mmddy:")
if birthday in pi_string:print("Your birthday appears in the first million digits of pi!")
else:print("Your birthday does not appear in the first million figits of pi.")
Enter your birthday,In the form mmddy:041900
Your birthday appears in the first million digits of pi!

10.2 写入文件

10.2.1 写入空文件

filename='programming.txt'with open(filename,'w') as file_object:file_object.write("I love programming.")

10.2.2 写入多行

filename='programming.txt'with open(filename,'w') as file_object:file_object.write("I love programming.\n")file_object.write("I love creating new games.\n")

10.2.3 附加到文件

filename='programming.txt'with open(filename,'a') as file_object:file_object.write("I also love finding meaning in large datasets.\n")file_object.write("I love creating apps that can run in a browser.\n")

10.3 异常

10.3.1 处理ZeroDivisionError异常

print(5/0)
ZeroDivisionError                         Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_2232\785342039.py in <module>
----> 1 print(5/0)
ZeroDivisionError: division by zero

10.3.2 使用try-except代码块

try:print(5/0)
except:print("You can't divide by zero!")
You can't divide by zero!

10.3.3 使用异常避免崩溃

print("Give me two numbers: and I'll divide them.")
print("Enter 'q' to quit.")while True:first_number=input("\nFirst number: ")if first_number=='q':breaksecond_number=input("Second number: ")if second_number=='q':breakanswear=int(first_number)/int(second_number)print(answear)
Give me two numbers: and I'll divide them.
Enter 'q' to quit.First number: 1
Second number: 0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_2232\744485532.py in <module>10     if second_number=='q':11         break
---> 12     answear=int(first_number)/int(second_number)13     print(answear)ZeroDivisionError: division by zero

10.3.4 else代码块

print("Give me two numbers: and I'll divide them.")
print("Enter 'q' to quit.")while True:first_number=input("\nFirst number: ")if first_number=='q':breaksecond_number=input("Second number: ")try:answear=int(first_number)/int(second_number)except ZeroDivisionError:print("You can't divide by 0!")else:print(answear)
Give me two numbers: and I'll divide them.
Enter 'q' to quit.First number: 5
Second number: 0
You can't divide by 0!First number: 5
Second number: 2
2.5First number: q

10.3.5 处理FileNotFoundError异常

filename='alice.txt'
try:with open(filename) as f_obj:contents=f_obj.read()
except FileNotFoundError:msg="Sorry, the file "+filename+" does not exist."print(msg)
Sorry, the file alice.txt does not exist.

10.3.6 分析文本

filename='alice.txt'
try:with open(filename) as f_obj:contents=f_obj.read()
except FileNotFoundError:msg="Sorry, the file "+filename+" does not exist."print(msg)
else:#计算文件大致包含多少个单词words=contents.split()num_words=len(words)print("The file "+filename+" has about "+str(num_words)+" words.")
The file alice.txt has about 29461 words.

10.3.7 使用多个文件

def count_words(filename):"""计算一个文件大致包含多少个单词"""try:with open(filename) as f_obj:contents=f_obj.read()except FileNotFoundError:msg="Sorry, the file "+filename+" does not exist."print(msg)else:#计算文件大致包含多少个单词words=contents.split()num_words=len(words)print("The file "+filename+" has about "+str(num_words)+" words.")filenames=['alice.txt','siddhartha.txt','moby_dict.txt','little_women.txt']
for filename in filenames:count_words(filename)
The file alice.txt has about 29461 words.
Sorry, the file siddhartha.txt does not exist.
The file moby_dict.txt has about 215136 words.
The file little_women.txt has about 189079 words.

10.3.8 失败时一声不吭

def count_words(filename):"""计算一个文件大致包含多少个单词"""try:with open(filename) as f_obj:contents=f_obj.read()except FileNotFoundError:passelse:#计算文件大致包含多少个单词words=contents.split()num_words=len(words)print("The file "+filename+" has about "+str(num_words)+" words.")filenames=['alice.txt','siddhartha.txt','moby_dict.txt','little_women.txt']
for filename in filenames:count_words(filename)
The file alice.txt has about 29461 words.
The file moby_dict.txt has about 215136 words.
The file little_women.txt has about 189079 words.

10.3.9 决定报告哪些错误

Python编程从入门到实践 第一部分基础知识 代码合集相关推荐

  1. Python编程从入门到实践 动手试一试 代码合集

    动手试一试 2-1 简单消息 a='a message' print(a) 2-2 多条简单消息 a='a message' print(a) a='two messages' print(a) 2- ...

  2. Python编程从入门到放弃 - Part 1基础知识习题解析

    目录 第1章 起步 第2章 变量和简单数据类型 第3章 列表简介 第4章 操作列表 第5章 if语句 第6章 字典 第7章 用户输入和while循环 第8章 函数 第9章 类 第10章 文件和异常 第 ...

  3. 《Python编程从入门到实践》记录之测试代码(unitttest模块)

    unittest模块提供了测试代码工具. 单元测试:用于核实函数的某个方面没有问题 测试用例:一组单元测试,这些单元测试一起核实函数在各种情形下的行为都符合要求. 函数编写测试用例时,要导入模块uni ...

  4. python编程 从入门到实践豆瓣-三周刷完《Python编程从入门到实践》的感受

    本文将以对话采访的形式展现 为什么会选择学习Python 语法简洁,实用,和golang部分类似,学习性价比高: 应用范围广,涉及后端,机器学习,图像处理,游戏等: 好奇这是一门怎样的语言 计划如何学 ...

  5. python基础学习[python编程从入门到实践读书笔记(连载五)]:数据可视化项目第16章

    文章目录 下载数据 制作全球地震散点图:JSON格式 end 几个实验结果: 每日最高气温: 地震图绘制: 下载数据 CSV文件格式 在文本文件中存储数据,一个简单方式是将数据作为一系列以逗号分隔的值 ...

  6. python基础学习[python编程从入门到实践读书笔记(连载三)]:django学习笔记web项目

    文章目录 Django项目:学习笔记web网页 项目部署 参考 自己部署的网站,还是小有成就感的,毕竟踩过很多坑,实战技能也有些许进步. 网站链接:http://lishizheng.herokuap ...

  7. python基础学习[python编程从入门到实践读书笔记(连载一)]

    写在前面:本文来自笔者关于<python编程从入门到实践>的读书笔记与动手实践记录. 程序员之禅 文章目录 02变量和简单数据类型 03 列表简介 04 操作列表 05 if语句 06 字 ...

  8. python数据可视化从入门到实战_《Python编程从入门到实践》json数据可视化练习详解...

    <Python编程从入门到实践>16.2中,计算收盘价均值的程序有些不易看懂,结合我自己的理解进行一些说明. 使用的数据集:join格式的数据, 数据集是由多个字典为元素组成的列表.每个字 ...

  9. python unique函数_《Python编程从入门到实践》json数据可视化练习详解

    <Python编程从入门到实践>16.2中,计算收盘价均值的程序有些不易看懂,结合我自己的理解进行一些说明. 使用的数据集:join格式的数据, 数据集是由多个字典为元素组成的列表.每个字 ...

最新文章

  1. .net Core+Dapper MySQL增删改查
  2. 博客园Logo创意之我的朋友弄的
  3. netbeans 定制代码_将NetBeans代码模板弯曲到我的意愿
  4. Why you have so few friends?
  5. 这让全场的chinaakd
  6. 一个15岁少年写的汇编代码
  7. LeetCode | 3 Sum
  8. aelf宣布推出集中式资产管理系统CAM
  9. 计算机组成原理_计算机组成原理amp;认识Python
  10. 安卓rom制作教程_MIUI官方ROM(卡刷包、线刷包)合集
  11. CREO:CREO软件之零件【模型】之操作、基准、形状、扫描、工程、编辑、曲面的简介及其使用方法(图文教程)之详细攻略
  12. Win10桌面极简美化
  13. 如何进行远程协作办公?
  14. C++ 简易的五子棋游戏 初学者
  15. 情感分析(判断文章正负向)
  16. C语言——任意分数化简
  17. mysql全称_mysql全称
  18. 视频处理系列︱利用达摩院ModelScope进行视频人物分割+背景切换(一)
  19. 测试网络SNMP连接的几个方法(我平时调试SNMP程序时用到的几个解决方案)
  20. matlab多元回归分析怎么计算,matlab在多元线性回归分析中的相关计算

热门文章

  1. 蓝鲸CMP:跳出云管看云管
  2. 计算机网络知识点概括
  3. GWO灰狼优化算法python和matlab代码
  4. (29)Verilog实现倍频【方法二】
  5. SolveigMM Video Splitter绿色中文版
  6. 华为nova2s用哪个型号服务器,华为Nova2s和Nova2买哪个好/区别大吗?华为Nova2s与Nova2的区别对比详解...
  7. 【SpringBoot项目中使用Mybatis批量插入百万条数据】
  8. 《学会提问-批判性思维指南》--70页原创PPT免费分享 (评论: 学会提问)
  9. 海康威视视频在页面中展示
  10. Vs2008编译vtk5.10详细教程