Python3速查表:语法、数据结构与函数全解析
基础语法
向用户显示输出
print
函数用于显示或打印输出。
print("Hello, World!")
从用户获取输入
input
函数用于从用户获取输入,输入内容默认为字符串类型。
name = input("Enter your name: ")
若需要其他数据类型的输入,需要进行类型转换。
# 获取整数输入
age = int(input("Enter your age: "))
# 获取浮点数输入
height = float(input("Enter your height: "))
range 函数
range
函数返回一个数字序列,例如,range(0, n)
生成从 0 到 n-1 的数字。
# 生成 0 到 9 的数字序列
numbers = list(range(10))
print(numbers) # 输出: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 生成 2 到 10 的偶数序列
even_numbers = list(range(2, 11, 2))
print(even_numbers) # 输出: [2, 4, 6, 8, 10]
注释
注释用于提高代码的可读性,不会被编译器或解释器执行。
单行注释
# 这是一个单行注释
多行注释
"""
这是一个多行注释,
可以跨越多行。
"""
转义序列
转义序列是在字符串字面量或字符中使用时,不表示自身的字符序列,而是被翻译成另一个字符。
换行符
print("Hello\nWorld!") # 输出: Hello\nWorld!(两行)
反斜杠
print("This is a backslash: \\") # 输出: This is a backslash: \
单引号
print("This is a single quote: \'") # 输出: This is a single quote: '
制表符
print("Name\tAge\tCountry") # 输出: Name Age Country
退格符
print("Hello\bWorld!") # 输出: HelloWorld!(退格)
八进制值
print("\110\145\154\154\157") # 输出: Hello(八进制表示)
十六进制值
print("\x48\x65\x6c\x6c\x6f") # 输出: Hello(十六进制表示)
回车符
print("Hello\rWorld!") # 输出: World!(回车,覆盖前面的内容)
字符串
Python 字符串是由字符组成的序列,可以通过索引单独访问每个字符。
字符串创建
可以使用单引号或双引号创建字符串。
string1 = 'Hello'
string2 = "World"
索引
字符串中每个字符的位置从 0 开始,依次递增。
string = "Hello"
print(string[0]) # 输出: H
print(string[4]) # 输出: o
切片
切片用于从给定字符串中获取子字符串。
string = "Hello, World!"
print(string[0:5]) # 输出: Hello
print(string[7:]) # 输出: World!
print(string[:5]) # 输出: Hello
print(string[::2]) # 输出: Hlo, Wr!
字符串方法
isalnum() 方法
如果字符串中的所有字符都是字母数字,则返回 True,否则返回 False。
print("Hello123".isalnum()) # 输出: True
print("Hello 123".isalnum()) # 输出: False
isalpha() 方法
如果字符串中的所有字符都是字母,则返回 True,否则返回 False。
print("Hello".isalpha()) # 输出: True
print("Hello123".isalpha()) # 输出: False
isdecimal() 方法
如果字符串中的所有字符都是十进制数字,则返回 True,否则返回 False。
print("12345".isdecimal()) # 输出: True
print("12.34".isdecimal()) # 输出: False
isdigit() 方法
如果字符串中的所有字符都是数字,则返回 True,否则返回 False。
print("12345".isdigit()) # 输出: True
print("Hello123".isdigit()) # 输出: False
islower() 方法
如果字符串中的所有字符都是小写字母,则返回 True,否则返回 False。
print("hello".islower()) # 输出: True
print("Hello".islower()) # 输出: False
isspace() 方法
如果字符串中的所有字符都是空白字符,则返回 True,否则返回 False。
print(" ".isspace()) # 输出: True
print("Hello".isspace()) # 输出: False
isupper() 方法
如果字符串中的所有字符都是大写字母,则返回 True,否则返回 False。
print("HELLO".isupper()) # 输出: True
print("Hello".isupper()) # 输出: False
lower() 方法
将字符串转换为小写。
print("Hello".lower()) # 输出: hello
upper() 方法
将字符串转换为大写。
print("hello".upper()) # 输出: HELLO
strip() 方法
移除字符串开头和结尾的空白字符。
print(" Hello, World! ".strip()) # 输出: Hello, World!
列表
Python 列表是用方括号括起来的逗号分隔值的集合,可以包含不同数据类型的元素。
列表创建
list1 = [1, 2, 3, 4, 5]
list2 = ["apple", "banana", "cherry"]
list3 = [1, "apple", 3.14, True]
索引
列表中每个元素的位置从 0 开始,依次递增。
list = [10, 20, 30, 40, 50]
print(list[0]) # 输出: 10
print(list[4]) # 输出: 50
列表方法
index() 方法
返回指定值的第一个元素的索引。
list = [10, 20, 30, 40, 50]
print(list.index(30)) # 输出: 2
append() 方法
在列表末尾添加一个元素。
list = [10, 20, 30]
list.append(40)
print(list) # 输出: [10, 20, 30, 40]
extend() 方法
将一个给定列表(或任何可迭代对象)的元素添加到当前列表的末尾。
list1 = [10, 20, 30]
list2 = [40, 50]
list1.extend(list2)
print(list1) # 输出: [10, 20, 30, 40, 50]
insert() 方法
在指定位置添加一个元素。
list = [10, 20, 40, 50]
list.insert(2, 30)
print(list) # 输出: [10, 20, 30, 40, 50]
pop() 方法
移除指定位置的元素并返回它。
list = [10, 20, 30, 40, 50]
removed_element = list.pop(2)
print(removed_element) # 输出: 30
print(list) # 输出: [10, 20, 40, 50]
remove() 方法
移除列表中第一个出现的指定值。
list = [10, 20, 30, 40, 50]
list.remove(30)
print(list) # 输出: [10, 20, 40, 50]
clear() 方法
移除列表中的所有元素。
list = [10, 20, 30]
list.clear()
print(list) # 输出: []
count() 方法
返回具有指定值的元素数量。
list = [10, 20, 10, 30, 10]
print(list.count(10)) # 输出: 3
reverse() 方法
反转列表的顺序。
list = [10, 20, 30, 40, 50]
list.reverse()
print(list) # 输出: [50, 40, 30, 20, 10]
sort() 方法
对列表进行排序。
list = [30, 10, 40, 20, 50]
list.sort()
print(list) # 输出: [10, 20, 30, 40, 50]
元组
元组是用括号括起来的逗号分隔值的集合,可以包含不同数据类型的元素。
元组创建
tuple1 = (1, 2, 3, 4, 5)
tuple2 = ("apple", "banana", "cherry")
tuple3 = (1, "apple", 3.14, True)
索引
元组中每个元素的位置从 0 开始,依次递增。
tuple = (10, 20, 30, 40, 50)
print(tuple[0]) # 输出: 10
print(tuple[4]) # 输出: 50
元组方法
count() 方法
返回元组中指定值出现的次数。
tuple = (10, 20, 10, 30, 10)
print(tuple.count(10)) # 输出: 3
index() 方法
在元组中查找指定值并返回其位置。
tuple = (10, 20, 30, 40, 50)
print(tuple.index(30)) # 输出: 2
集合
集合是用花括号括起来的多个值的集合,是无序且不带索引的。
集合创建
方法 1
set1 = {"apple", "banana", "cherry"}
方法 2
set2 = set(["apple", "banana", "cherry"])
集合方法
add() 方法
向集合中添加一个元素。
set = {"apple", "banana", "cherry"}
set.add("orange")
print(set) # 输出: {'apple', 'banana', 'cherry', 'orange'}
clear() 方法
移除集合中的所有元素。
set = {"apple", "banana", "cherry"}
set.clear()
print(set) # 输出: set()
discard() 方法
从集合中移除指定元素。
set = {"apple", "banana", "cherry"}
set.discard("banana")
print(set) # 输出: {'apple', 'cherry'}
intersection() 方法
返回两个或更多集合的交集。
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "banana", "apple"}
print(set1.intersection(set2)) # 输出: {'apple', 'banana'}
issubset() 方法
检查一个集合是否是另一个集合的子集。
set1 = {"apple", "banana"}
set2 = {"apple", "banana", "cherry"}
print(set1.issubset(set2)) # 输出: True
pop() 方法
从集合中移除一个元素。
set = {"apple", "banana", "cherry"}
removed_element = set.pop()
print(removed_element) # 输出: 'apple'(或另一个随机元素)
print(set) # 输出: {'banana', 'cherry'}(或另一个组合)
remove() 方法
从集合中移除指定元素。
set = {"apple", "banana", "cherry"}
set.remove("banana")
print(set) # 输出: {'apple', 'cherry'}
union() 方法
返回两个或更多集合的并集。
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "banana", "apple"}
print(set1.union(set2)) # 输出: {'apple', 'banana', 'cherry', 'google'}
字典
字典是无序的键值对集合,用花括号括起来,要求字典中的键是唯一的。
字典创建
dict1 = {"name": "John", "age": 30, "city": "New York"}
空字典
可以通过放置两个花括号来创建一个空白字典。
empty_dict = {}
向字典中添加元素
dict = {"name": "John", "age": 30}
dict["city"] = "New York"
print(dict) # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}
更新字典中的元素
如果指定的键已经存在,则其值将被更新。
dict = {"name": "John", "age": 30}
dict["age"] = 35
print(dict) # 输出: {'name': 'John', 'age': 35}
从字典中删除元素
使用 del
关键字删除指定的键值对。
dict = {"name": "John", "age": 30, "city": "New York"}
del dict["age"]
print(dict) # 输出: {'name': 'John', 'city': 'New York'}
字典方法
len() 方法
返回字典中元素(键值对)的数量。
dict = {"name": "John", "age": 30, "city": "New York"}
print(len(dict)) # 输出: 3
clear() 方法
移除字典中的所有元素。
dict = {"name": "John", "age": 30, "city": "New York"}
dict.clear()
print(dict) # 输出: {}
get() 方法
返回指定键的值。
dict = {"name": "John", "age": 30, "city": "New York"}
print(dict.get("name")) # 输出: John
items() 方法
返回一个包含字典中每个键值对的元组的列表。
dict = {"name": "John", "age": 30, "city": "New York"}
print(dict.items()) # 输出: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])
keys() 方法
返回一个包含字典中键的列表。
dict = {"name": "John", "age": 30, "city": "New York"}
print(dict.keys()) # 输出: dict_keys(['name', 'age', 'city'])
values() 方法
返回一个包含字典中值的列表。
dict = {"name": "John", "age": 30, "city": "New York"}
print(dict.values()) # 输出: dict_values(['John', 30, 'New York'])
update() 方法
用指定的键值对更新字典。
dict1 = {"name": "John", "age": 30}
dict2 = {"city": "New York", "country": "USA"}
dict1.update(dict2)
print(dict1) # 输出: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
缩进
在 Python 中,缩进是指代码块使用空格或制表符进行缩进,以便解释器能够轻松执行 Python 代码。
缩进应用于条件语句和循环控制语句。缩进指定了根据条件要执行的代码块。
条件语句
if
、elif
和 else
语句是 Python 中的条件语句,它们实现了选择结构(决策结构)。
if 语句
age = 20
if age >= 18:
print("You are an adult.")
if-else 语句
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
if-elif 语句
score = 75
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("D")
嵌套 if-else 语句
num = 10
if num > 0:
if num % 2 == 0:
print("Positive and even")
else:
print("Positive and odd")
else:
print("Non-positive")
Python 中的循环
循环或迭代语句会反复执行一个语句,直到控制表达式为假。
for 循环
Python 的 for 循环设计用于处理任何序列(如列表或字符串)中的项。
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
while 循环
while 循环是一种条件循环,只要条件为真,就会重复执行内部的指令。
count = 0
while count < 5:
print(count)
count += 1
break 语句
break 语句允许程序跳过代码的一部分。break 语句终止它所在的循环。
for num in range(10):
if num == 5:
break
print(num) # 输出: 0, 1, 2, 3, 4
continue 语句
continue 语句跳过循环的其余部分,并导致下一次迭代发生。
for num in range(10):
if num % 2 == 0:
continue
print(num) # 输出: 1, 3, 5, 7, 9
函数
函数是一段执行特定任务的代码块。你可以将参数传递给函数。它有助于使我们的代码更加有组织和易于管理。
函数定义
在定义函数之前使用 def
关键字。
def greet(name):
print(f"Hello, {name}!")
函数调用
每当在程序中需要该代码块时,只需调用该函数的名称。如果在定义函数时传递了参数,那么在调用函数时也需要传递参数。
greet("John") # 输出: Hello, John!
Python 函数中的 return 语句
函数的 return 语句将指定的值或数据项返回给调用者。
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 输出: 8
Python 函数中的参数
参数是定义和调用函数时括号内传递的值。
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")
greet("John", 30) # 输出: Hello, John! You are 30 years old.
文件处理
文件处理是指读取或写入文件中的数据。Python 提供了一些函数,允许我们操作文件中的数据。
open() 函数
file = open("example.txt", "r")
模式
- r - 从文件中读取内容
- w - 向文件中写入内容
- a - 将内容追加到文件中
- r+ - 读取和写入数据到文件中。文件中的先前数据将被覆盖。
- w+ - 写入和读取数据。它将覆盖现有数据。
- a+ - 追加和从文件中读取数据。它不会覆盖现有数据。
close() 函数
file = open("example.txt", "r")
# 操作文件
file.close()
read() 函数
read
函数包含不同的方法:read()
、readline()
和 readlines()
。
read()
返回文件中的所有内容。readline()
返回文件中的一行。readlines()
返回一个包含文件中各行的列表。
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
write() 函数
此函数将字符串序列写入文件。
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()
异常处理
异常是导致程序流程中断的不寻常情况。
try 和 except
这是 Python 中的基本 try-catch 块。当 try 块抛出错误时,控制权转到 except 块。
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
else
如果 try 块没有引发任何异常,并且代码成功运行,则执行 else 块。
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print(f"Result: {result}")
finally
无论 try 块的代码是否成功运行,还是 except 块的代码被执行,finally 块的代码都将被执行。finally 块的代码将强制执行。
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("This will always execute.")
面向对象编程(OOP)
这是一种主要关注使用对象和类的编程方法。对象可以是任何现实世界的实体。
类
在 Python 中编写类的语法。
class MyClass:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, {self.name}!")
创建对象
可以通过以下方式实例化对象:
obj = MyClass("John")
obj.greet() # 输出: Hello, John!
self 参数
self 参数是类中任何函数的第一个参数。它可以有不同的名称,但在类中定义任何函数时必须有此参数,因为它用于访问类的其他数据成员。
带有构造函数的类
构造函数是类的特殊函数,用于初始化对象。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Python 中的继承
通过使用继承,我们可以创建一个类,该类使用另一个类的所有属性和行为。新类被称为派生类或子类,而被获取属性的类被称为基类或父类。
它提供了代码的可重用性。
继承的类型
- 单继承
- 多继承
- 多级继承
- 层次继承
filter 函数
filter 函数允许处理可迭代对象并提取满足给定条件的项。
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # 输出: [2, 4]
issubclass 函数
用于查找一个类是否是指定类的子类。
class Parent:
pass
class Child(Parent):
pass
print(issubclass(Child, Parent)) # 输出: True
迭代器和生成器
以下是 Python 编程语言的一些高级主题,如迭代器和生成器。
迭代器
用于创建可迭代对象的迭代器。
numbers = [1, 2, 3, 4, 5]
iterator = iter(numbers)
print(next(iterator)) # 输出: 1
print(next(iterator)) # 输出: 2
生成器
用于动态生成值。
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
counter = count_up_to(5)
print(next(counter)) # 输出: 1
print(next(counter)) # 输出: 2
装饰器
装饰器用于修改函数或类的行为。它们通常在要装饰的函数定义之前调用。
property 装饰器(getter)
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
setter 装饰器
用于设置属性 'name'。
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
deleter 装饰器
用于删除属性 'name'。
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.deleter
def name(self):
del self._name
更多建议: