Python 编程从入门到实践
第一、二章
name = ' tom '
name.title()
name.upper()
name.lower()
name.lstrip()
name.rstrip()
name.strip() # 删除字符串左右两边的空格
age = 23
age.str() # 数字转字符
“ + ” 可以用来连接字符串
第三章
列表 List
bicycles = ['treck', 'cannondale', 'redline', 'specialized']
print(bicycles)
print(bicycles[0])
print(bicycles[0].title())
print(bicycles[-1]) # 访问列表最后一个元素
print(bicycles[-2])
message = "My first bicycle is a " + bicycles[0].title() + '.'
bicycles[0] = 'honda'
# 在列表末尾添加元素
bicycles.append('ducati')
# 在列表指定位置插入元素
bicycles.insert(0, 'yamaha')
# 删除列表中的元素
del bicycles[0]
# 使用 pop() 方法删除列表中的最后一个元素,并继续使用它的值(使用pop方法后,元素就不再在列表中了)
motorcycle = bicycles.pop()
# 根据值删除元素
bicycles.remove('ducati')
too_expensive = 'ducati'
bicycles.remove(too_expensive)
# 使用 sort() 方法对列表进行按字母顺序永久排序
cars = ['bmw','audi','toyota','subaru','benzi']
cars.sort()
cars.sort(reverse = True) # 按与字母顺序相反的顺序排列
sorted(cars) # 对列表进行临时排序
len(cars) # 确定列表的长度
第四章 操作列表
magicians = ['alice', 'david', 'carolina']
#使用 for 循环遍历整个列表
for magician in magicians: # 这里的 magician 是用于存储列表中值的临时变量,事实上临时变量可以指定任何名称
print(magician)
range() 函数
eg:
for value in range(1,5): # 打印数字 1~4
print(value)
numbers = list(range(1,6)) # 使用 list() 函数将 range() 的结果直接转换为列表
print(numbers)
结果是:[1,2,3,4,5]
even_numbers = list(range(2,11,2)) # 使用函数 range() 时,第三个参数可以指定步长
print(numbers)
结果是:[2,4,6,8,10]
#将前十个整数的平方加入到一个列表中
squares = []
for value in range(1,11):
square = value**2 # python中, ** 代表乘方运算,例如:平方 **2、立方 **3
squares.append(square)
# or 直接 squares.append(value**2) 也行
# 还可以使用列表解析的方法: squares = [value**2 for value in range(1,11)]
# 几个专门用于处理数字列表的 python 函数
digits = [1,2,3,4,5,6,7,8]
min(digits)
max(digits)
sum(digits)
切片
players = ['charles','martina','michael','florence','eli']
print(players[0:3]) # 打印列表中的前三个元素,输出的也是一个列表
print(players[1:4])
print(players[:3]) # 如果没有指定第一个索引,python 将自动从列表第 0 位元素开始
print(players[1:]) # 结束于末尾
print(players[-3:])
for player in players[:3]: # 在 for 循环中使用切片
print(player.title())
# 复制列表
my_foods = ['pizza','falafel','carrot','cake']
friend_foods = my_foods[:]
# 复制后的两个列表各自独立,比如 my_foods.append('banana'),在列表 friend_foods 中,并不会出现 'banana'
如果:
my_foods = friend_foods # 将 my_foods 赋给 friend_foods, 而不是将 my_foods 副本存储到 friend_foods
my_foods.append('banana')
# friend_foods 列表中也会出现 'banana'
元组:不可变的列表称为元组,元组使用圆括号
eg:
dimensions = (30,40,50)
dimensions[0] = 200 # 错误,元组中的元素不可改变
dimensions = (60,80,100) # 正确,可以重新定义整个元组
for dimension in dimensions:
print(dimension)
第五章 if语句
cars = ['audi','bmw','subaru','toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
car = 'Audi'
car.lower() == 'audi' # 返回 True
car == 'audi' # 返回 False, 因为 lower() 函数不会改变 car 中的值
# Python 中的 and 相当于 其他语言中的 &&, or 相当于 ||
# 判断特定的值是否在列表中,可使用关键字 in, 使用 not in 来判断特定值不在列表中
# if-elif-else 结构
age = 12
if age < 4:
print("Free")
elif age < 18:
print("Charge")
elif age < 65:
print("Discount")
else:
print("Free")
"""
Python 并不要求 if-elif 结构后面必须有 else 代码块,最后一句也可改为
elif age >= 65:
print("Free")
"""
request_toppings = []
if request_toppings: # 列表至少包含一个元素时返回 True, 否则返回 False
for request_topping in request_toppings:
print("Adding " + request_topping + ".")
# 使用多个列表
available_toppings = ['mushroom','olives','green peppers','pepperoni','pineappple','extra cheese']
request_toppings = ['mushroom','french fries','extar cheese']
for request_topping in request_toppings:
if request_topping in available_toppings:
print("Adding " + request_topping + ".")
else:
print("Sorry!")
第六章 字典
alien = {} # 空字典
alien = {'color':'green', 'points':5}
print(alien) # 打印字典
print(alien['color']) # 打印 green
print(alien['points']) # 打印 5
alien['x_position'] = 6 # 可直接在字典中添加键-值对
alien['y_position'] = 8
alien['color'] = 'yellow' # 修改字典中的键-值对
del alien['points'] # 删除字典中的键值对
"""
字典是一系列键-值对,上面的 color 和 points 都是键, green 和 5 是值
可以用键来访问与之相关联的值
值可以是数字、字符串、列表、乃至字典
事实上,python中的任何对象都可以作为字典中的值
"""
遍历字典
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for key, value in favorite_languages.items(): # key 和 value 是两个变量名
print("key: " + key)
print("value: " + value)
遍历字典中的所有键
print(favorite_languages.keys()) # 返回的是一个包含了字典中所有值的列表
for value in favorite_languages.keys():
*for value in favorite_languages 二者效果相同*
print(value)
按顺序遍历字典中的所有键
for name in sorted(favorite_languages.keys()):
print(name)
遍历字典中的所有值
print(favorite_languages.values()) # 返回的是一个包含了字典中所有值的列表
print( set( favorite_languages.values() ) )
'''
集合 set, 可让 Python 找出列表中独一无二的元素,
并使用这些元素来创建一个集合
'''
range() 方法
aliens = []
# 创建 30 个外星人
for alien_number in range(30): # 或者 range(0,30)
new_alien = {'color':'green', 'points':5, 'speed':'slow'}
aliens.append(new_alien)
在字典中存储列表
favorite_languages = {
'jen':['python','ruby'],
'sarah':['c','c++']
'edward':['ruby','php'],
'phil':['haskell','python',]
}
for name,language in favorite_languages.items():
print(name.title() + "'s favorite languages are:")
for language in languages:
print("\t" + language.title)
在字典中存储字典:
users = {
'einstein':{
'first':'albert',
'last':'einstein',
'location':'priceton',
},
'mcuurie':{
'first':'marie',
'last':'curie',
'location':'paris',
},
}
for username, user_info in users.items():
print("Username: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("Full_name: " + full_name.title())
print("Location: " + location.title())
第七章 用户输入和 while 循环
创建多行字符串
promt = "If you tell us who you are, we can personalize the message you see."
promt += "\nSo what is your name?"
name = input(promt) # 使用 input 来获取输出
print("\nHello " + name + "!")
'''
使用函数 input() 时,Python 将用户输入解读为字符串。比如:
输入的是数字 21, 返回的却是字符串 '21'
可用强制类型转换 int()
'''
使用用户输入来填充字典
responses = {}
polling_active = True
while polling_active:
name = input("what's your name?")
response = input("which president do you like?")
responses[name] = resopnse # 将键值对存储在字典中
第八章 函数
定义函数
def greet_user():
print("Hello!")
调用时直接 greet_user() 就行了
传递实参
def describe_pet(animal_type, pet_name):
print("I have a " + animal_type + ".")
print("Its name is " + pet_name + ".")
describe_pet('Dog', 'Tom') # 位置实参
describe_pet(animal_type = 'Dog', pet_name ='Tom') # 关键字实参
默认值:定义函数时,给形参指定默认值
def def describe_pet(pet_name, animal_type ='Dog')
'''
在调用函数中给形参提供了实参时,Python 将使用指定的实参值
否则,将使用形参的默认值
'''
返回值
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)
让实参变成可选的
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
'''
定义函数时,给可选的参数指定一个默认值——空字符串,
并将其放在形参列表的末尾
'''
返回字典
def bulid_person(first_name, last_name, age=''):
person = {'first':first_name, 'last':last_name}
if age:
person['age'] = age
return person
musician = bulid_person('jimi', 'hendrix')
print(musician)
传递列表
def greet_users(names):
for name in names:
msg = "Hello " + name.title() + "!"
print(msg)
usernames = ['Tom','Dog','Jerry']
greet_users(usernames)
要将列表的副本传递给函数的参数,可以:
function_name(list_name[:])
传递任意数量的实参
def make_pizza(*toppings):
print(toppings)
for topping in toppings:
print('===' + topping)
'''
形参名 *toppings 中的星号让 Python 创建一个名为 topping
的空元组,并将收到的所有值都封装到这个元组中
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量
实参的形参放在最后
'''
使用任意数量的关键字实参
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')
'''
形参 **user_info 中的两个星号让 Python 创建一个名为 user_info 的空字典,
并将收到的所有 名称-值 对都封装到这个字典中
'''
将函数存储在模块中
创建一个包含函数 make_pizza() 的模块
1.在 pizza.py 所在的目录中创建另一个名为 making_pizzas.py 的文件
2.在 making_pizzas.py 文件中 import pizza
3.调用 pizza.py 中函数时,pizza.make_pizza()
导入特定的函数
# 导入特定函数后,就可用该函数名来调用它了
1.from module_name import function_name
# 用逗号分隔函数名
2.from module_name import function_0,function_1
使用 as 给函数指定别名
from module_name import function_name as fn
使用 as 给模块指定别名
import module_name as mn
导入模块中的所有函数
from module_name *
# 由于导入了每个函数,可通过名称来调用每个函数,而无须使用句点表示法
第九章 类
创建 Dog 类
以 self 为前缀的变量都可供类中的所有方法使用
class Dog():
def __init__(self, name, age):
self.name = name;
self.age = age;
def sit(self):
print(self.name.title() + " is now sitting!")
创建对象:my_dog = Dog("willie", 6)
给属性指定给默认值
/可在初始化类的方法内设置默认值,如果对某个属性这样做了,就无需在方法中为它提供包含初始值的形参/
class Car():
def __init__(self, make, model, year):
self.year = year
self.make = make
self.model = model
self.odometer_reading = 0 # 设定默认值
直接修改属性的值
mew_car = Car('audi','a4',2016)
new_car.odometer_reading = 200 /*通过实例访问*/
通过方法修改属性的值
在类内部:
def update_odometer(self, mileage):
self.odometer_reading = mileage
继承
class Electricar(Car):
def __init__(self,make,model,year):
'''初始化父类的属性'''
super().__init__(self,make,model,year)
注意:创建子类时,父类必须包含在当前文件中,且位于子类前面,也可以重写父类中的方法
将实例用作属性(类中还有类)
self.battery = Battery() /*Battery 是电池类*/
导入类
from car import Car # 从 car.py 中导入 Car 类