参考书籍《Python从入门到实践》

一 变量和简单数据

1.变量名

  • 变量命名和使用
    • 变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头。

    • 变量名不能包含空格,但可以用下划线来分隔其中的单词。如:message_1

    • 不能使用Python关键字和函数名用作变量名

    • 变量名应具有一定的描述性且简短。如:student_name

2.字符串

字符串用“”或‘’括起来,两者可以夹杂着用

'I told my firend, "Python"'
"I told my firend, 'Python'"
方法 功能
title() 以首字母显示单词
upper() 将字符串全部改写为大写
lower() 将字符串全部改写为小写
strip() 删除字符串两端的空白
lstrip() 删除字符串左端的空白
rstrip() 删除字符串右端的空白

二 列表

1.列表的基本概念

  • 由一系列按特定顺序排列的元素组成。用方括号[]表示
bicycles = ['trek','cannodale','redline','specialized']
print(bicycles)	#打印结果中包含方括号和单引号和逗号

元素从0开始,通过bicycles[0]来索引,最后一个元素可同-1来索引,对倒数第二个可用-2,依此类推。

2.修改、添加和删除列表

  • 修改列表元素
bicycles = ['trek','cannodale','redline','specialized']
print(bicycles)
bicycles[0] = 'aaaa'
print(bicycles)	#打印后,第一个元素变为'aaaa'
  • 在列表中添加元素——append()
bicycles = ['trek','cannodale','redline','specialized']
print(bicycles)
bicycles.append('aaaa')	#默认加在列表的最后
print(bicycles)	#最后一个元素为'aaaa'
  • 在列表中插入元素——insert()
bicycles = ['trek','cannodale','redline','specialized']
print(bicycles)
bicycles.insert(0,'aaaa')	#接受位置和元素两个参数
print(bicycles) #第一个元素为'aaaa'
  • 在列表中删除元素——del语句(必须知道要删除元素在列表中的位置)
bicycles = ['trek','cannodale','redline','specialized']
print(bicycles)
del bicycles[0]
print(bicycles)	#第一个元素'trek'被删除,第一个元素现在是'cannodale'
  • 使用pop()删除元素——pop()将元素从列表删除,并接着使用它的值
bicycles = ['trek','cannodale','redline','specialized']
print(bicycles)
poped_bicycles1 = bicycles.pop()	#默认删除列表末尾的元素
poped_bicycles2 = bicycles.pop(1)	#删除列表中第二个元素,指定位置删除元素
  • 根据值删除元素——remove()
bicycles = ['trek','cannodale','redline','specialized']
print(bicycles)
bicycles.remove('redline')
print(bicycles)	#列表中'redline'元素被删除

3.组织列表

  • sort()对列表永久排序——按字母顺序排列
cars = ['bmw','audi','toyota','subaru']
cars.sort()
print(cars)	#结果中列表元素按字母顺序排列
car.sort(reverse = True)	#向sort()传递参数
print(cars) #结果中列表元素按反的字母顺序排列
  • sorted()对列表临时排序
cars = ['bmw','audi','toyota','subaru']
print(cars)	#未排序
print(sorted(cars))	#列表元素排列好打印出来
print(cars)	#未排序
  • reverse()反转列表元素的排列顺序,并非是按与字母顺序相反的顺序排列

  • len()获悉列表长度——元素数量

4.遍历列表

  • 遍历整个列表
magicians = ['alice','david','carolina']
for magician in magicians:	#不要忘记冒号,该行指将列表中的每个元素依次赋给magician这个变量
    print(magician)	#依次打印出列表中的元素
  • 创建数值列表——range()和list()
for value in range(1,5):	#range()生成1~4的元素,即差一行为
    print(value)
numbers = list(range(1,6))	#生成一个包含数字1~5的列表numbers
  • 对数字列表进行计算
digits = [1,2,3,4,5]
min(digits)	#求最小值
max(digits)	#求最大值
sum(digits)	#求和
  • 列表解析——将for循环和创建新元素的代码合并成一行,并自动附加新元素
squares = [value**2 for value in range(1,11)]
print(squqres)

5.切片

  • 列表的部分元素称之为切片,切片也是一个列表
players = ['charles','martina','michael','florence','eli']
print(players[0:3])	#打印出列表前三个元素(差一行为),players[0:3]就是一个切片

players[:3]默认从列表开头开始,players[2:]默认从第三个元素到列表末尾所有的元素。也可使用pythong[-3:]

  • 遍历切片——与列表一样
players = ['charles','martina','michael','florence','eli']
for player in players[0:3]:
    print(player)
  • 复制列表——列用name[:]快捷复制
players = ['charles','martina','michael','florence','eli']
aaa = players[:]	#两个变量指向同一个列表,一个发生变化,另一个也变化

6.元组

元组:列表中的元素不可修改,称这个不可变的列表为元组,用圆括号()来标识

dimensions = (200,50)	#这个就是一个数值元组
print(dimensions[0])	#索引和列表一样
for dimension in dimensions:
    print(dimension)	#遍历元组和遍历列表一样
dimensions = (400,100)	#修改元组

三 if语句

1.条件测试

  • 字符字符串和数字
#字符串
car = 'Audi'	#将'Audi'赋给car
car == 'audi'	#判断car和'audi'是否相等,结果为True或False
car != 'audi'	#判断car和'audi'是否不相等,结果为True和False
car.lower() == 'audi'	#不考虑大小写的判断方法

#数字
##将19赋给age
age = 19
##将age与21进行比较,结果为True和False
age < 21
age <= 21
age >= 21
  • 检查多个条件——and和or的使用
#and
age_0 = 22
age_1 = 18
age_0 >= 21 and age_1 >= 21	#两个都为True时,才为True
age_0 >= 21 or age_1 >= 21	#只要一个为True时,就为True
  • 检查特定值是否包含或不包含在列表中——in和not in的使用
requested_toppings = ['mushrooms','oninos','pineapple']
'mushrooms' in requested_toppings	#结果为True
'carrot' not in requested_toppings	#结果为True

2. if语句

  • 基本格式
if conditional_test:	#不要忘记冒号
    do something
  • 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.")
  • if-elif-else语句
age = 12
if age < 14:
    print("Your admission cost is $0.")
elif age < 18:	#elif有条件测试,且可以有多个
    print("Your admission cost is $5.")
else:	#else可以不用
    print("Your admission cost is $10.")

3. if语句在列表中的使用

  • 检查特殊元素
requested_toppings = ['mushroom','green peppers','extra cheese']
for requested_topping in requested_toppings:
    if requested_toppong == 'green peppers':
        print("Sorry, we are out of green peppers right now.")
    else:
        print("Adding " + requested_topping + ".")
 print("\nFinished making your pizza!")
  • 确定列表不为空
requested_toppings = []
if requested_toppings:	#判断列表是否为空,空为False,不空为True
    for requested_topping in requested_toppings:
        print("Adding " + requested_topp + ".")
    print("\nFinished making your pizza!")
else:
    print("Are you sure you want a plain pizza?")

四 字典

1.使用字典

  • 字典是一系列键值对,每个键都与一个值相关联,放在花括号{}中,键与值用冒号分隔,键值对之间用逗号分隔。
alien_0 = {'cloor':'green','points':5}
  • 访问字典中的值

要获取与键相关联的值,只需依次指定字典名和放在方括号内的键,如:

print(alien_0['cloor'])
  • 添加键-值对

字典是动态结构,可随时在其中添加键-值对。

alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)

字典中键-值对的排列顺序与其添加顺序不同。

  • 创建空字典,然后在其中添加键-值对
alien_0 = {}
  • 修改字典中值
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")
  • 删除键-值对

对于字典中不再需要的信息,可使用del语句将相应的键-值对彻底删除

#删除键值对
##删除之前
print(alien_0)
##删除之后
del alien_0['points']
print(alien_0)

2.遍历字典

  • 遍历字典所有的键-值对——items()
#遍历所有的键-值对
##遍历字典是,键-值对的返回顺序与存储顺序不同
user_0 = {
    'username': 'efermi', #不要忘记加逗号
    'first': 'enrico',
    'last': 'fermi',
    }
for  key, value in user_0.items():
    print("\nKey: " + key)
    print("Value: " + value)
  • 遍历字典所有的键——keys()
#遍历所有的键,keys()可去掉
for key in user_0.keys():
    print("key: " + key.title())
  • 按顺序遍历字典中的所用键——sorted()
#按顺序遍历字典中的所用键——sorted()
for name in sorted(favorite_language.keys()):
    print(name.title() + ", thank you for taking the poll.")
  • 遍历字典所有的值——values()
#遍历字典中所有的值
for language in favorite_language.values():
    print(language.title())
  • 历字典中所有值,同时剔除重复项——set()
for language in set(favorite_language.values()):
    print(language.title())

3.嵌套

字典存储在列表中,或列表存储在字典中,称为嵌套。

  • 字典列表
#字典列表
alien_0 = {'color': 'grenn', '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)

  • 在字典中存储列表

每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表。

#在字典中存储列表
#存储所点比萨的信息
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)
  • 在字典中存储字典
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())

五 用户输入和while循环

1. input()和int()

1.input(),让程序暂停运行,等待用户输入一些文本

#一行
name = input("Please enter your name: ")
print("Hello, " + name + "!")
#多行
prompt = "If you tell us who you are, we can personlaize the message you see."
prompt += "\nWhat is your first name?"
name = input(prompt)
print("\nHello, " + name + "!")

2.int(),获取数值输入,将数字的字符串表示为数值表示

int()一般与input()结合使用

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

3.球磨运算符%——将两个数相除并返回余数

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

2. while循环

1.while循环基本语法

current_number = 1
while current_number <= 5: #冒号不要忘记
    print(current_number)
    current_number += 1

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)
    print(message)

3.使用标志

在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志,充当了程序的交通信号灯。

active = True
while  active:
    message = input(prompt)
    if message == 'quit':
        active = False
    else:
        print(message)

4.使用break退出循环

break语句直接退出循环,不再执行循环中余下的代码,并退出循环。(注意与上一个代码块的区别)

while True:
    city = input(prompt)
    if city == 'quit':
        break #后面的else语句不再执行
    else:
        print("I'd love to go to " + city.title() + "!")

5.continue语句

continue语句直接返回到循环开头,并根据条件测试结果决定是否继续执行循环。

current_number = 0
while current_number <= 10:
    current_number += 1
    if current_number % 2 == 0:
        continue   
        #偶数就返回循环开头,继续根据条件测试结构决定是否继续执行循环,不执行下面的print语句
    print(current_number)

六 函数

1.函数

1.函数

def greet_user(): #不要忘记冒号
    """显示简单的问候语"""
    print("Hello!")
greet_user()

2.向函数传递信息

def greet_user(username):	#username是一个形参,函数定义中
"""显示简单的问候语"""
	print("Hello, " + username.title() + "!")
greet_user('jesse')	#'jesse'是一个实参,出现在函数调用中

3.传递实参——位置实参和关键字实参

  • 位置实参:形参和实参的顺序要相同
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')
  • 关键字实参:每个实参都由变量名和值组成,可不考虑顺序

    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(animal_type = 'hamster',pet_name = 'harry')
    

    使用关键字实参时,务必准确地指定函数定义中的形参名

  • 默认值

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

4.返回值

函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为返回值。在函数中,可使用return语句将值返回到调用函数的代码行。

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)

5.让实参可选——让可选的那个形参为空

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
musician = get_formatted_name('jimi','hendrix')
print(musician)
musician = get_formatted_name('john','hooker','lee')
print(musician)

七 类

1.创建类和根据类创建实例

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!")
my_dog = Dog('willie',6)
#调用属性
print("My dog's nmae is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
#调用方法
my_dog.sit()
my_dog.roll_over()
  • 类名Dog一般大写开头,实例my_dog一般小写。

  • __init__()初始化函数,两边各有两个下划线,每根据类创建一个实例时,就会运行,其中必须包含形参self,Python调用方法__init__()来创建实例时,将自动传入实参selfnameage可选,而且self必须位于最前面。

    • self.name = name用于获取存储在形参name中的值,并将其存储到变量name中,并且该变量被关联到当前创建的实例。
    • 创建实例my_dog时,主要时调用类Dog__init__()方法,只需给出nameage的实参即可。
  • self是一个指向实例本身的应用,让实例能够访问类中的属性和方法

    • 在实例中可直接通过my_dog.namemy_dog.age来使用nameage这两个属性。
    • 通过my_dog.sit()来访问类中的方法。
  • 类中的方法sit()roll_over()不需要其他信息,需包含形参self

2.给属性指定默认值

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.")
    #2.通过方法修改指定的值
    def update_odometer(self, mileage):
        """
        将里程表读数设置为指定的值
        禁止将里程表读数往回调
        """
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")
    #3.通过方法对属性的值进行递增
    def increment_odometer(self, miles):
        """将里程表读数增加指定的量"""
        self.odometer_reading += miles
my_new_car = Car('audi','a4',2016) #创建实例
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()


#1.直接修改属性的值(通过实例直接访问它)
my_new_car.odometer_reading = 23
my_new_car.read_odometer()

#2.通过方法修改属性的值——update_odometer(self,milegae)
my_new_car.update_odometer(23)
my_new_car.read_odometer()

#3.通过方法对属性的值进行递增
##实例化
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()
  • 类中每个属性都必须有初始值,哪怕这个值是0或空字符串。而且设置默认值后,__init__()无需包含为它提供初始值的形参。
  • 修改属性的值
    • 直接修改属性的值
    • 通过方法修改属性的值
    • 通过方法对属性的值进行递增

3.继承

一个类继承另一个类时,它将自动获得另一个类的所有属性和方法,原有得类称为父类,而新类称为子类,且新类还可以定义自己得属性和方法。

class Car():
	………………	#参考上一个代码块
class ElectricCar(Car):	#继承时,字类括号内指定父类得名称
    """
    电动汽车的独特之处
    """
    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.")
  • 创建子类时,父类必须包含在当前文件中,且位于子类前面。

  • 函数super()将父类和子类关联起来,super().__init__(make,model,year)让子类ElectricCar的实例包含父类所有的属性。

  • 在子类中可重新定义属性和方法,如:属性battery_size和方法describe_battery()

  • 重写父类的方法,只需在子类中定义一个与要重写父类方法同名的方法即可。

4.导入类

  • 导入单个类

在car.py的文件中,也称作模块,只包含Car类,将其导入my_car.py中,只需在my_car.py文件中:

from car import Car	#指从car中导入类Car
  • 从一个模块中导入多个类

如果模块car.py中包好多个类,如类Car、类Battery、类ElectricCar

from car import Car, Battery
  • 导入整个模块,之后便可通过module_name.class_name的方式访问模块中的类了
import car
my_beetle = car.Car('volkswagen','beetle',2016)
print(my_beetle.get_descriptive_name())
  • 导入模块中所有的类
from module_name import *

八 文件和异常

1.从文件中读取和写入数据

文件pi_digits.txt中的内容为:

3.1415926535
  8979323846
  2643383279
  • 读入整个文件
    • 函数open()接受一个文件名的参数时,则该文件必须存在于Python当前执行的文件所在的目录中。
    • 函数open()接受一个文件名的路径时,则对文件的位置不做要求。
    • 函数open()将pi_digits.txt文件及其内容的对象存储到了变量file_object中。
    • 函数read()用于读取这个文件的全部内容,并且read()到达文件末尾时返回一个空字符串,显示出来就是一个空行。可通过rstrip()来删除空白。
    • 关键字with在不再需要访问文件后将其关闭,不需要close()来关闭。
with open('pi_digits.txt') as file_object:
    contents = file_obejct.read()	#读取的内容作为一个长字符串存储在变量contents中
    print(contents)
  • 逐行读取——通过for循环实现
filename = 'pi_digits.txt'
with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())
  • 创建一个包含文件各行内容的列表
    • 使用with后,open()返回的文件对象只能在with代码块中使用。要在with代码块外使用,可将文件各行的内容存储在一个列表中。
    • readlines()用于读取文件中的每一行,并将其存储在一个列表中。
filename = 'pi_digits.txt'
with open(filename) as file_object:
    lines = file_object.readlines()
   
for line in lines:
    print(line.rstrip())

读取文本文件时, Python将其中的所有文本都解读为字符串。如果你读取的是数字,并要将其作为数值使用,就必须使用函数int()将其转换为整数,或使用函数float()将其转换为浮点数。

  • 写入空文件
    • 要将文本写入文件时,调用open()函数需要提供另一个实参,如:读取模式(‘r’)、写入模式(‘w’)、附加模式(‘a’),无参数时,默认是读取模式。
    • 当写入文件不存在时,opne()将自动创建。
    • wirte()将一个字符串写入文件,如果文件已经存在,以‘w’模式打开文件,将清空给文件内容。
    • Python只能将字符串写入文本文件中。要存储数据,必须先使用函数str()将其转换为字符串格式。
filename = 'programming.txt'
with open(filename, 'w') as file_object:
    file_object.write("I love programming.") #写入一行
    file_object.write("I love creating new games.") #写入多行
  • 附加到文件

    • 如果要给文件添加内容,而不是覆盖原有文件,可用附加模式(‘a’)打开文件。
    • 如果文件不存在,将创建一个空文件
    filename = 'programming.txt'
    with open(filename,'a') as file_obejct:
        file_object.write("I love programming.")
    

2.异常

  • 使用try-except代码块来处理可能引发的异常
try:
    print(5/0)
except: ZeroDivisionErroe:
    print("You can't divide by zero!")
    
  • 也可使用else代码块
while True:
    first_number = input("\nFirst number: ")
    if first_number == 'q':
        break
    second_number = input("Second number: ")
    try:
        answer = int(first_number)/int(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)

3.存储数据

用json(JavaScript Object Notation)来存储数据。

  • json.dump()

函数json.dump()接受两个实参:要存储的数据以及可用于存储数据的文件对象。

import json
numbers = [2,3,,5,7,11,13]
filename = 'numbers.json'
with open(filename,'w') as file_object:	#filename不存在,将自动创建文件
    json.dump(numbers,file_object)
  • json.load()

函数json.load()将文件name.json中的信息读取到变量中,只接受用于存储数据的文件对象。

import json
filename = 'username.json'	#username.json中已提前写入了内容
with open(filename) as file_object:
    username = json.load(file_obejct)

  • 重构:将代码划分为一系列完成具体工作的函数。