Chapter07 用户输入和while 循环
input()
age = input("How old are you? ") print(age) #默认为字符串 age = int(age) print(age) #强制类型转换
while
current_number = 1 while current_number <= 5: print(current_number) current_number += 1
自定义退出01
prompt = " Tell me something, and I will repeat it back to you:" prompt += " Enter 'quit' to end the program. " message = "" while message != 'quit': message = input() print(message) #输入为quit时,退出循环
自定义退出02
prompt = " Tell me something, and I will repeat it back to you:" prompt += " Enter 'quit' to end the program. " active = True while active: message = input(prompt) if message == 'quit': active = False else: print(message)
自定义退出3
prompt = " Tell me something, and I will repeat it back to you:" prompt += " Enter 'quit' to end the program. " active = True while active: message = input(prompt) if message == 'quit': break else: print(message)
处理列表和字典
删除特定元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(pets)
Chapter08函数
实参:函数完成其工作所需的一项信息
形参:调用函数时传递给函数的信息
实参的传递
#位置 describe_pet('harry', 'hamster') #关键字 describe_pet(pet_name='harry', animal_type='hamster') describe_pet(animal_type='hamster', pet_name='harry') #定义时默认值 def describe_pet(pet_name, animal_type='dog'):
返回值:
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)
传递任意数量的实参
def make_pizza(*toppings): """打印顾客点的所有配料""" print(toppings) make_pizza('pepperoni') make_pizza('mushrooms', 'green peppers', 'extra cheese')
形参名*toppings 中的星号让Python创建一个名为toppings 的空元组,并将收到的所有值都封装到这个元组中。
将函数存储在模块中
#pizza.py def make_pizza(size, *toppings): print(" Making a " + str(size) +"-inch pizza with the following toppings:") for topping in toppings: print("- " + topping) #makepizza.py import pizza pizza.make_pizza(16, 'pepperoni') pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
函数存在于pizza.py中,同文件夹情况下可通过另一文件引用。
Python读取这个文件时,代码行import pizza 让Python打开文件pizza.py,并将其中的所有函数都复制到这个程序中。你看不到复制的代码,因为这个程序运行时,Python在幕后复制这些代码。
#导入特定的函数 from pizza import make_pizza make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
as可以将模块名或者函数名重新命名:
#函数 from pizza import make_pizza as mp mp(16, 'pepperoni') mp(12, 'mushrooms', 'green peppers', 'extra cheese') #库 import pizza as p p.make_pizza(16, 'pepperoni') p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
导入所有函数:
from pizza import *
PS 建议代码行的长度不要超过79字符,这样只要编辑器窗口适中,就能看到整行代码。
Chapter09 类
根据约定,在Python中,首字母大写的名称指的是类。
9.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!")
a.类中的函数称为方法,方法__init__() 定义成了包含三个形参:self 、name 和age 。在这个方法的定义中,形参self 必不可少,还必须位于其他形参的前面。因为Python调用这个__init__() 方法来创建Dog 实例时,将自动传入实参self。注意__init__()前后均为两条下划线!!!!
b.定义的两个变量都有前缀self 。以self 为前缀的变量都可供类中的所有方法使用,我们还可以通过类的任何实例来访问这些变量。
其调用如下,通俗的说my_dog传递到self的位置:
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(" Your dog's name is " + your_dog.name.title() + ".") print("Your dog is " + str(your_dog.age) + " years old.") your_dog.sit()
内部变量引入、修改
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.") my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name()) my_new_car.read_odometer()
odometer_reading即为内部的变量,未在__init__里声明。
#1直接改 my_new_car.odometer_reading = 23 my_new_car.read_odometer() #2引进新方法来改 class Car(): --snip-- def update_odometer(self, mileage): #将里程表读数设置为指定的值""" self.odometer_reading = mileage 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() #3方法-递增 class Car(): --snip-- def update_odometer(self, mileage): --snip-- 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()
父类与子类
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())
super() 是一个特殊函数,帮助Python将父类和子类关联起来。这行代码让Python调用ElectricCar 的父类的方法__init__() ,让ElectricCar 实例包含父类的所有属性。父类也称为超类 (superclass),名称super因此而得名。
让一个类继承另一个类后,可添加区分子类和父类所需的新属性和方法。
对于父类的方法,只要它不符合子类模拟的实物的行为,都可对其进行重写。为此,可在子类中定义一个这样的方法,即它与要重写的父类方法同名。这样,Python将不会考虑这
个父类方法,而只关注你在子类中定义的相应方法。
9.5 Python标准库
略
Chapter10 文件和异常
10.1.1 读取整个文件
with open('pi_digits.txt') as file_object: contents = file_object.read() print(contents)
[1]关键字with 在不再需要访问文件后将其关闭;
[1-2]使用关键字with 时,open() 返回的文件对象只在with 代码块内可用。如果要在with 代码块外访问文件的内容,可在with 代码块内将文件的各行存储在一个列表中,并在with 代码块外使用该列表:你可以立即处理文件的各个部分,也可推迟到程序后面再处理。
[2]可以调用open() 和close() 来打开和关闭文件,但这样做时,如果程序存在bug,导致close() 语句未执行,文件将不会关闭。总之先别用这个吧。
[3]read() 到达文件末尾时返回一个空字符串,而将这个空字符串显示出来时就是一个空行。要删除多出来的空行,可在print 语句中使用rstrip();
with open('pi_digits.txt') as file_object: contents = file_object.read() print(contents.rstrip())
试验了一下不能读取汉字???应该有啥其他声明吧。
文件路径:
file_path = 'C:Usersehmatthesother_files ext_filesfilename.txt' with open(file_path) as file_object:
逐行输出:
filename = 'pi_digits.txt' with open(filename) as file_object: for line in file_object: print(line.rstrip())
将文件内容搞到with模块外操作(建立一个列表):
1.文件格式读取:
filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() for line in lines: print(line.rstrip())
2.字符串格式读取:
filename = 'pi_30_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) print(len(pi_string))
[1].strip()用于去除字符串内的空格;
[2].pi_string += line.strip() 字符串操作;
[替换操作]
>>> message = "I really like dogs." >>> message.replace('dog', 'cat') 'I really like cats.'
写入文件
filename = 'programming.txt' with open(filename, 'w') as file_object: file_object.write("I love programming.")
[1]在这个示例中,调用open() 时提供了两个实参。第一个实参也是要打开的文件的名称;第二个实参('w' )告诉Python,我们要以写入模式 打开这个文件。打开文件时,可指定读取模式 ('r' )、写入模式 ('w' )、附加模式 ('a' )(添加内容,而不是覆盖原有的内容)或让你能够读取和写入文件的模式('r+' )。如果你省略了模式实参,Python将以默认的只读模式打开文件。
[2]如果你要写入的文件不存在,函数open() 将自动创建它。然而,以写入('w' )模式打开文件时千万要小心,因为如果指定的文件已经存在,Python将在返回文件对象前清空该文件。
写入多行文件
filename = 'programming.txt' with open(filename, 'w') as file_object: file_object.write("I love programming. ") file_object.write("I love creating new games. ")
附加入文件;
filename = 'programming.txt' with open(filename, 'a') as file_object: file_object.write("I also love finding meaning in large datasets. ") file_object.write("I love creating apps that can run in a browser. "