Python基础语法

本文最后更新于 2025年10月27日 下午

打印

字符串大小写

1
2
3
4
str1="Hellow World!"
str1.upper()#全大写
str1.lower()#全小写
str1.title()#首字母大写

格式化

f字符串

1
2
3
4
5
first_name="only"
last_name="matthew"
full_name=f"{first_name} {last_name}"
print(f"Hello {full_name.title()}")

打印符

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> print("Python")
Python
>>> print("\tPython")
Python
>>> print("Languages:\nPython\nC\nJavaScript")
Languages:
C Python
JavaScript
>>> print("Languages:\n\tPython\n\tC\n\tJavaScript")
Languages:
Python
C
JavaScript

空白rstrip()、lstrip()、strip()函数

可以找出左右的空白

1
2
3
4
5
6
7
>>> favorite_language = 'python '
>>> favorite_language
'python '
>>> favorite_language.rstrip()
'python'
>>> favorite_language
'python '

移除前后缀

1
2
3
4
5
6
7
8
9
10
str2="USD10000"
print(str2.removeprefix("USD"))

str3="1000CNY"
print(str3.removesuffix("CNY"))


10000
1000

数字类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
##整数:python使用**表示乘方运算
print(2**3) # 输出8

##浮点数:带小数点的
##小数点可能会出现多余的0和小数点后面的数字
print(3*0.1)#可能会输出3.0000000000000004

##整数和浮点数的运算
##在python中,整数和浮点数相乘除都会得到浮点数,这也就意味着我们在python中不需要担心整数溢出的问题
print(2*3.0) # 输出6.0

##下划线
##在python中,数字可以使用下划线来分隔,增加可读性
##下划线不会影响数字的值
print(1_000_000) # 输出1000000

##同时赋值
a, b = 1, 2
print(a, b) # 输出1 2

##多行赋值
a = b = c = 1

##常量:在python中,常量通常使用全大写字母表示
PI = 3.14 # 圆周率常量
##这与我们在C++中学习的有所差别,在这里,常量理论上是可以更改的
##但是在实际编程中,我们应该遵循约定,不要更改常量的值

列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#列表(list):
# 1. 列表的创建
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)

# 2. 列表的访问
print(bicycles[0])
print(bicycles[1])
print(bicycles[2])
print(bicycles[3])

# 2.1 负索引访问
print(bicycles[-1]) # 最后一个元素
print(bicycles[-2]) # 倒数第二个元素
print(bicycles[-3]) # 倒数第三个元素‘

# 2.2 可以使用之前的字符串方法
print(bicycles[0].title()) # 将第一个元素的首字母大写
print(bicycles[1].upper()) # 将第二个元素转换为大写

print(f"My first bicycle is a {bicycles[0].title()}")


# 3. 列表的增加、修改、删除(列表往往是动态的)
bicycles[0] = 'giant'
print(bicycles)

# 3.1 在列表末尾添加元素
bicycles.append('bianchi')
print(bicycles)

a= []
a.append(1)
a.append(2)
print(a)
[1, 2]

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
bicycles.insert(0, 'giant') # 在索引0的位置插入元素
print(bicycles) # ['giant', 'trek', 'cannondale', 'redline', 'specialized']
#这使得每一个元素都向后移动了一个位置

# 从列表中删除元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
bicycles.remove("redline") # 删除指定元素
print(bicycles) # ['trek', 'cannondale', 'specialized']

bicycles.remove(0) # 删除指定索引的元素
print(bicycles) # ['cannondale', 'specialized']


# # 像栈一样pop()
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
# print(bicycles)# ['trek', 'cannondale', 'redline', 'specialized']
# # pop()方法默认删除列表的最后一个元素,并返回该元素
# last_bicycle = bicycles.pop()
# print(last_bicycle) # specialized
# print(bicycles) # ['trek', 'cannondale', 'redline']

# # pop()方法可以指定索引
first_bicycle = bicycles.pop(0)
print(f"The first bicycle I owned was a {first_bicycle.title()}")

# 用remove()方法删除元素时,如果列表中有多个相同的元素,只会删除第一个匹配的元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized', 'redline']
bicycles.remove('redline') # 删除第一个匹配的元素
print(bicycles) # ['trek', 'cannondale', 'specialized', 'redline']


## 遍历列表中的每个元素、删除
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
for bicycle in bicycles:
print(bicycle.title())

# 删除列表中的元素时,遍历列表的副本
for bicycle in bicycles[:]: # 使用切片创建列表的副本
if bicycle == 'redline':
bicycles.remove(bicycle)

列表的管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 列表的管理:

## 1.排序sort(永久排序):根据首字母
cars=['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)# ['audi', 'bmw', 'subaru', 'toyota']

## 2.逆序sort(reverse=True)
cars.sort(reverse=True)
print(cars) # ['toyota', 'subaru', 'bmw', 'audi']

## 3.临时排序sorted():返回一个新的列表
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(sorted(cars)) # ['audi', 'bmw', 'subaru', 'toyota']
print(cars) # ['bmw', 'audi', 'toyota', 'subaru']
##这个排序只是临时的,原列表不变

## 4.反转reverse():反转列表的顺序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.reverse()
print(cars) # ['subaru', 'toyota', 'audi', 'bmw']

## 5.获取列表长度len()
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(len(cars))#4

列表小结

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
places=["Bejing", "Shanghai", "Guangzhou", "Shenzhen", "Chengdu","New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
print(places[0])#顺序访问
#Bejing

print(places[-1])#逆序访问
#Phoenix

print(places[0].upper())#可以使用字符串方法
#BEJING

places[0]="Hnu University"#可以更改
print(places[0])
#Hnu University

places.append("Tsing Hua University")#末尾添加
print(places[-1])
#Tsing Hua University

places.insert(1,"Peking University")#插入
print(places)
#['Hnu University', 'Peking University', 'Shanghai', 'Guangzhou', 'Shenzhen', 'Chengdu', 'New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Tsing Hua University']

## 删除的方法
places.remove("Shanghai")#使用remove,只能删除最前面的那个
print(places)
#['Hnu University', 'Peking University', 'Guangzhou', 'Shenzhen', 'Chengdu', 'New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Tsing Hua University']

del places[1]#del指定元素
print(places)
#['Hnu University', 'Guangzhou', 'Shenzhen', 'Chengdu', 'New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Tsing Hua University']

del places[0:3]#del一部分,不包含index=3的元素
print(places)
#["Chengdu", "New York", "Los Angeles", "Chicago", "Houston", "Phoenix", "Tsing Hua University"]

places.pop()#使用pop函数像栈一样弹出最后一个
print(places)
#["Chengdu", "New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]

places.sort()#按首字母排序
print(places)
#['Chengdu', 'Chicago', 'Houston', 'Los Angeles', 'New York', 'Phoenix']

places.sort(reverse=True)#按首字母逆序
print(places)
#['Phoenix', 'New York', 'Los Angeles', 'Houston', 'Chicago', 'Chengdu']

places.reverse()#反向
print(places)
#['Chengdu', 'Chicago', 'Houston', 'Los Angeles', 'New York', 'Phoenix']

print(sorted(places))#临时排序
print(places)
#['Chendu', 'Chicago', 'Houston', 'Los Angeles', 'New York', 'Phoenix']

print(sorted(places,reverse=True))#临时排序+反向
#['Phoenix', 'New York', 'Los Angeles', 'Houston', 'Chicago', 'Chengdu']
print(places)
#['Chengdu', 'Chicago', 'Houston', 'Los Angeles', 'New York', 'Phoenix']

使用列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# 4.1 对于列表的遍历

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

for magician in magicians:
print(magician.title() + ", that was a great trick!")
# Alice, that was a great trick!
# David, that was a great trick!
# Carolina, that was a great trick!
print("\nThank you, everyone. That was a great magic show!")

# 4.2 数值列表
# 4.2.1 使用 range() 函数
for value in range(1, 5):
print(value)
# 1
# 2
# 3
# 4

# 4.2.2 使用 range() 函数创建数字列表

numbers = list(range(1, 6))
print(numbers)
# [1, 2, 3, 4, 5]

numbers = list(range(1, 11, 2))
print(numbers)
# [1, 3, 5, 7, 9]

squares=[]
for value in range(1,11):
square=value**2
squares.append(square)
# or: squares.append(value**2)

# 4.2.3 统计运算(min,max,sum)

digits = [1, 2, 3, 4, 5]
print(min(digits))
# 1
print(max(digits))
# 5
print(sum(digits))
# 15

# 4.2.4 列表推导式

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

# 4.4 切片

players=["a","b","c","d","e","f","g"]
print(players[0:3])
print(players[:3])
print(players[-3:])

for player in players[:3]:
print(player)

# 4.4.2 列表的复制(副本)

my_food=['pizza', 'falafel', 'carrot cake']
# 复制列表
friend_food=my_food[:]
# 修改原列表
my_food.append('cannoli')
friend_food.append('ice cream')
print("My favorite foods are:")
for food in my_food:
print(food)

print("\nMy friend's favorite foods are:")
for food in friend_food:
print(food)

#辨析:

# my_food 和 friend_food 是两个独立的列表,修改一个不会影响另一个。
# 如果使用 my_food = friend_food,则两个变量指向同一个列表对象,修改一个会影响另一个。

# 4.5 元组:不可变的列表

dimensions = (200, 50)
print(dimensions[0])
# 200
print(dimensions[1])
# 50
# 尝试修改元组中的值会报错
# dimensions[0] = 250 # TypeError: 'tuple' object does not support item assignment

# 遍历元组
for dimension in dimensions:
print(dimension)
# 200
# 50

#如果我们非要修改元组的值:
dimensions = (200, 50)
print("\nOriginal dimensions:")
for dimension in dimensions:
print(dimension)

dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)

条件语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
## Bool表达式&判断符
car='bmw'
print(car=='bmw')#True

## 忽略大小写

Name='John'
print(Name.lower()=='john')#True

## 不等于!=
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print('Hold the anchovies')

## <,<=,>,>=

number=19
if number>=10:
print("The number is bigger than ten")
if number<=20:
print('The number is smaller than twenty')
## and,or,not
age_0 = 22
age_1 = 18
if age_0 >= 21 and age_1 >= 21:#and 需要两个都满足
print("Both are above 21")
if age_0 >= 21 or age_1 >= 21:
print("At least one is above 21")#or只需要一个满足
if not age_0 >= 21:
print("Age 0 is not above 21")#not 取反

user=['marie','john','alice']
banned_user=['marie','bob']
if 'alice' not in banned_user:
print('Alice is allowed to post a response')#not in 检查元素是否不在列表中

# if
## 最简单的if:
conditon_test=True
if conditon_test:
#do something
print('Hello Wolrd!')
#如果if后的conditon_test不成立,冒号及其缩进范围内的内容不会被执行

## if_else

#模板如下

conditon_test=False#在这个例子里,conditon_test不成立,进入else所管辖的内容
if conditon_test:
#do somethin
print('Hello Wolrd')
else:
#do something
print('Hello!')

## if_elif_else
#在这个结构中,python只会执行一个代码块,其余的不会被执行
# 假设我们需要判断门票的价格
ages=[4,17,25]
for age in ages:
if age<4:
prices=10
elif age<18:#因为我们已经知道age>=4
prices=20
else:#上面的条件都不成立,则age>=18
prices=25
print(f'The prices for age at {age} is {prices}')
#为了增加程序的安全性,我们可以不要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}.")

# 列表与if
requested_toppings=[]
if requested_toppings:
for requested_topping in requested_toppings:
print(f'Adding {requested_topping}.')
else:
print('Are you sure you want a plain pizza?')

available_toppings=('mushrooms','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'{requested_topping.title()} is not available.')

#字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#字典 dictionary
alien_0={'color' : 'green' , 'points' : 5}#字典中可以包含任意数量的键值对
print(alien_0['color'])

#键值对的添加
#直接使用并赋值即可,python会为你添加
alien_0['x_position']=0
alien_0['y_position']=25
print(alien_0)

#字典的修改
#直接修改即可
print(f'The color of the alien is {alien_0["color"]}')
alien_0['color']='yellow'
print(f'The color of the alien is {alien_0["color"]}')

#综合应用
alien_0['speed']='medium'
print(f'The original position of the alien is {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'The new position is x:{alien_0["x_position"]}, y:{alien_0["y_position"]}.')

# 字典中键值对的删除
#使用del
print(alien_0)
del alien_0['speed']
print(alien_0)

# 安全地访问字典
#使用get()

del alien_0['points']
# print(alien_0['points']) 报错:(KeyError: 'points')
print(alien_0.get('points','No point value assigned'))#No point value assigned
#若字典中不存在第一个参数的键,则返回第二个参数
#如何不指定第二个参数,将返回None
print(alien_0.get('points'))#None


# 字典的遍历

# 1.遍历所有键值对
favoratie_languages={
'a':'C++',
'b':'Rust',
'c':'Python'
}
for name,language in favoratie_languages.items():#items函数会返回字典中的键值对
print(f'The favoratie language of {name.title()} is {language.title()}.')

# 2.遍历所有的键
friends=['a','b']
for name in favoratie_languages.keys():
print(f"Hi {name.title()}.")
if name in friends:
print(f"\tDear {name.title()}, I see you love {favoratie_languages[name]}.")
# key()函数实际上会返回一个列表
print(favoratie_languages.keys())

# 3.遍历所有的值
for language in favoratie_languages.values():
print(f'The favoratie language is {language.title()}.')

#嵌套
# 字典中可以嵌套字典
alien_0={
'color' : 'green' ,
'points' : 5,
'x_position' : 0,
'y_position' : 25,
'speed' : 'medium'
}
alien_1={
'color' : 'yellow' ,
'points' : 10,
'x_position' : 5,
'y_position' : 30,
'speed' : 'fast'
}
aliens=[alien_0,alien_1]#列表中嵌套字典
for alien in aliens:
print(alien)

aliens=[]#创建一个空列表
#使用range()函数创建100个外星人
for alien_number in range(100):
new_alien={'color' : 'green' , 'points' : 5, 'x_position' : 0, 'y_position' : 25, 'speed' : 'medium'}
aliens.append(new_alien)#将新外星人添加到列表中
for alien in aliens[:5]:#只打印前5个外星人
print(alien)

# 字典中嵌套列表
favorite_languages={
'a':['C++','Rust'],
'b':['Python'],
'c':['JavaScript','Go']
}
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"\t{topping.title()}")

for name,languages in favorite_languages.items():
print(f'{name.title()}\'s favorite languages are:')
for language in languages:
print(f'\t{language.title()}')

# 字典中嵌套字典
users={
'a': {
'first_name':'a',
'last_name':'aa',
'location':'aaa'
},
'b':{
'first_name':'b',
'last_name':'bb',
'location':'bbb'
},
}
for username,user_info in users.items():
print(f'Username:{username}')
full_name=f'{user_info['first_name']} {user_info['last_name']}'
location=user_info['location']
print(f'\tFull name: {full_name}')
print(f'\tThe location of {full_name} is {location}.')

while

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#计数
counting_number=1
while counting_number <=5:
print(counting_number)
counting_number+=1

#repeat 小游戏
message=''
while message != 'quit':
message=input("Tell me something then I'll repeat it to you.")
if message!='quit':
print(message)

# 小trick:标识符
active=True
message=''
while active:
message=input("Tell me something then I'll repeat it to you.")
if message!='quit':
print(message)
else:
active=False


#使用break

while True:
city=input('Please input your favorite city:\t')

if city=='quit':
break
else:
print(f"I'd love to visit {city.title()}")

#continue
#continue会直接跳过之后的语句,直接跳回while的开头判断条件是否成立
counting_number=0
while counting_number<10:
counting_number+=1
if counting_number%2==0:
continue
print(counting_number)

# 用while从list中删除东西
pets=['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
while 'cat' in pets:
pets.remove('cat')
print(pets)

函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#def:define function
def greetings(username):
print(f"Hello {username.title()}")

greetings('Matthew')

# 位置实参

def describe_pets(onwer_name,pet_name):
print(f'{onwer_name.title()} have a/an {pet_name.title()}')

describe_pets('a','b')

# 关键字实参
describe_pets(onwer_name='a',pet_name='b')

#默认值
def describe_pets(onwer_name,pet_name='dog'):
print(f'{onwer_name.title()} have a/an {pet_name.title()}')

describe_pets(onwer_name='c')

def get_formatted_name(first_name,last_name,middle_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()

print(get_formatted_name(first_name='a',last_name='b'))

def build_person(first_name,last_name,age=None):
person = {
'first_name' : first_name.title(),
'last_name' : last_name.title(),
}
if age:
person['age']=age
return person

musician = build_person('a','b',21)
print( musician )

# 传递列表
def greet_users(names):
for name in names:
msg=f"Hello, {name.title()}!"
print(msg)
usernames=['a','b','c']
greet_users(usernames)
#修改列表
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("The 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)# ['phone case', 'robot pendant', 'dodecahedron']

# 传递副本
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("The 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)# ['phone case', 'robot pendant', 'dodecahedron]
print(unprinted_designs) #['phone case', 'robot pendant', 'dodecahedron']

def make_pizza(size,*toppings):# *toppings表示这个参数可以接受任意数量的实参,并将它们放在一个名为toppings的元组中
"""概述要制作的比萨"""
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza(16,'pepperoni')# 'makeing a 16-inch pizza with the following toppings: - pepperoni'
make_pizza(12,'mushrooms','green peppers','extra cheese')# 'makeing a 12-inch pizza with the following toppings: - mushrooms - green peppers - extra cheese'

# 接受传递任意数量的实参

def build_profile(first,last,**user_info):# **user_info表示这个参数可以接受任意数量的关键字实参,并将它们放在一个名为user_info的字典中
user_info['first_name']=first # 在user_info字典中添加一个键'first_name',其值为first参数的值
user_info['last_name']=last # 在user_info字典中添加一个键'last_name',其值为last参数的值
return user_info #将添加了first_name和last_name键值对的user_info字典返回

user_profile=build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile) # {'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}

# 将函数模块化

#导入整个模块
import pizza
pizza.make_pizza(16,'pepperoni')
pizza.make_pizza(12,'mushrooms','green peppers','extra cheese')


# 只导入一个函数
from pizza import make_pizza
make_pizza(16,'pepperoni')

# 使用别名
import pizza as pz
pz.make_pizza(16,'pepperoni')
from pizza import make_pizza as mp
mp(16,'pepperoni')

from pizza import * # 导入模块中的所有函数
# 这样写可能会导致命名冲突,但是如果模块是你自己编写的话,通常不会有问题
make_pizza(16,'pepperoni')

class 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def sit(self):
print(f"{self.name} is sitting.")

def roll(self):
print(f"{self.name} is rolling.")


my_dog = Dog('Niu Niu', 7)

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

my_dog.sit()
my_dog.roll()

your_dog = Dog('Lucy', 5)
your_dog.sit()
your_dog.roll()
print(f"Your dog's name is {your_dog.name}")


class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_read = 0 # 默认值为0
self.gas_tank = 0

def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name

def update_odometer(self, mileage):
if mileage >= self.odometer_read:
self.odometer_read = mileage
else:
print("You can't roll back an odometer!")

def incremen_odometer(self, miles):
if miles > 0:
self.odometer_read += miles
else:
print(f"Your can't add negative number!")

def fill_gas_tank(self):
# 将油箱属性设为 100
self.gas_tank = 100


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

# 修改属性的值


## 方法一:直接修改
my_new_car.odometer_read = 10
print(f"odometer_read: {my_new_car.odometer_read} miles")


## 方法二:通过方法修改

my_new_car.update_odometer(100)
print(f"odometer_read: {my_new_car.odometer_read} miles")

my_new_car.incremen_odometer(-1) # Your can't add negative number!
my_new_car.incremen_odometer(1)
print(my_new_car.odometer_read)


class ElectriCar(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.")

def fill_gas_tank(self):
print("This Car doesn't hava a gas tank!")


electriCar_1 = ElectriCar('audi', 'a4', 2024)
print(electriCar_1.get_descriptive_name())
electriCar_1.describe_battery()
electriCar_1.fill_gas_tank()

my_new_car.fill_gas_tank()
print(my_new_car.gas_tank)

class Car:
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_read = 0 # 默认值为0
self.gas_tank = 0

def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name

def update_odometer(self,mileage):
if mileage >= self.odometer_read:
self.odometer_read = mileage
else:
print("You can't roll back an odometer!")

def incremen_odometer(self,miles):
if miles > 0:
self.odometer_read += miles
else:
print(f"Your can't add negative number!")

def fill_gas_tank(self):
self.gas_tank = 100

class Battery:
def __init__(self,battery_size=40):
self.battery_size = battery_size

def get_range(self):
if self.battery_size == 40:
range = 150
elif self.battery_size == 65:
range = 225

return range

class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery = Battery()
def fill_gas_tank(self):
print("This car doesn't need a gas tank!")

def get_range(self):
range = self.battery.get_range()
print(f"This car can go about {range} miles on a full charge.")

def upgrade_battery(self):
if self.battery.battery_size < 65:
self.battery.battery_size = 65

my_tesla = ElectricCar('tesla','model s',2024)
print(my_tesla.get_descriptive_name())
my_tesla.get_range()
my_tesla.fill_gas_tank()

my_tesla.upgrade_battery()
my_tesla.get_range()


Python基础语法
https://www.mirstar.net/2025/09/28/Python-fundemental1/
作者
onlymatt
发布于
2025年9月28日
许可协议