Python的基础知识整理

前言

说明:
全部内容来源于《Python 编程从入门到实践》Eric Matthes

好记性不如烂笔头

末尾.py表明这是一个python程序,编辑器使用python解释器来运行它,解释器读取整个程序,确定每一个单词的含义
数据结构:序列、列表、元组、字典
流程控制:if判断、for循环

变量
1. 变量名只能包含数字、字母、下划线,但不能以数字开头
2. 变量名不能包含空格,但可以用下划线
3. 不要将python的关键字和函数名用作变量,如print
4. 变量名既简短有具有描述性
5. 慎用小写字母l和大写字母O,容易错看成数字1和0

字符串

就是一系列字符,单引号/双引号阔起来的。

name =“ada love”
print(name.title())
Ada Love

合并(拼接字符)

#用加号“+”合并字符串
first_name = "ada"
last_name = "lovelace" 
full_name = first_name + " " + last_name
print(full_name)
#打印结果
ada Lovelace

制表符/换行符

\t 制表符:开头添加一个空格
\n换行符:换行

print("Languages:\n\tPython\n\tC\n\tJavaScript")
#输出结果
Languages:
       Python
       C
       JavaScrip

数字

•	整数

可执行加减乘除运算(+、-、*、/),加括号可修改运算次序
乘方:**
3**3
27
• 浮点数
带小数点的数字都称为浮点数,结果包含的小数位是不确定的,暂时忽略多余的小数位数即可

0.2 + 0.1
0.30000000000000004
3 * 0.1
0.30000000000000004

列表

定义:
由一系列按特定顺序排列的元素组成。元素可以是字母、数字或者其他任何东西。
用方括号[]表示列表,逗号来分隔元素

访问列表元素

要访问列表元素,可指出列表的名称,再指出元素的索引,并将其放在方括号内。

bicycles = ['trek', 'cannondale', 'redline', 'specialized'] 
print(bicycles[0])
#trek

'''索引从0开始,例如返回第二个元素为bicycles[1]
访问最后一个列表元素的特殊语法:索引指定为-1,倒数第二为-2.'''
bicycles[-1]
#结果:specialized

修改列表元素

要修改列表元素,可指定列表名和要修改的元素的索引,再指定该元素的新值。
例如,假设有一个摩托车列表,其中的第一个元素为’honda’ ,如何修改它的值呢?

motorcycles.py
 motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
 motorcycles[0] = 'ducati'
print(motorcycles)
#结果
#['honda', 'yamaha', 'suzuki']
#['ducati', 'yamaha', 'suzuki']

列表中添加元素

列表末尾添加元素
append()

motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)
#结果输出
['honda', 'yamaha', 'suzuki']

列表中插入元素,指定新元素的索引和值

insert()

motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
#结果展示
['ducati', 'honda', 'yamaha', 'suzuki']

从列表中删除元素

⁃ del

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
#结果展示
['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']

⚠️使用**pop()**删除元素:将元素从列表中删除,并接着使用它
pop() :可删除列表末尾的元素,并让你能够继续使用它

motorcycles = ['honda', 'yamaha', 'suzuki']
last_owned = motorcycles.pop()
print("The last motorcycle I owned was a " + last_owned.title() + ".")
#结果
The last motorcycle I owned was a Suzuki.

pop(0):可弹出任意位置的值
first_owned = motorcycles.pop(0)。列表中弹出首值位

remove()

知道要删除列表的元素的值,不知道具体位置的值

motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
#结果
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']

组织列表

sort()
对列表进行排序,必须是同一类型的元素,否则需要进行列表转换。排序是永久性的

汽车是按字母顺序排列的,再也无法恢复到原来的排列顺序:

cars = ['bmw', 'audi', 'toyota', 'subaru'] 
 cars.sort()
print(cars)
#结果
['audi', 'bmw', 'subaru', 'toyota']

sort(reverse=True)
按与字母顺序相反的顺序排列列表元素

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

['toyota', 'subaru', 'bmw', 'audi']

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)
#结果
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']
Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']
 Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']

reverse()
反转列表元素的排列顺序

cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
#结果
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']

方法reverse() 永久性地修改列表元素的排列顺序,但可随时恢复到原来的排列顺序,为此只需对列表再次调用reverse() 即可。

len()
确定列表的长度

cars = ['bmw', 'audi', 'toyota', 'subaru']
len(cars)
#结果
4

元组

定义:圆括号“()”标识,犹如列表,但元组内的元素不可更改

dimensions = (200, 50) 
print(dimensions[0])
print(dimensions[1])
#结果输出:
200
50

下面来尝试修改元组dimensions 中的一个元素,看看结果如何:

dimensions = (200, 50) 
dimensions[0] = 250
#会报错,提示类型错误

⁃ 可以对元组变量重新赋值

dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
      print(dimension)
dimensions = (400, 100) 
print("\nModified dimensions:")
for dimension in dimensions:
      print(dimension)
#结果输出:
Original dimensions:
200
50
Modified dimensions:
400
100

字典

定义:是一系列的键-值对。用花括号”{}” 中的一系列键值对表示
可以存储的是一个对象的多种信息或者存储众多对象的同一种信息
alien_0={‘color’:’green’,’point’:5}

访问字典中的值

指定与值相关的键

alien_0 = {'color': 'green', 'points': 5}
new_points = alien_0['points'] 
print("You just earned " + str(new_points) + " points!")
#结果输出:
You just earned 5 points!

添加键—值对

alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0 
alien_0['y_position'] = 25
print(alien_0)
#结果输出:
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}

修改字典中的值

alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")
#结果输出:
The alien is green.
The alien is now yellow.

删除键—值对:指定字典名和键

必须指定字典名和要删除的键

alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
#结果输出:
{'color': 'green', 'points': 5}
{'color': 'green'}

嵌套

需将一系列字典存储在列表中,或将列表作为值存储在字典中

列表中嵌套字典

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)
#结果输出:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

字典中存储列表

pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
#概述所点的比萨
print("You ordered a " + pizza['crust'] + "-crust pizza " +
"with the following toppings:")
for topping in pizza['toppings']:
   print("\t" + topping)
#结果输出:
You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese

字典嵌套字典

users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items(): 
   print("\nUsername: " + username) 
   full_name = user_info['first'] + " " + user_info['last']
   location = user_info['location']
   print("\tFull name: " + full_name.title())
   print("\tLocation: " + location.title())
#结果输出:
Username: aeinstein
        Full name: Albert Einstein
        Location: Princeton
Username: mcurie
         Full name: Marie Curie
         Location: Paris

流程操作

for 循环

定义:需要对列表内的每个元素执行相同的运算
⚠️for语句后的冒号不能忘,不加执行提示语法错误。⚠️缩进,for语句后缩进部分是循环体,在循环内重复执行
• 遍历
• 遍历整个列表

magicians = ['alice', 'david', 'carolina'] 
for magician in magicians: 
       print(magician.title())
#结果     
Alice
David
Carolina

这个代码从列表magicians 中取出一个元素,并将其存储在变量magician中

遍历切片

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:") 
for player in players[:3]:
     print(player.title())
#结果
Here are the first three players on my team:
Charles
Martina
Michael

遍历元组内的值

dimensions = (200, 50)
for dimension in dimensions:
      print(dimension)
#结果
200
50

遍历字典

遍历所有的键——值对

user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items(): 
   print("\nKey: " + key) 
   print("Value: " + value)
#结果
Key: last
Value: fermi
Key: first
Value: enrico
Key: username
Value: efermi

遍历字典中所有键

favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():
    print(name.title())
#结果输出:
Jen
Sarah
Phil
Edward

遍历字典中的所有值

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())
#结果输出:
The following languages have been mentioned:
Python
C
Python
Ruby

使用列表的一部分,切片,选取列表中部分的元素

players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
print(players[0:3])
#结果输出:
['charles', 'martina', 'michael']

print(players[1:4])
#结果输出:
['martina', 'michael', 'florence']

print(players[:4])
#结果输出:
['charles', 'martina', 'michael', 'florence']

print(players[2:])
#结果输出:
['michael', 'florence', 'eli']

print(players[-3:])
#上述代码打印最后三名队员的名字,即便队员名单的长度发生变化,也依然如此。(打印结果同上)

复制列表
⁃ 创建列表的副本

my_foods = ['pizza', 'falafel', 'carrot cake'] 
friend_foods = my_foods[:] #新建列表副本
my_foods.append('cannoli') 
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
#结果输出:
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli']
My friend's favorite foods are: 
['pizza', 'falafel', 'carrot cake', 'ice cream']

⁃ 赋值列表

my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods
 my_foods 赋给friend_foods ,而不是将my_foods 的副本存储到friend_foods
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
#结果输出:
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']

if语句

表达式的条件测试

Ture还是False来决定是否执行if语句中的代码
1. 检查是否时区分大小写,‘Alice’!=‘alice’
2. 数字比较:age=19
age<=21/age>21/age>=21
3.检查多个条件:and/or

age_0 = 22
age_1 = 18 
age_0 >= 21 and age_1 >= 21
False 
age_0 >= 21 and age_1 >= 17
True
#使用or
age_0 >= 21 or age_1 >= 21
True
age_0 >= 23 or age_1 >= 21
False

4.检查特定值是否包含在列表中

'''包含'''
 requested_toppings = ['mushrooms', 'onions', 'pineapple'] 
'mushrooms' in requested_toppings
True 
'pepperoni' in requested_toppings
False
'''不包含'''
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
    print(user.title() + ", you can post a response if you wish.")

5.布尔表达式:布尔表达式的结果只有两个 True/False
为跟踪程序状态或程序中重要的条件方面,布尔值提供了一种高效的方式

game_active = True
can_edit = False

if语句

简单的if语句

如果条件测试的结果为True ,Python就会执行紧跟在if 语句后面的代码;否则Python将忽略这些代码。

age = 19 
if age >= 18:   #⚠️冒号不能丢
    print("You are old enough to vote!")

You are old enough to vote!
	•	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!")
#结果输出:
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!

If-elif-else 结构(多种情形)

if-elif-else 结构功能强大,但仅适合用于只有一个条件满足的情况:遇到通过了的测试后,Python就跳过余下的测试。这种行为很好,效率很高,让你能够测试一个特定的条件。

4岁以下免费;
4~18岁收费5美元;
18岁(含)以上收费10美元。

age = 12
if age < 4:
    print("Your admission cost is $0.") 
elif age < 18:
    print("Your admission cost is $5.") 
else:
    print("Your admission cost is $10.")

Your admission cost is $5.

条件增多,可使用多个elif代码块,else可省略,只保留 if-elif-…-elif结构

if-if -if结构(测试多个条件)

有时候必须检查你关心的所有条件。在这种情况下,应使用一系列不包含elif 和else 代码块的简单if 语句。在可能有多个条件为True ,且你需要在每个条件为True 时都采取相应措施时,适合使用这种方法。

下面再来看前面的比萨店示例。如果顾客点了两种配料,就需要确保在其比萨中包含这些配料:

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!")
#结果输出:
Adding mushrooms.
Adding extra cheese.
Finished making your pizza!

使用if语句处理列表

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("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
'''这里在比萨中添加每种配料前都进行检查。处的代码检查顾客点的是否是青椒,如果是,就显示一条消息,指出不能点青椒的原因。else 代码块确保其他配料都将添加到比萨中
输出表明,妥善地处理了顾客点的每种配料:'''
Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.
Finished making your pizza!

while循环

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

简单的while循环

current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
#结果输出:
1
2
3
4
5

用户选择何时退出

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)

#结果输出:
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello everyone!
Hello everyone!
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello again.
Hello again.
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit

使用标志位

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 = False 
else:
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':
        break
     else:
        print("I'd love to go to " + city.title() + "!")

#结果输出:
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) New York
I'd love to go to New York!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) San Francisco
I'd love to go to San Francisco!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) quit

循环中使用continue

current_number = 0
while current_number < 10: 
   current_number += 1
   if current_number % 2 == 0:
       continue
   print(current_number)

#结果输出:
1
3
5
7
9

定义函数

def greet_user():
     Print(‘hello!’)
great_user()
#结果输出:
hello!

向函数传递信息(实参和形参)

def greet_user(username): """显示简单的问候语"""
print("Hello, " + username.title() + "!")
greet_user('jesse')

#结果输出:
Hello,Jesse!

传递实参

直接传递
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('hamster', 'harry') #必须按照顺序
describe_pet('dog', 'willie')

#结果输出:
I have a hamster.
My hamster's name is Harry.
I have a dog.
My dog's name is Willie.
关键字实参

def describe_pet(animal_type, pet_name):
“”“显示宠物的信息”“”

describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster'#关键字实参可以不考虑实参
默认值
def describe_pet(pet_name, animal_type='dog'):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')

#结果输出:
I have a dog.
My dog's name is Willie.

返回值

返回简单值
def get_formatted_name(first_name, last_name): 
                """返回整洁的姓名"""
	full_name = first_name + ' ' + last_name 
	return full_name.title()
musician = get_formatted_name('jimi', 'hendrix') print(musician)

#结果输出:
 Jimi Hendrix 
返回字典
def build_person(first_name, last_name): 
      """返回一个字典,其中包含有关一个人的信息"""
	person = {'first': first_name, 'last': last_name} 
	return person
musician = build_person('jimi', 'hendrix') 
print(musician)

#结果输出:
{'first': 'jimi', 'last': 'hendrix‘}

结合使用函数和while循环

def get_formatted_name(first_name, last_name): 
     """返回整洁的姓名"""
	full_name = first_name + ' ' + last_name 
	return full_name.title()
	while True:
		print("\nPlease tell me your name:") 
		print("(enter 'q' at any time to quit)")
		f_name = input("First name: ") 
		if f_name == 'q':
		  break
		l_name = input("Last name: ") 
		if l_name == 'q':
		  break
formatted_name = get_formatted_name(f_name, l_name) print("\nHello, " + formatted_name + "!")

#结果输出:
Please tell me your name: (enter 'q' at any time to quit) First name: eric
Last name: matthes
Hello, Eric Matthes!
Please tell me your name: (enter 'q' at any time to quit) First name: q

传递列表

def greet_users(names):
 """向列表中的每位用户都发出简单的问候""" 
 for name in names:
		msg = "Hello, " + name.title() + "!" print(msg)
usernames = ['hannah', 'ty', 'margot'] greet_users(usernames)

#结果输出:
Hello, Hannah! Hello, Ty! Hello, Margot!

传递任意数量的实参

参数数量不确定的时候

def make_pizza(*toppings): 
"""打印顾客点的所有配料""" 
   print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

#结果输出:
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')

结合使用位置实参和任意数量实参

def make_pizza(size, *toppings): 
	"""概述要制作的比萨""" 
	print("\nMaking a " + str(size) +
	"-inch pizza with the following toppings:") 
	for topping in toppings:
		print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

#结果输出:
Making a 16-inch pizza with the following toppings: - pepperoni
Making a 12-inch pizza with the following toppings: - mushrooms
- green peppers
- extra cheese

使用任意数量的关键字实参

def build_profile(first, last, **user_info): 
"""创建一个字典,其中包含我们知道的有关用户的一切"""                          profile = {}
 profile['first_name'] = first profile['last_name'] = last
    for key, value in user_info.items(): 
      profile[key] = value
    return profile
user_profile = build_profile('albert', 'einstein', location='princeton',
print(user_profile)

#结果输出:
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}

导入模块

将函数存储在模块中

#导入模块
import pizza

#导入特定的函数
from module_name import function_name,funnction_0

#使用as给函数指定别名
from pizza import make_pizza as mp

#使用as给模块指定别名
import module_name as men

#导入模块中的所有函数
from pizza import *

定义一大类对象都有通用行为,基于类创建对象,每个对象都自动具备这种通用行为,然后根据需要赋予每个对象独特的个性。
根据类来创建对象被称为实例化,这让你能够使用类的实例

创建和使用类

通常首字母大写的指的是类,类其实就像一个模具
方法_init_():
类中的函数,形参self必不可少,必须位于其他形参前面

 class Dog(): 
 """一次模拟小狗的简单尝试"""
	 def __init__(self, name, age):
	"""初始化属性name和age""" 
		self.name = name
		self.age = age
	def sit(self):
	 """模拟小狗被命令时蹲下""" 
	    print(self.name.title()
	def roll_over(self): 
     """模拟小狗被命令时打滚""" 
        print(self.name.title()+ " is now sitting.")+ " rolled over!")

访问属性

my_dog.name

My dog's name is Willie.
My dog is 6 years old.

调用方法

class Dog(): 
--snip--
my_dog = Dog('willie', 6) 
my_dog.sit() 
my_dog.roll_over()

Willie is now sitting.
Willie rolled over!

创建多个实例

class Dog(): 
--snip--
my_dog = Dog('willie', 6) 
your_dog = Dog('lucy', 3)
print("My dog's name is " + my_dog.name.title() + ".") print("My dog is " + str(my_dog.age) + " years old.") my_dog.sit()
print("\nYour dog's name is " + your_dog.name.title() + ".") print("Your dog is " + str(your_dog.age) + " years old.") your_dog.sit()

#输出结果:
My dog's name is Willie. My dog is 6 years old. Willie is now sitting.
Your dog's name is Lucy. Your dog is 3 years old. Lucy is now sitting.

使用类和实例

class Car(): 
         """一次模拟汽车的简单尝试"""
     def __init__(self, make, model, year): """初始化描述汽车的属性"""
        self.make = make
		self.model = model
		self.year = year

     def get_descriptive_name(self):
            """返回整洁的描述性信息"""
         long_name = str(self.year) + ' ' + self.make + ' ' + self.model 
         return long_name.title()
         
my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name())

#解果输出
2016 Audi A4
给属性指定默认值

类中的每个属性都必须有初始值,哪怕是0或者空字符串

 class Car():
        def __init__(self, make, model, year): 
                """初始化描述汽车的属性"""
                 self.make = make
                 self.model = model
                 self.year = year
                    self.odometer_reading = 0
         def. get_descriptive_name(self): 
                      --snip--
         def read_odometer(self):
                """打印一条指出汽车里程的消息"""
                print("This car has " + str(self.odometer_reading) + " miles on it.")
my_new_car = Car('audi', 'a4', 2016) 
print(my_new_car.get_descriptive_name()) my_new_car.read_odometer()

#结果输出
2016 Audi A4
This car has 0 miles on it.

修改属性的值

直接修改属性的值

class Car(): --snip--
my_new_car = Car('audi', 'a4', 2016) print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23 my_new_car.read_odometer()

#结果输出
2016 Audi A4
This car has 23 miles on it.

通过方法修改属性的值

class Car(): 
      --snip--
     def update_odometer(self, mileage): """将里程表读数设置为指定的值""" 
           self.odometer_reading = mileage
my_new_car = Car('audi', 'a4', 2016) 
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(23) my_new_car.read_odometer()

#结果输出
2016 Audi A4
This car has 23 miles on it.

通过方法对属性的值直接进行递增

class Car(): 
         --snip--
        def update_odometer(self, mileage): 
        --snip--
        def increment_odometer(self, miles): """将里程表读数增加指定的量""" self.odometer_reading += miles
my_used_car = Car('subaru', 'outback', 2013) 
print(my_used_car.get_descriptive_name())
my_used_car.update_odometer(23500) my_used_car.read_odometer()
my_used_car.increment_odometer(100) my_used_car.read_odometer()

#结果输出
2013 Subaru Outback
This car has 23500 miles on it. This car has 23600 miles on it.

继承

一个类继承另一个类时,它将自动获得另一个类的所有属性和方法,原有的类称为父类,新类称为子类。子类继承了其其父类的所有属性和方法,同时还定义自己的属性和方法。

导入类

导入单个类:
存在car.py的文件,并且包含class Car()类

from car import Car

在一个模块中存储多个类,从一个模块中导入多个类

from car import Car,ElectricCar

导入整个模块

import car 

文件和异常

文件处理

读取文件

在这里插入图片描述
逐行读取,利用for 循环
在这里插入图片描述
用列表存储文件内容,以便于其他函数调用
在这里插入图片描述

写入文件

在这里插入图片描述

添加文件内容

在这里插入图片描述

异常

在这里插入图片描述
处理FileNotFoundError
在这里插入图片描述
使用多个文件
在这里插入图片描述
pass语句,失败时一声不吭

存储数据

存储数据和读取数据
在这里插入图片描述

生成器

一边循环一边计算的机制称为生成器(generator)
节省系统资源
在这里插入图片描述在这里插入图片描述

迭代器

迭代是访问集合元素的一种方式,迭代器是一个可以记住遍历位置的对象。
迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退,可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator
所以,生成器也是一种迭代器

判断是否是一个可迭代对象
在这里插入图片描述
在这里插入图片描述
定义:函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需要调用其函数名即可
可以减少代码的复用
方便修改,便于扩展
保持代码的一致性

进入方法:选中某个方法,按住crtl键进入查看
类内的参数会直接定位到_init_方法

内置方法

built-in函数官方文档

字符串操作

字符串大小写
title():方法表以首字母大写的方式显示每个单词
upper():字符串全为大写
lower():字符串全为小写
删除空白
删除字符串中多余的空白(最常用于在存储用户输入前对其进行清理)
rstrip(): 删除末尾
lstrip():删除开头
strip():删除两端

favorite_language = '  python  ' 
 favorite_language.rstrip()
'  python'
 favorite_language.lstrip()
'python  ' 
 favorite_language.strip()
'python'

⚠️调用方法后,多余空格只是暂时被删除了,再次询问变量值时,会发现这个字符串同原来的字符串是一样的。
永久删除,必须将删除操作的结果存回到变量中

favorite_language = 'python ' 
favorite_language = favorite_language.rstrip()
favorite_language
'python'

非字符转换为字符串
str()

age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)

Happy 23rd Birthday!

列表操作

range()函数
生成一系列数字

for value in range(1,6):    #步长默认为1
     print(value)
#这样,输出将从1开始,到5结束:
1
2
3
4
5

创建数字列表

even_numbers = list(range(2,11,2))#步长为2
print(even_numbers)
#在这个示例中,函数range() 从2开始数,然后不断地加2,直到达到或超过终值(11),因此输出如下:
[2, 4, 6, 8, 10]

squares = []
for value in range(1,11): 
     squares.append(value**2)
print(squares)
#结果输出
[1,4,9,16,25,36,49,64,81,100]

数字列表的统计计算
min()、max() 、sum()

digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
min(digits)
#结果为:0
 max(digits)
#结果为:9
sum(digits)
#结果为:45
•	input()函数

input()让程序暂停运行,等待用户输入一些文本,获取用户输入后,Python将其存储在一个变量中。⚠️使用该函数时, python将用户输入解读为字符串

name = input("Please enter your name: ")
print("Hello, " + name + "!")
#结果输出:
Please enter your name: Eric
Hello, Eric!
•	int()

将字符串转换为数值表示

height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
    print("\nYou're tall enough to ride!")
else:
    print("\nYou'll be able to ride when you're a little older.")
#结果输出:
How tall are you, in inches? 71
You're tall enough to ride!
•	求模运算符

求模运算符(%),将两个数相除并返回余数

a=4%3
print(a) #1
Python基础知识整理包括以下几个方面: 1. 数据类型:Python中常见的数据类型有整数(int)、浮点数(float)、字符串(str)、布尔值(bool)、列表(list)、元组(tuple)、字典(dict)等。 2. 变量和赋值:在Python中,可以使用变量来保存数据,并使用赋值语句将值赋给变量。变量名可以由字母、数字和下划线组成,但不能以数字开头。 3. 运算符:Python支持常见的算术运算符(如加减乘除)、比较运算符(如等于、大于、小于等)、逻辑运算符(如与、或、非)等。 4. 控制流程:Python中的控制流程包括条件语句(if-else)、循环语句(while和for)以及跳转语句(break和continue)等。 5. 函数和模块:函数是一段可重复使用的代码块,可以通过函数来组织代码和实现代码的复用。而模块是一个包含了函数、类和变量的文件,可以通过import语句导入并使用。 6. 异常处理:在编写程序时,可能会出现错误,为了避免程序崩溃,可以使用异常处理机制来捕捉和处理错误,保证程序的正常执行。 7. 文件操作:Python提供了丰富的文件操作函数,可以读取和写入文件内容,以及对文件进行其他操作。 8. 面向对象编程:Python是一种面向对象的编程语言,支持类和对象的概念,可以通过定义类来创建对象,并使用对象调用类中的方法和属性。 这些是Python基础知识的主要内容,希望对你有所帮助。如果你有具体的问题,可以继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值