8.2传递实参
向函数传递实参的方式:位置实参,这要求实参的顺序与形参相同;关键字实参,其中每个实参由变量名和值组成;还可使用列表和字典
def get_formatted_name(first_name,last_name,middle_name=''):
# if middle_name:
# full_name = f"{first_name} {middle_name} {last_name}"
# else:
full_name = f"{first_name} {middle_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
8.3.3返回字典
def build_person(first_name,last_name,age=None):
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}
def get_formatted_name(first_name,last_name):
full_name = f"{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(f"{formatted_name}")
Please tell me your name:
(enter 'q' at any time to quit)
First name:q
def print_models(unprinted_designs,completed_models):
while unprinted_designs:
current_design = unprinted_designs.pop()
print(f"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 = ['phone 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:phone case
The following models have been printed:
dodecahedron
robot pendant
phone case
第九章 类
9.1.1创建Dog类
class Dog():
def __init__(self,name,age):
self.name = name
self.age = age
def sit(self):
print(f"{self.name} is now sitting")
def roll_over(self):
print(f"{self.name} rolled over!")
my_dog = Dog('willie',6)
print(f"My dog's name is {my_dog.name}")
print(f"My dog is {my_dog.age} years old")
My dog's name is willie
My dog is 6 years old
my_dog.sit()
my_dog.roll_over()
willie is now sitting
willie rolled over!
9.2.1Car类
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 = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odmeter(self):
print(f"This car has {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_new_car = Car('audi','a4',2019)
# print(my_new_car.get_descriptive_name())
# my_new_car.update_odometer(22)
# # my_new_car.update_odometer(20)
# my_new_car.increment_odometer(1000)
# my_new_car.read_odmeter()
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
self.battery_size = 75
def describe_battery(self):
print(f"This car has a {self.battery_size}-KWh battery.")
my_tesla = ElectricCar('tesla','model',2019)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
2019 Tesla Model
This car has a 75-KWh battery.
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 = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odmeter(self):
print(f"This car has {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 Battery:
def __init__(self,battery_size=75):
self.battery_size = battery_size
def describe_battery(self):
print(f"This car has a {self.battery_size}-KWh battery.")
def get_range(self):
if self.battery_size == 75:
range = 260
elif self.battery_size == 100:
range = 315
print(f"This car can go about {range} miles on a full charge")
class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
self.battery = Battery(100)
my_tesla = ElectricCar('tesla','model',2019)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
2019 Tesla Model
This car has a 100-KWh battery.
This car can go about 315 miles on a full charge
第十章 文件和异常
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
3.1415926535
8979323846
2643383279
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(f"{pi_string}...")
3.141592653589793238462643383279...
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')
filename = 'programming.txt'
with open(filename,'a') as file_object:
file_object.write('I also Love programming.\n')
file_object.write('I also Love creating new games.\n')
处理异常
filename = 'alice.txt'
try:
with open(filename,encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry,the file {filename} does not exist")
Sorry,the file alice.txt does not exist
10.4.1 使用json.dump()和json.load()
import json
numbers = [2,3,5,7,11,13]
filename = 'numbers.json'
with open(filename,'w') as f:
json.dump(numbers,f)
import json
filename = 'numbers.json'
with open(filename) as f:
numbers = json.load(f)
print(numbers)
[2, 3, 5, 7, 11, 13]
import json
username = input("What is your name?")
filename = 'username.json'
with open(filename,'w',encoding='utf-8') as f:
json.dump(username,f)
print(f"We'll remember you when you come back,{username}!")
What is your name?w
We'll remember you when you come back,w!
import json
filename = 'username.json'
with open(filename,encoding='utf-8') as f:
username = json.load(f)
print(f"Welcome back,{username}!")
Welcome back,w!
import json
def greet_user():
filename = 'username.json'
try:
with open(filename,encoding='UTF-8') as f:
username = json.load(f)
except FileNotFoundError:
username = input("What is your name?")
with open(filename,'w',encoding='utf-8') as f:
json.dump(username,f)
print(f"We'll remember you when you come back,{username}!")
else:
print(f"Welcome back,{username}!")
greet_user()
Welcome back,w!
import json
def get_sorted_username():
filename = 'username.json'
try:
with open(filename,encoding='UTF-8') as f:
username = json.load(f)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
username = input("What is your name?")
filename = 'username.json'
with open(filename,'w',encoding='utf-8') as f:
json.dump(username,f)
return username
def greet_user():
username = get_sorted_username()
if username:
print(f"Welcome back,{username}!")
else:
username = get_new_username()
print(f"We'll remember you when you come back,{username}!")
greet_user()
Welcome back,w!