python编程入门

news/2024/4/28 12:16:18/文章来源:https://blog.csdn.net/qq_30614345/article/details/137112790

1、第1章-起步

print("Hello Python interpreter!")
$ python chapter1\hello_world.py
Hello Python interpreter!

2、第2章-变量和简单数据类型

## 运行hello_world
print("Hello Python world!")## 定义变量
messgae = "Hello Python world!"
print(messgae)## 重新赋值变量
message = "Hello Python Crash Course world!"
print(message)## 字符串表示
print("""This is a string.""")
print('This is a string.')
print("This is a string.")## 系统函数
name = "ada lovelace"
print(name.title())
print(name.upper())
print(name.lower())## 格式化
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name)
print(f"Hello, {full_name.title()}!")message = f"Hello, {full_name.title()}!"
print(message)full_name = "{} {}".format(first_name, last_name)
print(full_name)## 制表符
print("\tPython")
print("Languages:\nPython\nC\nJavaScript")## 删除空白
favorite_language = ' python '
print(favorite_language)
print(favorite_language.lstrip())
print(favorite_language.strip())
print(favorite_language.rstrip())## 数字操作
print(2 + 3)
print(3 - 2)
print(2 * 3)
print(3 / 2)
print(3 ** 2)
print(3 ** 3)
print(10 ** 6)
print(2 + 3*4)
print((2 + 3) * 4)
print(0.1 + 0.1)
print(0.2 + 0.2)
print(2 * 0.1)
print(2 * 0.2)
print(0.2 + 0.1)
print(3 * 0.1)
print(4/2)
print(1 + 2.0)
print(2 * 3.0)
print(3.0 ** 2)## 数中的下划线
universe_age = 14_000_000_000
print(universe_age)## 同时给多个变量赋值
x, y, z = 0, 0, 0## 常量
MAX_CONNECTIONS = 5000# 如何编写注释
# 向大家问好。
import this

3、第3章-列表简介

## 列表是什么
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)## 访问列表元素
print(bicycles[0])
print(bicycles[0].title())
print(bicycles[1])
print(bicycles[3])
print(bicycles[-1])## 使用列表中的各个值
message = f"My first bicycle was a {bicycles[0].title()}."
print(message)## 修改列表元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)## 在列表末尾添加元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)## 在列表中插入元素
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)## 从列表中删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[1]
print(motorcycles)## 使用方法pop()删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)motorcycles = ['honda', 'yamaha', 'suzuki']
last_owned = motorcycles.pop()
print(f"The last motorcycle I owned was a {last_owned.title()}.")## 弹出列表中任何位置处的元素
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print(f"The first motorcycle I owned was a {first_owned.title()}.")## 根据值删除元素
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
too_expensive = 'ducati'
motorcycles.remove(too_expensive)
print(motorcycles)
print(f"\nA {too_expensive.title()} is too expensive for me.")## 使用方法sort()对列表永久排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)##还可以按与字母顺序相反的顺序排列列表元素,只需向sort()方法传递参数reverse=True即可
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)## 使用函数sorted()对列表临时排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)## 倒着打印列表
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)## 确定列表的长度
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(len(cars))## 使用列表时避免索引错误
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles[3])motorcycles = []
print(motorcycles[-1])

4、第4章-操作列表

## 遍历整个列表
# for循环需要进行缩进
magicians = ['alice', 'david', 'carolina']
for magician in magicians:print(magician)## 在for循环中执行更多操作
magicians = ['alice', 'david', 'carolina']
for magician in magicians:print(f"{magician.title()}, that was a great trick!")## 在for循环结束后执行一些操作
magicians = ['alice', 'david', 'carolina']
for magician in magicians:print(f"{magician.title()}, that was a great trick!")print(f"I can't wait to see your next trick, {magician.title()}.")
print("Thank you, everyone. That was a great magic show!")## 创建数值列表
## 使用函数range()
for value in range(1, 5):print(value)for value in range(1, 6):print(value)## 使用range()创建数字列表
numbers = list(range(1, 6))
print(numbers)even_numbers = list(range(2, 11, 2))
print(even_numbers)squares = []
for value in range(1, 11):square = value ** 2squares.append(square)
print(squares)squares = []
for value in range(1,11):squares.append(value**2)
print(squares)## 对数字列表执行简单的统计计算
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
print(max(digits))
print(sum(digits))## 列表解析
squares = [value**2 for value in range(1, 11)]
print(squares)## 切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4])players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:])players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:])## 遍历切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:print(player.title())## 复制列表
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)# 深拷贝
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
# ['pizza', 'falafel', 'carrot cake', 'cannoli']
print(my_foods)
print("\nMy friend's favorite foods are:")
# ['pizza', 'falafel', 'carrot cake', 'ice cream']
print(friend_foods)# 浅拷贝
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
# ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
print(my_foods)
print("\nMy friend's favorite foods are:")
# ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
print(friend_foods)## 元组
# 定义元组
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])dimensions = (200, 50)
# 试图修改元组的操作是被禁止的
# dimensions[0] = 250my_t = (3,)
print(my_t)## 遍历元组中的所有值
dimensions = (200, 50)
for dimension in dimensions:print(dimension)dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:print(dimension)dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:print(dimension)

5、第5章-if语句

## 一个简单示例
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:if car == 'bmw':print(car.upper())else:print(car.title())## 检查是否相等
car = 'bmw'
print(car == 'bmw')car = 'audi'
print(car == 'bmw')## 检查是否相等时忽略大小写
car = 'Audi'
print(car == 'audi')car = 'Audi'
print(car.lower() == 'audi')car = 'Audi'
print(car.lower() == 'audi')## 检查是否不相等
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':print("Hold the anchovies!")## 数值比较
age = 18
print(age == 18)answer = 17
if answer != 42:print("That is not the correct answer. Please try again!")age = 19
print(age < 21)
print(age <= 21)
print(age > 21) 
print(age >= 21)## 检查多个条件
## 使用and 检查多个条件
age_0 = 22
age_1 = 18
print(age_0 >= 21 and age_1 >= 21)
age_1 = 22
print(age_0 >= 21 and age_1 >= 21)
print((age_0 >= 21) and (age_1 >= 21))## 使用or检查多个条件
age_0 = 22
age_1 = 18
print(age_0 >= 21 or age_1 >= 21)
age_0 = 18
print(age_0 >= 21 or age_1 >= 21)## 检查特定值是否包含在列表中
requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in requested_toppings)
print('pepperoni' in requested_toppings)## 检查特定值是否不包含在列表中
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:print(f"{user.title()}, you can post a response if you wish.")## 布尔表达式
game_active = True
can_edit = Falsecar = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False.")
print(car == 'audi')## 简单的if 语句
age = 19
if age >= 18:print("You are old enough to vote!")age = 19
if age >= 18:print("You are old enough to vote!")print("Have you registered to vote yet?")## 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.")print("Please register to vote as soon as you turn 18!")## if-elif-else 结构
age = 12
if age < 4:print("Your admission cost is $0.")
elif age < 18:print("Your admission cost is $25.")
else:print("Your admission cost is $40.")age = 12
if age < 4:price = 0
elif age < 18:price = 25
else:price = 40
print(f"Your admission cost is ${price}.")## 使用多个elif 代码块
age = 12
if age < 4:price = 0
elif age < 18:price = 25
elif age < 65:price = 40
else:price = 20
print(f"Your admission cost is ${price}.")## 省略else代码块
age = 12
if age < 4:price = 0
elif age < 18:price = 25
elif age < 65:price = 40
elif age >= 65:price = 20
print(f"Your admission cost is ${price}.")## 测试多个条件
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:print("Adding extra cheese.")
print("\nFinished making your pizza!")requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:print("Adding mushrooms.")
elif 'pepperoni' in requested_toppings:print("Adding pepperoni.")
elif 'extra cheese' in requested_toppings:print("Adding extra cheese.")
print("\nFinished making your pizza!")## 检查特殊元素
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:print(f"Adding {requested_topping}.")
print("\nFinished making your pizza!")requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:if requested_topping == 'green peppers':print("Sorry, we are out of green peppers right now.")else:print(f"Adding {requested_topping}.")
print("\nFinished making your pizza!")## 确定列表不是空的
# Python将在列表至少包含一个元素时返回True,并在列表为空时返回False
requested_toppings = []
if requested_toppings:for requested_topping in requested_toppings:print(f"Adding {requested_topping}.")print("\nFinished making your pizza!")else:print("Are you sure you want a plain pizza?")## 使用多个列表
available_toppings = ['mushrooms', 'olives', 'green peppers','pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:if requested_topping in available_toppings:print(f"Adding {requested_topping}.")else:print(f"Sorry, we don't have {requested_topping}.")
print("\nFinished making your pizza!")## 设置if语句的格式
# 在诸如== 、>= 和<= 等比较运算符两边各添加一个空格
# if age < 4:

6、第6章-字典

## 一个简单的字典
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])## 使用字典
alien_0 = {'color': 'green'}
print(alien_0['color'])## 访问字典中的值
alien_0 = {'color': 'green', 'points': 5}
new_points = alien_0['points']
print(f"You just earned {new_points} points!")## 添加键值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)## 先创建一个空字典
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)## 修改字典中的值
alien_0 = {'color': 'green'}
print(f"The alien is {alien_0['color']}.")
alien_0['color'] = 'yellow'
print(f"The alien is now {alien_0['color']}.")alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print(f"Original position: {alien_0['x_position']}")
# 向右移动外星人。
# 根据当前速度确定将外星人向右移动多远。
if alien_0['speed'] == 'slow':x_increment = 1
elif alien_0['speed'] == 'medium':x_increment = 2
else:# 这个外星人的移动速度肯定很快。x_increment = 3
# 新位置为旧位置加上移动距离。
alien_0['x_position'] = alien_0['x_position'] + x_increment
print(f"New position: {alien_0['x_position']}")
alien_0['speed'] = 'fast'## 删除键值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)## 由类似对象组成的字典
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
language = favorite_languages['sarah'].title()
print(f"Sarah's favorite language is {language}.")## 使用get()来访问值
alien_0 = {'color': 'green', 'speed': 'slow'}
point_value = alien_0.get('points', 'No point value assigned.')
print(point_value)## 遍历所有键值对
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():print(f"\nKey: {key}")print(f"Value: {value}")favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_languages.items():print(f"{name.title()}'s favorite language is {language.title()}")## 遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():print(name.title())
# 等价
for name in favorite_languages:print(name.title())friends = ['phil', 'sarah']
for name in favorite_languages.keys():print(f"Hi {name.title()}.")if name in friends:language = favorite_languages[name].title()
print(f"\t{name.title()}, I see you love {language}!")favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
if 'erin' not in favorite_languages.keys():print("Erin, please take our poll!")## 按特定顺序遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):print(f"{name.title()}, thank you for taking the poll.")## 遍历字典中的所有值
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("The following languages have been mentioned:")
for language in favorite_languages.values():print(language.title())## 为剔除重复项,可使用集合
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):print(language.title())## 可使用一对花括号直接创建集合,并在其中用逗号分隔元素
languages = {'python', 'ruby', 'python', 'c'}
print(languages)## 嵌套字典列表
alien_0 = {'color': 'green', '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)# 创建一个用于存储外星人的空列表。
aliens = []
# 创建30个绿色的外星人。
for alien_number in range(30):new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}aliens.append(new_alien)
# 显示前5个外星人
for alien in aliens[:5]:print(alien)
print("...")
# 显示创建了多少个外星人。
print(f"Total number of aliens: {len(aliens)}")# 创建一个用于存储外星人的空列表。
aliens = []
# 创建30个绿色的外星人。
for alien_number in range (30):new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}aliens.append(new_alien)
for alien in aliens[:3]:if alien['color'] == 'green':alien['color'] = 'yellow'alien['speed'] = 'medium'alien['points'] = 10elif alien['color'] == 'yellow':alien['color'] = 'red'alien['speed'] = 'fast'alien['points'] = 15
# 显示前5个外星人
for alien in aliens[:5]:print(alien)
print("...")## 在字典中存储列表
# 存储所点比萨的信息。
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
# 概述所点的比萨。
print(f"You ordered a {pizza['crust']}-crust pizza "
"with the following toppings:")
for topping in pizza['toppings']:print(f"{topping}")favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():print(f"\n{name.title()}'s favorite languages are:")
for language in languages:print(f"\t{language.title()}")## 在字典中存储字典
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():print(f"\nUsername: {username}")full_name = f"{user_info['first']} {user_info['last']}"location = user_info['location']print(f"\tFull name: {full_name.title()}")print(f"\tLocation: {location.title()}")

7、第7章-用户输入和while 循环

## 函数input()
message = input("Tell me something, and I will repeat it back to you: ")
print(message)## 编写清晰的程序
name = input("Please enter your name: ")
print(f"\nHello, {name}!")prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print(f"\nHello, {name}!")## 使用int()来获取数值输入
age = input("How old are you? ")
print(age)
age = int(age)
print(age >= 18)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.")## 求模运算符
print(4 % 3)
print(5 % 3)
print(6 % 3)
print(7 % 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(f"\nThe number {number} is even.")
else:print(f"\nThe number {number} is odd.")## 使用while 循环
current_number = 1
while current_number <= 5:print(current_number)current_number += 1## 让用户选择何时退出
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)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)if message != 'quit':print(message)## 使用标志
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:message = input(prompt)if message == 'quit':active = Falseelse:print(message)## 使用break退出循环
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:city = input(prompt)if city == 'quit':breakelse:print(f"I'd love to go to {city.title()}!")## 在循环中使用continue
current_number = 0
while current_number < 10:current_number += 1if current_number % 2 == 0:continueprint(current_number)## 避免无限循环
x = 1
while x <= 5:print(x)    x += 1## 在列表之间移动元素
# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表。
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# 验证每个用户,直到没有未验证用户为止。
# 将每个经过验证的用户都移到已验证用户列表中。
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 been confirmed:")
for confirmed_user in confirmed_users:print(confirmed_user.title())## 删除为特定值的所有列表元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:pets.remove('cat')
print(pets)## 使用用户输入来填充字典
responses = {}
# 设置一个标志,指出调查是否继续。
polling_active = True
while polling_active:# 示输入被调查者的名字和回答。name = input("\nWhat is your name? ")response = input("Which mountain would you like to climb someday? ")# 将回答存储在字典中。responses[name] = response# 看看是否还有人要参与调查。repeat = input("Would you like to let another person respond? (yes/ no) ")if repeat == 'no':polling_active = False
# 调查结束,显示结果。
print("\n--- Poll Results ---")
for name, response in responses.items():print(f"{name} would like to climb {response}.")

8、第8章-函数

## 定义函数
def greet_user():"""显示简单的问候语。"""print("Hello!")
greet_user()## 向函数传递信息
def greet_user(username):"""显示简单的问候语。"""print(f"Hello, {username.title()}!")
greet_user('jesse')## 位置实参
def describe_pet(animal_type, pet_name):"""显示宠物的信息。"""print(f"\nI have a {animal_type}.")print(f"My {animal_type}'s name is {pet_name.title()}.")
# 多次调用函数
describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')## 位置实参的顺序很重要
def describe_pet(animal_type, pet_name):"""显示宠物的信息。"""print(f"\nI have a {animal_type}.")print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('harry', 'hamster')## 关键字实参
def describe_pet(animal_type, pet_name):"""显示宠物的信息。"""print(f"\nI have a {animal_type}.")print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(animal_type='hamster', pet_name='harry')## 默认值
def describe_pet(pet_name, animal_type='dog'):"""显示宠物的信息。"""print(f"\nI have a {animal_type}.")print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(pet_name='willie')
describe_pet('willie')
describe_pet(pet_name='harry', animal_type='hamster')## 等效的函数调用
# 下面对这个函数的所有调用都可行
# 一条名为Willie的小狗
describe_pet('willie')
describe_pet(pet_name='willie')
# 一只名为Harry的仓鼠
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name='harry')## 避免实参错误
def describe_pet(animal_type, pet_name):"""显示宠物的信息。"""print(f"\nI have a {animal_type}.")print(f"My {animal_type}'s name is {pet_name.title()}.")
# 错误调用
# describe_pet()## 返回简单值
def get_formatted_name(first_name, last_name):"""返回整洁的姓名。"""full_name = f"{first_name} {last_name}"return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)## 让实参变成可选的
def get_formatted_name(first_name, middle_name, last_name):"""返回整洁的姓名。"""full_name = f"{first_name} {middle_name} {last_name}"return full_name.title()
musician = get_formatted_name('john', 'lee', 'hooker')
print(musician)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} {last_name}"return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)## 返回字典
def build_person(first_name, last_name):"""返回一个字典,其中包含有关一个人的信息。"""person = {'first': first_name, 'last': last_name}return person
musician = build_person('jimi', 'hendrix')
print(musician)# 特殊值None(表示变量没有值),可将None视为占位值,在条件测试中None相当于False
def build_person(first_name, last_name, age=None):"""返回一个字典,其中包含有关一个人的信息。"""person = {'first': first_name, 'last': last_name}if age:person['age'] = agereturn person
musician = build_person('jimi', 'hendrix', age=27)
print(musician)## 结合使用函数和while循环
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:")f_name = input("First name: ")l_name = input("Last name: ")formatted_name = get_formatted_name(f_name, l_name)print(f"\nHello, {formatted_name}!")
'''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':breakl_name = input("Last name: ")if l_name == 'q':breakformatted_name = get_formatted_name(f_name, l_name)print(f"\nHello, {formatted_name}!")## 传递列表
def greet_users(names):"""向列表中的每位用户发出简单的问候。"""for name in names:msg = f"Hello, {name.title()}!"print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)  ## 在函数中修改列表
# 首先创建一个列表,其中包含一些要打印的设计。
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
# 模拟打印每个设计,直到没有未打印的设计为止。
# 打印每个设计后,都将其移到列表completed_models中。
while unprinted_designs:current_design = unprinted_designs.pop()print(f"Printing model: {current_design}")completed_models.append(current_design)
# 显示打印好的所有模型。
print("\nThe following models have been printed:")
for completed_model in completed_models:print(completed_model)# 为重新组织这些代码,可编写两个函数,每个都做一件具体的工作。
def print_models(unprinted_designs, completed_models):""" 模拟打印每个设计,直到没有未打印的设计为止。打印每个设计后,都将其移到列表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)## 禁止函数修改列表
# 为解决这个问题,可向函数传递列表的副本而非原件。这样,函数所做的任何修改都只影响副本,而原件丝毫不受影响。
# 要将列表的副本传递给函数,可以像下面这样做:function_name(list_name_[:])
print_models(unprinted_designs[:], completed_models)## 传递任意数量的实参
def make_pizza(*toppings):"""打印顾客点的所有配料。"""print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')def make_pizza(*toppings):"""概述要制作的比萨。"""print("\nMaking a pizza with the following toppings:")for topping in toppings:print(f"- {topping}")
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')## 结合使用位置实参和任意数量实参
def make_pizza(size, *toppings):"""概述要制作的比萨。"""print(f"\nMaking a {size}-inch pizza with the following toppings:")for topping in toppings:print(f"- {topping}")
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')## 使用任意数量的关键字实参
def build_profile(first, last, **user_info):"""创建一个字典,其中包含我们知道的有关用户的一切。"""user_info['first_name'] = firstuser_info['last_name'] = lastreturn user_info
user_profile = build_profile('albert', 'einstein',location='princeton',field='physics')
# {'location': 'princeton', 'field': 'physics','first_name': 'albert', 'last_name': 'einstein'}
print(user_profile)## 导入整个模块
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')## 导入特定的函数
# from module_name import function_name
# from module_name import function_0, function_1, function_2
from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')## 使用as给函数指定别名
# from module_name import function_name as fn
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')## 导入模块中的所有函数
# 使用星号(*)运算符可让Python导入模块中的所有函数
# from module_name import *
from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')## 函数编写指南
# 给形参指定默认值时,等号两边不要有空格
# def function_name(parameter_0, parameter_1='default value')
# 对于函数调用中的关键字实参,也应遵循这种约定
# function_name(value_0, parameter_1='value')
# 大多数编辑器会自动对齐后续参数列表行,使其缩进程度与你给第一个参数列表行指定的缩进程度相同:
'''
def function_name(parameter_0, parameter_1, parameter_2,parameter_3, parameter_4, parameter_5):
'''

9、第9章-类

## 创建和使用类
# 创建Dog类
# 务必确保__init__()的两边都有两个下划线
class Dog:"""一次模拟小狗的简单尝试。"""def __init__(self, name, age):"""初始化属性name和age。"""self.name = nameself.age = agedef 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.sit()
my_dog.roll_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()
print(f"\nYour dog's name is {your_dog.name}.")
print(f"Your dog is {your_dog.age} years old.")
your_dog.sit()## 使用类和实例
# Car类
class Car:"""一次模拟汽车的简单尝试。"""def __init__(self, make, model, year):"""初始化描述汽车的属性。"""self.make = makeself.model = modelself.year = yeardef get_descriptive_name(self):"""返回整洁的描述性信息。"""        long_name = f"{self.year} {self.make} {self.model}"return long_name.title()my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())## 给属性指定默认值
class Car:def __init__(self, make, model, year):"""初始化描述汽车的属性。"""self.make = makeself.model = modelself.year = yearself.odometer_reading = 0def get_descriptive_name(self):print()def read_odometer(self):"""打印一条指出汽车里程的消息。"""print(f"This car has {self.odometer_reading} miles on it.")my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()## 修改属性的值
## 直接修改属性的值
my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23
my_new_car.read_odometer()## 通过方法修改属性的值
class Car:def __init__(self, make, model, year):"""初始化描述汽车的属性。"""self.make = makeself.model = modelself.year = yearself.odometer_reading = 0def get_descriptive_name(self):print()def read_odometer(self):"""打印一条指出汽车里程的消息。"""print(f"This car has {self.odometer_reading} miles on it.")def update_odometer(self, mileage):"""将里程表读数设置为指定的值。"""self.odometer_reading = mileagemy_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(23)
my_new_car.read_odometer()class Car:def __init__(self, make, model, year):"""初始化描述汽车的属性。"""self.make = makeself.model = modelself.year = yearself.odometer_reading = 0def get_descriptive_name(self):print()def read_odometer(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 = mileageelse:print("You can't roll back an odometer!")## 通过方法对属性的值进行递增
class Car:def __init__(self, make, model, year):"""初始化描述汽车的属性。"""self.make = makeself.model = modelself.year = yearself.odometer_reading = 0def get_descriptive_name(self):print()def read_odometer(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 = mileageelse:print("You can't roll back an odometer!")def increment_odometer(self, miles):"""将里程表读数增加指定的量。"""self.odometer_reading += milesmy_used_car = Car('subaru', 'outback', 2015)
print(my_used_car.get_descriptive_name())
my_used_car.update_odometer(23_500)
my_used_car.read_odometer()
my_used_car.increment_odometer(100)
my_used_car.read_odometer()## 继承
## 子类的方法__init__()
# 在既有类的基础上编写新类时,通常要调用父类的方法__init__()
# 这将初始化在父类__init__()方法中定义的所有属性,从而让子类包含这些属性。
class Car:"""一次模拟汽车的简单尝试。"""def __init__(self, make, model, year):self.make = makeself.model = modelself.year = yearself.odometer_reading = 0def get_descriptive_name(self):long_name = f"{self.year} {self.make} {self.model}"return long_name.title()def read_odometer(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 = mileageelse:print("You can't roll back an odometer!")def increment_odometer(self, miles):self.odometer_reading += milesclass ElectricCar(Car):"""电动汽车的独特之处。"""def __init__(self, make, model, year):"""初始化父类的属性。"""super().__init__(make, model, year)my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())## 给子类定义属性和方法
# 让一个类继承另一个类后,就可以添加区分子类和父类所需的新属性和新方法了。
class ElectricCar(Car):"""电动汽车的独特之处。"""def __init__(self, make, model, year):""" 初始化父类的属性。再初始化电动汽车特有的属性。"""super().__init__(make, model, year)self.battery_size = 75def describe_battery(self):"""打印一条描述电瓶容量的消息。"""print(f"This car has a {self.battery_size}-kWh battery.")my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()## 重写父类的方法
class ElectricCar(Car):"""电动汽车的独特之处。"""def __init__(self, make, model, year):""" 初始化父类的属性。再初始化电动汽车特有的属性。"""super().__init__(make, model, year)self.battery_size = 75def describe_battery(self):"""打印一条描述电瓶容量的消息。"""print(f"This car has a {self.battery_size}-kWh battery.")def fill_gas_tank(self):"""电动汽车没有油箱。"""print("This car doesn't need a gas tank!")## 将实例用作属性
class Battery:"""一次模拟电动汽车电瓶的简单尝试。"""def __init__(self, battery_size=75):"""初始化电瓶的属性。"""self.battery_size = battery_sizedef describe_battery(self):"""打印一条描述电瓶容量的消息。"""print(f"This car has a {self.battery_size}-kWh battery.")class ElectricCar(Car):"""电动汽车的独特之处。"""def __init__(self, make, model, year):""" 初始化父类的属性。  再初始化电动汽车特有的属性。"""super().__init__(make, model, year)self.battery = Battery()my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()class Battery:"""一次模拟电动汽车电瓶的简单尝试。"""def __init__(self, battery_size=75):"""初始化电瓶的属性。"""self.battery_size = battery_sizedef describe_battery(self):"""打印一条描述电瓶容量的消息。"""print(f"This car has a {self.battery_size}-kWh battery.")def get_range(self):"""打印一条消息,指出电瓶的续航里程。"""if self.battery_size == 75:range = 260elif self.battery_size == 100:range = 315print(f"This car can go about {range} miles on a full charge.")my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()## 导入类
## 在一个模块中存储多个类
## 导入单个类
from car import Car
from car import ElectricCar## 从一个模块中导入多个类
from car import Car, ElectricCar## 导入整个模块
import car## 导入模块中的所有类
from car import *## 在一个模块中导入另一个模块
from car import Car## 使用别名
from electric_car import ElectricCar as EC
my_tesla = EC('tesla', 'roadster', 2019)## Python标准库
# 下面来看看模块random,它在你模拟很多现实情况时很有用。
# 在这个模块中,一个有趣的函数是randint() 。它将两个整数作为参数,并随机返回一个位于这两个整数之间(含)的整数。
from random import randint
print(randint(1, 6))from random import choice
players = ['charles', 'martina', 'michael', 'florence', 'eli']
first_up = choice(players)
print(first_up)

10、第10章-文件和异常

## 从文件中读取数据
## 读取整个文件
# 关键字with在不再需要访问文件后将其关闭。在这个程序中,注意到我们调用了open(),但没有调用close()。
# 也可以调用open()和close()来打开和关闭文件,但这样做时,如果程序存在bug导致方法close()未执行,文件将不会关闭。
with open('pi_digits.txt') as file_object:contents = file_object.read()
print(contents)## 删除字符串末尾的空白
print(contents.rstrip())## 文件路径
# with open('text_files/filename.txt') as file_object:# file_path = '/home/ehmatthes/other_files/text_files/_filename_.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)filename = 'pi_digits.txt'
with open(filename) as file_object:for line in file_object:print(line.rstrip())## 创建一个包含文件各行内容的列表
filename = 'pi_digits.txt'
with open(filename) as file_object:lines = file_object.readlines()
for line in lines:print(line.rstrip())## 使用文件的内容
filename = 'pi_digits.txt'
with open(filename) as file_object:lines = file_object.readlines()
pi_string = ''
for line in lines:pi_string += line.rstrip()
print(pi_string)
print(len(pi_string))pi_string = ''
for line in lines:pi_string += line.strip()
print(pi_string)
print(len(pi_string))# 注意 读取文本文件时,Python将其中的所有文本都解读为字符串。
# 如果读取的是数,并要将其作为数值使用,就必须使用函数int()将其转换为整数或使用函数float()将其转换为浮点数。## 包含一百万位的大型文件
filename = 'pi_million_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[:52]}...")
print(len(pi_string))## 圆周率值中包含你的生日吗
pi_string = ''
for line in lines:pi_string += line.strip()
birthday = input("Enter your birthday, in the form mmddyy: ")
if birthday in pi_string:print("Your birthday appears in the first million digits of pi!")
else:print("Your birthday does not appear in the first million digits of pi!")## 单词替换
message = "I really like dogs."
message.replace('dog', 'cat')## 写入文件
## 写入空文件
# 打开文件时,可指定读取模式 ('r')、写入模式 ('w' )、附加模式 ('a' )或读写模式 ('r+')。
# 如果省略了模式实参,Python将以默认的只读模式打开文件。
filename = 'programming.txt'
with open(filename, 'w') as file_object:file_object.write("I love programming.")## 写入多行
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, '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 finding meaning in large datasets.\n")file_object.write("I love creating apps that can run in a browser.\n")## 异常
# 异常是使用try-except 代码块处理的
## 处理ZeroDivisionError异常
try:print(5/0)
except ZeroDivisionError:print("You can't divide by zero!")## 使用异常避免崩溃
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:first_number = input("\nFirst number: ")if first_number == 'q':breaksecond_number = input("Second number: ")if second_number == 'q':breakanswer = int(first_number) / int(second_number)print(answer)## else代码块
while True:first_number = input("\nFirst number: ")if first_number == 'q':breaksecond_number = input("Second number: ")if second_number == 'q':breaktry:answer = int(first_number) / int(second_number)except ZeroDivisionError:print("You can't divide by 0!")else:print(answer)
# 不执行try的执行else## 处理FileNotFoundError 异常
filename = 'alice.txt'
with open(filename, encoding='utf-8') as f:contents = f.read()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.")## 分析文本
title = "Alice in Wonderland"
print(title.split())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.")
else:# 计算该文件大致包含多少个单词。words = contents.split()num_words = len(words)print(f"The file {filename} has about {num_words} words.")## 使用多个文件
def count_words(filename):"""计算一个文件大致包含多少个单词。"""try:with open(filename, encoding='utf-8') as f:contents = f.read()except FileNotFoundError:print(f"Sorry, the file {filename} does not exist.")else:words = contents.split()num_words = len(words)print(f"The file {filename} has about {num_words} words.")
filename = 'alice.txt'
count_words(filename)filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:count_words(filename)## 静默失败
# pass 语句还充当了占位符,提醒你在程序的某个地方什么都没有做,并且以后也许要在这里做些什么。
def count_words(filename):"""计算一个文件大致包含多少个单词。"""try:with open(filename, encoding='utf-8') as f:contents = f.read()except FileNotFoundError:passelse:words = contents.split()num_words = len(words)print(f"The file {filename} has about {num_words} words.")## 决定报告哪些错误
line = "Row, row, row your boat"
print(line.count('row'))
print(line.lower().count('row'))## 存储数据
## 使用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)## 保存和读取用户生成的数据
import json
username = input("What is your name? ")
filename = 'username.json'
with open(filename, 'w') as f:json.dump(username, f)
print(f"We'll remember you when you come back, {username}!")import json
filename = 'username.json'
with open(filename) as f:username = json.load(f)print(f"Welcome back, {username}!")import json
# 如果以前存储了用户名,就加载它。
# 否则,提示用户输入用户名并存储它。
filename = 'username.json'
try:with open(filename) as f:username = json.load(f)
except FileNotFoundError:username = input("What is your name? ")with open(filename, 'w') as f:json.dump(username, f)print(f"We'll remember you when you come back, {username}!")
else:print(f"Welcome back, {username}!")## 重构
import json
def greet_user():"""问候用户,并指出其名字。"""filename = 'username.json'try:with open(filename) as f:username = json.load(f)except FileNotFoundError:username = input("What is your name? ")with open(filename, 'w') 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()import json
def get_stored_username():"""如果存储了用户名,就获取它。"""filename = 'username.json'try:with open(filename) as f:username = json.load(f)except FileNotFoundError:return Noneelse:return username
def greet_user():"""问候用户,并指出其名字。"""username = get_stored_username()if username:print(f"Welcome back, {username}!")else:username = input("What is your name? ")filename = 'username.json'with open(filename, 'w') as f:json.dump(username, f)print(f"We'll remember you when you come back, {username}!")
greet_user()import json
def get_stored_username():"""如果存储了用户名,就获取它。"""filename = 'username.json'try:with open(filename) as f:username = json.load(f)except FileNotFoundError:return Noneelse:return usernamedef get_new_username():"""提示用户输入用户名。"""username = input("What is your name? ")filename = 'username.json'with open(filename, 'w') as f:json.dump(username, f)return usernamedef greet_user():"""问候用户,并指出其名字。"""username = get_stored_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()

11、第11章-测试代码

## 将学习如何使用Python模块unittest中的工具来测试代码
def get_formatted_name(first, last):"""生成整洁的姓名。"""full_name = f"{first} {last}"return full_name.title()## 测试函数
print("Enter 'q' at any time to quit.")
while True:first = input("\nPlease give me a first name: ")if first == 'q':breaklast = input("Please give me a last name: ")if last == 'q':breakformatted_name = get_formatted_name(first, last)print(f"\tNeatly formatted name: {formatted_name}.")## 单元测试和测试用例
## Python标准库中的模块unittest 提供了代码测试工具## 可通过的测试
import unittest
class NamesTestCase(unittest.TestCase):"""测试name_function.py"""def test_first_last_name(self):"""能够正确地处理像Janis Joplin这样的姓名吗?"""formatted_name = get_formatted_name('janis', 'joplin')self.assertEqual(formatted_name, 'Janis Joplin')if __name__ == '__main__':unittest.main()# 这个类可以随意命名,但最好让它看起来与要测试的函数相关并包含Test字样。这个类必须继承unittest.TestCase类
# 所有以test_打头的方法都将自动运行## 未通过的测试
def get_formatted_name(first, middle, last):"""生成整洁的姓名。"""full_name = f"{first} {middle} {last}"return full_name.title()import unittest
class NamesTestCase(unittest.TestCase):"""测试name_function.py"""def test_first_last_name(self):"""能够正确地处理像Janis Joplin这样的姓名吗?"""formatted_name = get_formatted_name('janis', 'joplin')self.assertEqual(formatted_name, 'Janis Joplin')if __name__ == '__main__':unittest.main()## 测试未通过时怎么办
def get_formatted_name(first, last, middle=''):"""生成整洁的姓名。"""if middle:full_name = f"{first} {middle} {last}"else:full_name = f"{first} {last}"return full_name.title()## 添加新测试
class NamesTestCase(unittest.TestCase):"""测试name_function.py。"""def test_first_last_name(self):passdef test_first_last_middle_name(self):"""能够正确地处理像Wolfgang Amadeus Mozart这样的姓名吗?"""formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus')self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')if __name__ == '__main__':unittest.main()## 测试类
## 各种断言方法
# unittest模块中的断言方法
# assertEqual(a, b): 核实a == b
# assertNotEqual(a, b): 核实a != b
# assertTrue(x): 核实x为True
# assertFalse(x): 核实x为False
# assertIn(item , list): 核实item在list中
# assertNotIn(item , list):核实item不在list中## 一个要测试的类
class AnonymousSurvey:"""收集匿名调查问卷的答案。"""def __init__(self, question):"""存储一个问题,并为存储答案做准备。"""self.question = questionself.responses = []def show_question(self):"""显示调查问卷。"""print(self.question)def store_response(self, new_response):"""存储单份调查答卷。"""self.responses.append(new_response)def show_results(self):"""显示收集到的所有答卷。"""print("Survey results:")for response in self.responses:print(f"- {response}")# 定义一个问题,并创建一个调查。
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
# 显示问题并存储答案。
my_survey.show_question()
print("Enter 'q' at any time to quit.\n")
while True:response = input("Language: ")if response == 'q':breakmy_survey.store_response(response)
# 显示调查结果。
print("\nThank you to everyone who participated in the survey!")
my_survey.show_results()## 测试AnonymousSurvey 类
import unittest
class TestAnonymousSurvey(unittest.TestCase):"""针对AnonymousSurvey类的测试。"""def test_store_single_response(self):"""测试单个答案会被妥善地存储。"""question = "What language did you first learn to speak?"my_survey = AnonymousSurvey(question)my_survey.store_response('English')self.assertIn('English', my_survey.responses)
if __name__ == '__main__':unittest.main()# 在TestAnonymousSurvey中再添加一个方法
import unittest
class TestAnonymousSurvey(unittest.TestCase):"""针对AnonymousSurvey类的测试。"""def test_store_single_response(self):"""测试单个答案会被妥善地存储。"""question = "What language did you first learn to speak?"my_survey = AnonymousSurvey(question)my_survey.store_response('English')self.assertIn('English', my_survey.responses)def test_store_three_responses(self):"""测试三个答案会被妥善地存储。"""question = "What language did you first learn to speak?"my_survey = AnonymousSurvey(question)responses = ['English', 'Spanish', 'Mandarin']for response in responses:my_survey.store_response(response)for response in responses:self.assertIn(response, my_survey.responses)if __name__ == '__main__':unittest.main()## 方法setUp()
# 如果在TestCase类中包含了方法setUp(),Python将先运行它,再运行各个以test_打头的方法。
import unittest
class TestAnonymousSurvey(unittest.TestCase):"""针对AnonymousSurvey类的测试。"""def setUp(self):""" 创建一个调查对象和一组答案,供使用的测试方法使用。"""question = "What language did you first learn to speak?"self.my_survey = AnonymousSurvey(question)self.responses = ['English', 'Spanish', 'Mandarin']def test_store_single_response(self):"""测试单个答案会被妥善地存储。"""self.my_survey.store_response(self.responses[0])self.assertIn(self.responses[0], self.my_survey.responses)def test_store_three_responses(self):"""测试三个答案会被妥善地存储。"""for response in self.responses:self.my_survey.store_response(response)for response in self.responses:self.assertIn(response, self.my_survey.responses)
if __name__ == '__main__':unittest.main()

12、第12章-CSV操作

## 下面是一行CSV格式的天气数据
# "USW00025333","SITKA AIRPORT, AK US","2018-01-01","0.45",,"48","38"
import csv
filename = 'sitka_weather_07-2018_simple.csv'
with open(filename) as f:reader = csv.reader(f)header_row = next(reader)print(header_row)# 打印文件头及其位置
with open(filename) as f:reader = csv.reader(f)header_row = next(reader)
for index, column_header in enumerate(header_row):print(index, column_header)## 提取并读取数据
with open(filename) as f:reader = csv.reader(f)header_row = next(reader)# 从文件中获取最高温度。highs = []for row in reader:high = int(row[5])highs.append(high)print(highs)## 模块datetime
from datetime import datetime
first_date = datetime.strptime('2018-07-01', '%Y-%m-%d')
# 2018-07-01 00:00:00
print(first_date)# 模块datetime中设置日期和时间格式的实参
# %A 星期几,如Monday
# %B 月份名,如January
# %m 用数表示的月份(01~12)
# %d 用数表示的月份中的一天(01~31)
# %Y 四位的年份,如2019
# %y 两位的年份,如19
# %H 24小时制的小时数(00~23)
# %I 12小时制的小时数(01~12)
# %p am或pm
# %M 分钟数(00~59)
# %S 秒数(00~61)

13、第13章-使用API

# api路径
# https://api.github.com/search/repositories?q=language:python&sort=stars## 安装Requests
# python -m pip install --user requests## 处理API响应
import requests
# 执行API调用并存储响应。
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
headers = {'Accept': 'application/vnd.github.v3+json'}
r = requests.get(url, headers=headers)
print(f"Status code: {r.status_code}")
# 将API响应赋给一个变量。
response_dict = r.json()
# 处理结果。
# dict_keys(['total_count', 'incomplete_results', 'items'])
print(response_dict.keys())## 处理响应字典
import requests
# 执行API调用并存储响应。
# 将API响应赋给一个变量。
response_dict = r.json()
print(f"Total repositories: {response_dict['total_count']}")
# 探索有关仓库的信息。
repo_dicts = response_dict['items']
print(f"Repositories returned: {len(repo_dicts)}")
# 研究第一个仓库。
repo_dict = repo_dicts[0]
print(f"\nKeys: {len(repo_dict)}")
for key in sorted(repo_dict.keys()):print(key)# 研究有关仓库的信息。
repo_dicts = response_dict['items']
print(f"Repositories returned: {len(repo_dicts)}")
# 研究第一个仓库。
repo_dict = repo_dicts[0]
print("\nSelected information about first repository:")
print(f"Name: {repo_dict['name']}")
print(f"Owner: {repo_dict['owner']['login']}")
print(f"Stars: {repo_dict['stargazers_count']}")
print(f"Repository: {repo_dict['html_url']}")
print(f"Created: {repo_dict['created_at']}")
print(f"Updated: {repo_dict['updated_at']}")
print(f"Description: {repo_dict['description']}")## 概述最受欢迎的仓库
# 研究有关仓库的信息。
repo_dicts = response_dict['items']
print(f"Repositories returned: {len(repo_dicts)}")
print("\nSelected information about each repository:")
for repo_dict in repo_dicts:print(f"\nName: {repo_dict['name']}")print(f"Owner: {repo_dict['owner']['login']}")print(f"Stars: {repo_dict['stargazers_count']}")print(f"Repository: {repo_dict['html_url']}")print(f"Description: {repo_dict['description']}")## 监视API的速率限制
## api路径
# https://api.github.com/rate_limit
import requests
# 执行API调用并存储响应。
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
headers = {'Accept': 'application/vnd.github.v3+json'}
r = requests.get(url, headers=headers)
print(f"Status code: {r.status_code}")
# 处理结果。
response_dict = r.json()
repo_dicts = response_dict['items']
repo_names, stars = [], []
for repo_dict in repo_dicts:repo_names.append(repo_dict['name'])stars.append(repo_dict['stargazers_count'])
print(repo_names)
print(stars)# 处理结果。
response_dict = r.json()
repo_dicts = response_dict['items']
repo_names, stars, labels = [], [], []
for repo_dict in repo_dicts:repo_names.append(repo_dict['name'])stars.append(repo_dict['stargazers_count'])owner = repo_dict['owner']['login']description = repo_dict['description']label = f"{owner}<br />{description}"labels.append(label)
print(repo_names)
print(stars)
print(labels)# 处理结果。
response_dict = r.json()
repo_dicts = response_dict['items']
repo_links, stars, labels = [], [], []
for repo_dict in repo_dicts:repo_name = repo_dict['name']repo_url = repo_dict['html_url']repo_link = f"<a href='{repo_url}'>{repo_name}</a>"repo_links.append(repo_link)stars.append(repo_dict['stargazers_count'])
print(stars)
print(repo_links)# Hacker News API
## api路径
# https://hacker-news.firebaseio.com/v0/item/19155826.json
import requests
import json
# 执行API调用并存储响应。
url = 'https://hacker-news.firebaseio.com/v0/item/19155826.json'
r = requests.get(url)
print(f"Status code: {r.status_code}")
# 探索数据的结构。
response_dict = r.json()
readable_file = 'readable_hn_data.json'
with open(readable_file, 'w') as f:json.dump(response_dict, f, indent=4)# api路径
# https://hacker-news.firebaseio.com/v0/topstories.json
from operator import itemgetter
import requests
# 执行API调用并存储响应。
url = 'https://hacker-news.firebaseio.com/v0/topstories.json'
r = requests.get(url)
print(f"Status code: {r.status_code}")
# 处理有关每篇文章的信息。
submission_ids = r.json()
submission_dicts = []
for submission_id in submission_ids[:30]:# 对于每篇文章,都执行一个API调用。url = f"https://hacker-news.firebaseio.com/v0/item/{submission_id}.json"r = requests.get(url)   print(f"id: {submission_id}\tstatus: {r.status_code}")response_dict = r.json()# 对于每篇文章,都创建一个字典。submission_dict = {'title': response_dict['title'],'hn_link': f"http://news.ycombinator.com/item?id={submission_id}",'comments': response_dict['descendants'],}submission_dicts.append(submission_dict)
submission_dicts = sorted(submission_dicts, key=itemgetter('comments'),reverse=True)
for submission_dict in submission_dicts:print(f"\nTitle: {submission_dict['title']}")print(f"Discussion link: {submission_dict['hn_link']}")print(f"Comments: {submission_dict['comments']}")

14、第14章-从Django入手

## 安装
# python -m pip install --user django## 执行如下命令新建一个项目
# django-admin startproject learning_log .## 创建数据库
# python manage.py migrate## 查看项目
# python manage.py runserver
# python manage.py runserver 8001## 访问
# http://127.0.0.1:8000/## 创建应用程序
# Django项目 由一系列应用程序组成,它们协同工作让项目成为一个整体。本章只创建一个应用程序,它将完成项目的大部分工作。
# python manage.py startapp learning_logs# 其它使用请参考管方文档

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_1028250.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

知行之桥EDI系统功能介绍——系统安全性

在知行之桥EDI系统中&#xff0c;系统安全性问题主要分为两大类&#xff1a; 保证知行之桥EDI系统运行的基础通过知行之桥EDI系统保护数据 保证知行之桥EDI系统运行的基础 许多安全设置由服务器配置文件管理。使用知行之桥中包含的嵌入式 Web 服务器时&#xff0c;可以在以下…

vue3+ts+elementplus写一个登录页面教程

文章目录 前言1. 安装 Vue CLI 和 TypeScript 支持2. 创建登录组件 文章重点内容 前言 前期准备步骤&#xff1a; 创建一个使用 Vue 3 和 TypeScript 的登录页面涉及到多个步骤。以下是一个基本的教程&#xff0c;帮助你从头开始构建这样一个页面&#xff1a; 1. 安装 Vue CL…

Spring Boot | SpringBoo“开发入门“

目录 : 1.SpringBoot的“介绍”SpringBoot”概述” &#xff1a;SpringBoot”简介“SpringBoot的“优点” 2. SpringBoot入门程序环境准备使用 “Maven”方式构建SpringBoot 项目使用“Spring Initializr”方式构建Spring Boot 项目 3. “单元测试” 和“热部署”单元测试热部署…

SUSE 15 SP5 一键安装 Oracle 19C(19.22)单机版

前言 Oracle 一键安装脚本&#xff0c;演示 SUSE 15 SP5 一键安装 Oracle 19C&#xff08;19.22&#xff09;单机版过程&#xff08;全程无需人工干预&#xff09;&#xff1a;&#xff08;脚本包括 ORALCE PSU/OJVM 等补丁自动安装&#xff09; ⭐️ 脚本下载地址&#xff1…

54、Qt/对话框、事件机制相关学习20240325

一、完善对话框&#xff0c;点击登录按钮&#xff0c;如果账号和密码匹配&#xff0c;则弹出信息对话框&#xff0c;给出提示”登录成功“&#xff0c;提供一个Ok按钮&#xff0c;用户点击Ok后&#xff0c;关闭登录界面&#xff0c;跳转到其他界面 如果账号和密码不匹配&#…

【计算机网络篇】数据链路层(4.2)可靠传输的实现机制

文章目录 &#x1f354;可靠传输的实现机制⭐停止 - 等待协议&#x1f5d2;️注意 &#x1f50e;停止 - 等待协议的信道利用率&#x1f5c3;️练习题 ⭐回退N帧协议&#x1f388;回退N帧协议的基本工作流程&#x1f50e;无传输差错的情况&#x1f50e;超时重传的情况&#x1f5…

Linux vim用法

在命令模式下&#xff0c;点i 进入输入模式 输入模式下&#xff1a;通过箭头可以实现左右上下移动 o是从新起下一行开始写 O是新起上一行开始写 $是到此行的末尾 0是到此行的开头 gg是到第一行 yy是复制此行&#xff0c;p是粘贴 dd是删除此行 u是撤销 Ctrl r是反向撤…

边缘计算网关在机械制造企业的应用效果和价值-天拓四方

随着智能制造行业的飞速发展&#xff0c;数据量的激增和实时性要求的提高&#xff0c;传统的数据处理方式已经难以满足生产需求。而边缘计算网关的出现&#xff0c;为智能制造行业带来了革命性的变化。下面&#xff0c;我们将通过一个具体案例展示边缘计算网关在智能制造行业的…

pycharm使用远程服务器的jupyter环境

1、确保服务器上安装了jupyter,如果没有&#xff0c;执行下面命令安装 pip install jupyter2、启动jupyter notebook服务 jupyter notebook --no-browser --port8888 --ip0.0.0.0 --allow-root表明在服务器的8888 端口上启动 Jupyter Notebook&#xff0c;并允许从任何 IP 地…

手动实现一个扩散模型DDPM

扩散模型是目前大部分AIGC生图模型的基座&#xff0c;其本质是用神经网络学习从高斯噪声逐步恢复图像的过程&#xff0c;本文用python代码从零开始构建了一个简单的扩散模型。 理论部分 DDPM(Denoising Diffusion Probabilistic Models) 是一种在生成对抗网络等技术的基础上发展…

阿里云OSS存储的视频如何加水印

OSS是不能进行视频添加水印的&#xff0c;可以图片添加水印。 您可以在视频点播中进行配置&#xff1a; https://help.aliyun.com/zh/vod/user-guide/video-watermarks?spma2c4g.11186623.0.i2 原来的业务代码都是使用python 对oss的 视频进行上传 的,上传的视频路径已经保存到…

小米汽车正式发布:开启智能电动新篇章

随着科技的不断进步&#xff0c;汽车产业正经历着前所未有的变革。智能电动汽车作为这一变革的重要方向&#xff0c;正吸引着越来越多的目光。在这个充满机遇和挑战的时代&#xff0c;小米汽车凭借其卓越的技术实力和深厚的市场底蕴&#xff0c;终于迈出了坚实的一步。今天&…

计算机网络:传输控制协议(Transmission Control Protocol-TCP协议

计算机网络&#xff1a;传输控制协议&#xff08;Transmission Control Protocol-TCP协议&#xff09; 本文目的前置知识点TCP协议简介主要特性通信流程1. 建立连接的过程(三次握手&#xff0c;243)1.1 为什么要三次握手&#xff0c;两次不行吗&#xff1f; 2. 释放连接的过程(…

Java基础语法(二)

前言 Hello&#xff0c;大家好&#xff01;很开心与你们在这里相遇&#xff0c;我是一个喜欢文字、喜欢有趣的灵魂、喜欢探索一切有趣事物的女孩&#xff0c;想与你们共同学习、探索关于IT的相关知识&#xff0c;希望我们可以一路陪伴~ 1. 类型转换 1.1 自动类型转换 什么是自…

RabbitMQ3.x之三_RabbitMQ新建用户及开启远程访问

RabbitMQ3.x之三_RabbitMQ新建用户及开启远程访问 文章目录 RabbitMQ3.x之三_RabbitMQ新建用户及开启远程访问1. guest不能远程访问2. 创建专有用户远程访问RabbitMQ1. 创建用户2. 给用户分配tag(角色)3. 开启远程访问 3. 新用户远程登录 1. guest不能远程访问 在 RabbitMQ 中&…

网络爬虫框架Scrapy的入门使用

Scrapy的入门使用 Scrapy概述引擎&#xff08;Engine&#xff09;调度器&#xff08;Scheduler&#xff09;下载器&#xff08;Downloader&#xff09;SpiderItem Pipeline 基本使用安装scrapy创建项目定义Item数据模型对象创建爬虫(Spider)管道pipeline来保存数据启动爬虫 其他…

利用lidar生成深度图

前言 目前&#xff0c;深度图像的获取方法有&#xff1a;激光雷达深度成像法、计算机立体视觉成像、坐标测量机法、莫尔条纹法、结构光法等。针对深度图像的研究重点主要集中在以下几个方面&#xff1a;深度图像的分割技术&#xff0c;深度图像的边缘检测技术&#xff0c;基于…

python的神奇bug2

今天测试出一个很诡异的bug&#xff0c; 这个错误还真的很难发现 测试1 a [1,10,100] for i in a:print(i)if(i10):a[20,30,-1]一般来说我们在进行迭代时&#xff0c;a这个值时不能改动的&#xff0c;但是现在的问题时如果我不小心给改动了呢&#xff0c;结果如下 也就是说…

文本文件操作

大家好&#xff1a; 衷心希望各位点赞。 您的问题请留在评论区&#xff0c;我会及时回答。 文件操作 程序运行时&#xff0c;产生的数据都是临时数据&#xff0c;程序一旦运行结束都会被释放。通过文件可以将数据持久化。 C中对文件进行操作需要包含头文件<fstream> 文件…

关于深度学习的 PyTorch 项目如何上手分析?从什么地方切入?

文章目录 PyTorch 项目分析1.背景2.分析流程 PyTorch 项目分析 1.背景 当我们拿到一个 PyTorch 的深度学习项目时&#xff0c;应该怎么入手&#xff1f;怎么去查看代码&#xff1f; 2.分析流程 首先阅读对应项目的 README.md 文件。通过阅读 README.md &#xff0c;一般可以…