列表名 = [表达式 for 变量 in 列表名 if 条件] # 例子:生成一列数字的平方 squares = [x**2for x inrange(1, 10)] print(squares) # 例子:生成所包含数字的平方和大于100的数字的列表 greater_than_100 = [x for x inrange(1, 20) if x**2 > 100] print(greater_than_100)
3.3 使用列表的一部分
切片
1 2 3 4 5 6 7
players = ['charles','martina','michael','florence','eli'] print(players[0:3]) # 0 to 2 print(players[1:4]) # 1 to 3 print(players[:4]) # 0 to 3 print(players[2:]) # 2 to end print(players[-3:]) #last 3 print(players[1:4:2]) # 1 to 3, every other one
遍历切片
1 2 3 4
players = ['charles','martina','michael','florence','eli'] print("Here are the first three aplayers on my team:") for player in players[:3]: print(player.title())
for request_topping in request_toppings: if request_topping == 'green peppers': print("Sorry,we are out of green peppers right now.") else: print(f"Adding {request_topping}.") print("\nFinished making your pizza!")
确定列表为空
1 2 3 4 5 6 7 8
request_toppings = []
if request_toppings: for request_topping in request_toppings: print(f"Adding {request_topping}.") print(f"\nFinished making your pizza!") else: print("Are you sure you want a plain pizza?")
列表为空时返回False,不为空时返回True,
使用多个列表
1 2 3 4 5 6 7 8 9 10
# 列表一包含店内供应的配料,列表二包含顾客的请求,检查顾客的请求是否在店内供应的配料中,再决定是否在比萨中添加它。 available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese'] request_toppings = ['mushrooms', 'french fires', 'extra cheese'] for request_topping in request_toppings: if request_topping in available_toppings: print(f"Adding {request_topping}.") else : print(f"Sorry, we don't have {request_topping}.") print("\nFinished making your pizza!")
aliens = [alien_0, alien_1, alien_2] for alien in aliens: print(alien)
1 2 3 4 5 6 7 8 9
aliens = [] for alien_number inrange(30): new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} aliens.append(new_alien) for alien in aliens[:5]: print(alien) print("```")
print(f"Total number of aliens: {len(aliens)}")
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
aliens = [] for alien_number inrange(30): new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} aliens.append(new_alien) for alien in aliens[:5]: print(alien) print("```")
print(f"Total number of aliens: {len(aliens)}")
for alien in aliens[:3]: if alien['color'] == 'green': alien['color'] = 'yellow' alien['speed'] = 'medium' alien['points'] = 10 for alien in aliens[:5]: print(alien)
for name,languages in favorite_languages.items(): iflen(languages)!=1: print(f"\n{name.title()}'s favorite languages are:") for language in languages: print(f"\t{language.title()}") else: print(f"\n{name.title()}'s favorite language is:") for language in languages: print(f"\t{language.title()}")
height = input("How tall are you,in inches?") height = int (height) if height >= 48: print("\nYou're tall enough to ride!") else: print("\nYou'll be able to ride when you're a little older.")
求模运算符
求模运算符(%)可以将两个数相除并返回余数
判断是奇数还是偶数
1 2 3 4 5 6 7
number = input("Enter a number,and I'll tell you if it's even or odd:") number = int(number)
if number % 2 == 0: print(f"\nThe number {number} is even.") else: print(f"\nThe number {number} is odd.")
while unconfirmed_users: current_user = unconfirmed_users.pop() print(f"Verifying user: {current_user.title()}") confirmed_users.append(current_user) print("\nThe following users have benn confirmed:") for confirmed_user in confirmed_users: print(confirmed_user.title())
whileTrue: 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
defshow_completed_models(completed_models): print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model)
classDog: # 一次模拟小狗的简单尝试 def__init__(self,name,age): # 初始化属性name和age self.name = name self.age = age defsit(self): # 模拟小狗收到命令时坐下 print(f"{self.name} is now siting.") defroll_over(self): # 模拟小狗收到命令时打滚 print(f"{self.name} rolled over!")
my_dog = Dog('willie',6) your_dog = Dog('Lucy',3) print(f"My dog's name is {my_dog.name}") print(f"My dog is {my_dog.age} years old.") my_dog.sit() my_dog.roll_over() print(f"My dog's name is {your_dog.name}") print(f"My dog is {your_dog.age} years old.") your_dog.sit()
8.2 使用类和实例
Car类
1 2 3 4 5 6 7 8 9 10 11 12 13
classCar: # 一次模拟汽车的简单尝试 def__init__(self,make,model,year): self.make = make self.model = model self.year = year defget_descriptive_name(self): long_name = f"{self.year}{self.make}{self.model}" return long_name.title() my_new_car = Car('audi','a4','2024') print(my_new_car.get_descriptive_name())
给属性指定默认值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classCar: # 一次模拟汽车的简单尝试 def__init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 defget_descriptive_name(self): long_name = f"{self.year}{self.make}{self.model}" return long_name.title()
defread_odometer(self): print(f"This car has {self.odometer_reading} miles on it.") my_new_car = Car('audi','a4','2024') print(my_new_car.get_descriptive_name()) my_new_car.read_odometer()
classCar: # 一次模拟汽车的简单尝试 def__init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 defget_descriptive_name(self): long_name = f"{self.year}{self.make}{self.model}" return long_name.title()
defread_odometer(self): print(f"This car has {self.odometer_reading} miles on it.") my_new_car = Car('audi','a4','2024') print(my_new_car.get_descriptive_name())
classCar: # 一次模拟汽车的简单尝试 def__init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 defget_descriptive_name(self): long_name = f"{self.year}{self.make}{self.model}" return long_name.title()
defread_odometer(self): print(f"This car has {self.odometer_reading} miles on it.") defupdate_odometer(self,nileage): self.odometer_reading = nileage my_new_car = Car('audi','a4','2024') print(my_new_car.get_descriptive_name())
classCar: # 一次模拟汽车的简单尝试 def__init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 defget_descriptive_name(self): long_name = f"{self.year}{self.make}{self.model}" return long_name.title()
defread_odometer(self): print(f"This car has {self.odometer_reading} miles on it.") defupdate_odometer(self,nileage): self.odometer_reading = nileage defincrement_odometer(self,miles): self.odometer_reading += miles
classCar: # 一次模拟汽车的简单尝试 def__init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 defget_descriptive_name(self): long_name = f"{self.year}{self.make}{self.model}" return long_name.title()
defread_odometer(self): print(f"This car has {self.odometer_reading} miles on it.") defupdate_odometer(self,nileage): self.odometer_reading = nileage defincrement_odometer(self,miles): self.odometer_reading += miles
defdescribe_battery(self): print(f"This car has a {self.battery_size}-kWh battery.") my_leaf = ElectricCar('nissan','leaf','2024') print(my_leaf.get_descriptive_name()) my_leaf.describe_battery()
path = Path('test.txt') try: contents = path.read_text(encoding='utf-8') except FileNotFoundError: print("Sorry, the file does not exist.")
分析文本
1 2 3 4 5 6 7 8 9 10 11
from pathlib import Path
path = Path('test.txt') try: contents = path.read_text(encoding='utf-8') except FileNotFoundError: print("Sorry, the file does not exist.") else: words = contents.split() num_words = len(words) print(f"The file {path} has about {num_words} words.")
使用多个文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
from pathlib import Path
defcount_words(path): try: contents = path.read_text(encoding='utf-8') except FileNotFoundError: print(f"Sorry, the file {path} does not exist.") else: words = contents.split() num_words = len(words) print(f"The file {path} has about {num_words} words.")
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] for filename in filenames: path = Path(filename) count_words(path)
defget_stored_username(path): if path.exists(): contents = path.read_text() return json.loads(contents) else: returnNone defget_new_username(path): username = input("What is your name?") path.write_text(json.dumps(username)) return username defgreet_user(): path = Path('username.json') username = get_stored_username(path) if username: print(f"Welcome back,{username}") else: username = get_new_username(path) print(f"We'll remember you next time,{username}") greet_user()
第十章 测试代码
10.1 使用pip安装pytest
更新pip
1
python -m pip install --upgrade pip
1
python -m pip install --upgrade <package>
安装pytest
1
python -m pip install --user pytest
1
python -m pip install --user <package>
10.2 测试函数
测试函数中验证代码格式assert 变量名 == 指定的值
10.3 测试类
各种断言
| 断言 | 用途 |
| -------- | -------- | ----|
| assert a == b | 断言两个值相等 |
| assert a != b | 断言两个值不等 |
| assert a | 断言a的布尔值为True |
| assert assert not a | 断言a的布尔值为False |
| assert element in list | 断言元素在列表中 |
| assert element not in list | 断言元素不在列表中 |