字符串(string)

大小写修改

upper():将字符串全部改为大写
lower():将字符串全部改为小写
title():每个单词的首字母大写

f-字符串

f是format的简写
我们可以在 f-字符串中,使用花括号来引用代码中定义的变量

1
2
3
4
5
first_name = "ada" 
last_name = "lovelace"
full_name = f"{first_name} {last_name}" print(full_name)
message = f"Hello, {full_name.title()}!"
print(message)

添加空白

\t:在字符串中表示制表符
\n:在字符串中表示换行符

删除空白

可以使用以下方法来删除空白:
lstrip():移除左端的空白
rstrip():移除右端的空白
strip() :移除两端的空白

1
2
3
' iTruing'.lstrip() 
'iTruing '.rstrip()
' iTruing '.strip()

删除前缀

removeprefix():移除字符串中指定的前缀

1
2
3
url = 'https://www.ituring.com.cn' 
url = url.removeprefix('https://')
print(url)

列表(list)

1
2
bikes = ['trek', 'redline', 'giant'] 
print(bikes)

索引(index)

索引(index)——即元素的位置:可用于访问列表中的元素
负数索引:与列表末尾有相应距离的位置

1
2
3
bikes = ['trek', 'redline', 'giant'] 
print(bikes[0])
print(bikes[2], bikes[-1])

使用列表中的各个元素

1
2
3
bicycles = ['trek', 'cannondale', 'redline', 'specialized'] 
message = f"My first bicycle was a {bicycles[0]}."
print(message)

操作列表

lst.append(val) :在列表的末尾添加新元素
lst.insert(idx, val):在列表的指定位置上添加新元素
del lst[idx] :删除列表中指定索引的元素
lst.pop([idx]) -> val:删除并返回列表中指定索引(默认为末尾) 的元素,弹出(pop)的值能被接着使用
lst.remove(val):删除列表中匹配到的第一个指定元素
lst.sort() :永久修改原列表,对其中的元素进行排序
sorted(lst) -> lst':返回排序后的列表的副本
lst.reverse():永久修改原列表,对其中的元素进行翻转
len(lst) -> num:获取列表的元素个数

遍历整个列表

for 循环:对列表中的每个元素都执行相同的操作

1
2
3
magicians = ['alice', 'david', 'carolina'] 
for magician in magicians:
print(magician)

for后面的magician是一个临时变量,可以更改命名

字符串的循环

1
2
3
4
time = "14:10:15" 
for char in time:
if(char!=":"):
print(char)

运行结果:
1
4
1
0
1
5

for循环操作

1
2
3
4
5
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 more, {magician.title()}.\n")
print("Thank you, everyone. That was a great magic show!")

创建数值列表

range([start,] end [,step]):生成可迭代的数值列表的表示

1
2
for value in range(1, 5):
print(value)

运行结果:1
2
3
4
这是编程语言中常见的差一行为,输出在指定的第二个值处停止了。要打印数 1 ~ 5,需要使用 range(1, 6)
第一个参数 start 是可选的:
例如 range(6) 将会打印数 0 ~ 5 运行结果:1 2 3

1
2
3
squares = [] 
for value in range(1, 11): squares.append(value ** 2)
print(squares)

用列表推导式写:

1
2
squares = [value**2 for value in range(1, 11)]
print(squares)

数值列表的简单统计运算

max(lst):取数值列表中的最大值。
min(lst):取数值列表中的最小值。
sum(lst):对数值列表执行求和计算

列表的切片

可以通过在索引中添加冒号(:)来获取部分列表:

1
2
players = ['charles', 'martina', 'michael', 'florence'] 
print(players[0:3])

运行结果:[‘charles’, ‘martina’, ‘michael’]
获取第二和第三个元素:

1
2
players = ['charles', 'martina', 'michael', 'florence'] 
print(players[1:3])

运行结果:[‘martina’, ‘michael’]
如果没有指定索引,将自动从列表开头开始:

1
2
players = ['charles', 'martina', 'michael', 'florence'] 
print(players[:3])

运行结果:[‘charles’, ‘martina’, ‘michael’]
类似的,我们也可以省略终止索引:

1
2
players = ['charles', 'martina', 'michael', 'florence'] 
print(players[2:])

运行结果: [‘michael’, ‘florence’]
也可以用负数索引来进行切片操作:

1
2
players = ['charles', 'martina', 'michael', 'florence']
print(players[-2:])

运行结果: [‘michael’, ‘florence’]

遍历切片

for循环遍历切片

1
2
3
4
players = ['charles', 'martina', 'michael', 'florence']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player)

列表的拷贝

1
2
3
4
5
6
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)

元组

元组是一些元素的不可变有序序列

1
2
3
dimensions = (200, 50) 
print(dimensions[0])
print(dimensions[1])

也可以通过使用 for 循环来遍历元组中的元素
无法通过 dimensions[0] = 250 修改元组中的元素, 试图这样做的话,你将会得到类型错误(TypeError)

列表与字符串相互转换

s t r i n g 类型的字符可以通过 l i s t ( s ) 转换成列表类型 ;
s.split(d) 使用 d 为分隔符拆分字符串 s ;
‘ ’.join(L) 将包含字母的列表合成字符串 ;

1
2
s = "I< 3 cs"
print(s.split('<'))

运行结果:[‘I’, ‘3 cs’]

1
2
L = ['a', 'b', 'c']
print('_'.join(L))

运行结果:“a_b_c”


if语句

比较

1
2
3
4
5
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else: print(car.title())

运行结果:Audi
BMW
Subaru
Toyota

1
2
3
car = 'Audi' 
print(car != 'audi')
print(car.lower() != 'audi')

运行结果:Ture
False

布尔运算

andor 关键字:用于布尔运算,分别表示和/或

1
2
3
4
>>> age_0 = 22 
>>> age_1 = 18
>>> age_0 >= 21 and age_1 >= 21
>>> age_0 >= 21 or age_1 >= 21

运算结果:False
Ture
not 关键字:用于布尔运算,表示非
in 关键字:用于检查特定值是否在集合中

1
2
3
4
5
requested_toppings = ['mushrooms', 'onions'] 
print('mushrooms' in requested_toppings)
print('pepperoni' in requested_toppings)
print('mushrooms' not in requested_toppings)
print('pepperoni' not in requested_toppings)

运行结果:Ture
False
False
Ture
布尔表达式:不过是条件测试的别名
布尔值:存储布尔表达式结果的变量

1
2
game_active = True 
can_edit = False

测试多个条件

1
2
3
4
5
6
7
age = 25
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."

确定列表非空

我们可以将列表名用作条件表达式
这个表达式只有当列表至少包含一个元素时才为 True

1
2
3
4
5
6
7
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?")

运行结果:Are you sure you want a plain pizza?


字典

一个字典

下面是一个存储了有关特定外星人信息的简单字典,最后两行代码访问并显示信息:

1
2
3
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])

运行结果:green
5

添加键值对

1
2
3
alien_0 = {'color': 'green'} 
alien_0['points'] = 5
print(alien_0)

运行结果:{‘color’: ‘green’, ‘points’: 5}

修改字典中的值

1
2
3
alien_0 = {'color': 'green'} 
alien_0['color'] = 'yellow'
print(alien_0['color'])

运行结果:yellow

删除键值对

使用del语句

1
2
3
4
alien_0 = {'color': 'green','points': 5} 
print(alien_0)
del alien_0['points']
print(alien_0)

运行结果:{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’}

使用get()来访问值

d.get(key, [default]):根据键获取值,方括号中的默认值(default)实参是可选的

1
2
3
alien_0 = {'color': 'green', 'speed': 'slow'} 
point_value = alien_0.get('color')
print(point_value)

运行结果:green

1
2
3
alien_0 = {'color': 'green', 'speed': 'slow'} 
point_value = alien_0.get('points', 'Empty')
print(point_value)

运行结果:Empty
提供default值时,方法将返回它,否则将返回特殊值 None

遍历所有的键值对

d.items() :返回所有键值对的元组视图

1
2
3
favorites = {'jen': 'python', 'edward': 'rust'} 
for name, language in favorites.items():
print(f"{name} loves {language}.")

运行结果:jen loves python.
edward loves rust.
d.keys() :返回所有键的列表视图

1
2
3
4
favorites = {'jen': 'python', 'edward': 'rust'}  
for name in favorites.keys():
language = favorites[name].title()
print(f"{name} loves {language}.")

运行结果:jen loves Python.
edward loves Rust
d.values():返回所有值的列表视图

1
2
3
favorites = {'jen': 'python', 'edward': 'rust'} 
for language in favorites.values():
print(language.title())

运行结果:Python
Rust

嵌套:在字典中存储列表

1
2
3
4
5
6
7
pizza = { 
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese']
}
print(f"{pizza['crust']}-crust pizza " "toppings:")
for topping in pizza['toppings']:
print(f"\t{topping}")

运行结果:thick-crust pizza toppings:
mushrooms
extra cheese

嵌套:在字典中存储字典

1
2
3
4
5
6
7
8
9
10
11
12
users = { 
'aeinstein':{
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}

用户输入

input()函数

input() 函数:让程序等待用户输入函数的接受一个参数:向用户显示的提示(prompt)

1
2
name = input("Please enter your name: ") 
print(f"\nHello, {name}!"

获取数值输入

把文本当作数值直接使用,会导致类型错误(TypeError)
我们可以在执行数值相关操作前,把用户的输入转换为数值类型:

1
2
3
age = input("How old are you? ") 
age = int(age)
print(age >= 18)

运行结果:How old are you? 21
True

求模运算符

求模运算符(%):将两个数相除并返回余数
取模运算有很多妙用,比如可以用它来判断一个数是否是偶数


while循环简介

while循环简介

for 循环用于针对集合中的每个元素执行一个代码块, 而 while 循环则不断地运行,直到指定的条件不再满足为止

1
2
3
4
current_number = 1 
while current_number < 3:
print(current_number)
current_number += 1

运行结果:1
2

退出循环

1
2
3
4
5
6
prompt = "\nTell me something, and I will repeat it back:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
print(message)

程序会不断询问用户的输入,直到用户输入 ‘quit’ 才退出

使用标志

我们可以使用标志(flag)变量来控制程序的循环逻辑, 这样做能使程序更易于处理多种不同事件导致的停止:

1
2
3
4
5
6
7
8
9
prompt = "\nTell me something, and I will repeat it back:" 
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)

使用break退出循环

break 关键字:立即退出循环

1
2
3
4
5
6
current_number = 0 
while True:
if current_number > 5:
break
current_number += 1
print(current_number)

使用continue跳过循环

continue 关键字:跳过当前的循环,返回到循环的开头

1
2
3
4
5
6
current_number = 0 
while True:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)

穷举法

示例:用穷举法求取整数的立方根

1
2
3
4
5
6
7
cube = 8 
for guess in range(cube+1):
if guess**3 == cube:
print(str(cube)+'的整数立方根是'+str(guess))
break
if guess**3 != cube:
print(cube, '没有整数立方根')

二分查找法

二分查找法的特点:

  • 每次迭代搜索步长均减半(穷举法一般搜索步长不变)
  • 新的猜想值取搜索范围的中间值
    示例:二分查找法求取立方根近似解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
cube = 27 
epsilon = 0.01
num_guesses = 0
low = 0
high = cube
guess = (high + low)/2.0
while abs(guess**3 - cube) >= epsilon:
if guess**3 < cube :
low = guess
else:
high = guess
guess = (high + low)/2.0
num_guesses += 1
print('猜想次数为', num_guesses, '次')
print(guess, '是', cube, '立方根的近似解'

函数

函数(function):带名字的代码块,用于完成具体的工作要执行函数定义的特定任务,可调用(call)该函数

定义函数

def 关键字:告诉 Python 你要定义一个函数,后面跟随函数定义

1
2
3
4
5
def greet_user(): 
"""显示简单的问候语"""
print("Hello!")

greet_user()

实参与形参

1
2
3
4
5
def greet_user(username): 
"""显示简单的问候语"""
print(f"Hello, {username.title()}!")

greet_user('jesse')

默认值

在编写函数时,可以给每个形参指定默认值
当函数描述的动物大多是小狗时,我们将 animal_type 默认值设置为 ‘dog’:

1
2
3
4
5
6
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')

返回值

1
2
3
4
5
6
7
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)

让实参变得可选

考虑大多数同学没有中间名,我们需要为它指定默认值,让它变成可选的:

1
2
3
4
5
6
7
8
9
10
11
12
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)

传递任意数量的实参

我们有时候无法确定函数需要接受多少个实参
例如披萨店顾客点选的配料种数可能是不确定的,此时可以:

1
2
3
4
5
6
def make_pizza(*toppings): 
"""打印顾客点的所有配料"""
print(toppings)

make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

星号 * 让 Python 创建一个名为 toppings 的元组, 其中包含函数收到的所有(余下的)位置实参。


类-面向对象编程思想

对象

对象是一种数据抽象,也称:“通过类定义的数据结构实例”
对象是Python程序处理的核心元素,每个对象都有类型,定义了程序能够在这个对象上做的操作

创建类

_init_:初始化方法
self形参:它是一个指向实例本身的引用, 实例的每次调用都会自动传入自身,这样使得实例能够访问类中的属性和方法
self 形参必不可少,而且必须位于其他形参的前面
方法→定义Dog两种行为

1
2
3
4
5
6
7
8
9
10
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.")

根据类创建实例化

1
2
3
4
5
6
7
my_dog = Dog('Willie', 6)

my_dog.sit( )
my_dog.roll_over( )

print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")

给属性指定默认值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Car: 
"""一次模拟汽车的简单尝试"""
def __init__(self, make, model, year):
...
self.odometer_reading = 0

def get_descriptive_name(self):
...

def read_odometer(self):
"""打印一条指出汽车行驶里程的消息"""
print(f"This car has {self.odometer_reading} miles on it.")

my_new_car = Car('audi', 'a4', 2023)
print(my_new_car.get_descriptive_name()) my_new_car.read_odometer()

运行结果:2023 Audi A4
This car has 0 miles on it.

修改属性的值

通过实例修改属性的值

1
2
my_new_car.odometer_reading = 23 
my_new_car.read_odometer()

通过方法设置

1
2
3
4
5
class Car: 
...
def update_odometer(self, mileage):
"""将里程表读数设置为指定的值"""
self.odometer_reading = mileage

继承

继承提供了一种方便的机制,可以建立一组彼此相关的抽象。它使程序员能够建立一个类型的层次结构,其中每个类型都可以从上层的类型继承属性
在Python中,一切都是对象,因此Object类在最顶层

给子类定义属性和方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Car:
...

class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""初始化父类的属性"""
super().__init__(make, model, year)
self.battery_size = 40

def describe_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()

在子类的初始化方法中, 我们使用了 super() 函数这是一个特殊的函数,让你能够调用父类的方法。
父类也称为超类(supercalss), 函数名 super 就是由此而来的
还可以添加特有的属性和函数,如battery_size、describe_battery()

重写父类中的方法

当父类中定义的一些方法不能满足子类的要求时,可以在子类中随时重写父类的方法:定义一个同名的方法

1
2
3
4
5
6
7
8
9
10
class Car:
...
def get_descriptive_name(self):
...

class ElectricCar(Car):
...
def get_descriptive_name(self):
"""返回格式规范的描述性信息"""
return f"{super.get_descriptive_name()}{self.battery_size}".title()

将实例用作属性

在 ElectricCar 类中, 我们将之前电池容量属性, 改为了表示电池的属性 self.battery,然后将电池实例赋值给了这个属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Car: 
...

class Battery:
"""一次模拟电动汽车电池的简单尝试"""
def __init__(self, size=40):
"""初始化电池的属性"""
self.size = size
def describe_battery(self):
"""打印一条描述电池容量的消息"""
print(f"This car has a {self.size}-kWh battery."

class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""初始化父类的属性"""
super().__init__(make, model, year)
self.battery = Battery()

my_leaf = ElectricCar('nissan', 'leaf', 2024) print(my_leaf.get_descriptive_name()) my_leaf.battery.describe_battery()

运行结果:2024 Nissan Leaf
This car has a 40-kWh battery.

导入单个类

第一行语句 from car import Car 便是导入语句

1
2
3
4
5
from car import Car
my_new_car = Car('audi', 'a4', 2023)
print(my_new_car.get_descriptive_name()
my_new_car.odometer_reading = 23
my_new_car.read_odometer()

也可以直接导入整个模块

1
import car