温馨提示:本文最后更新于
2025-06-09 11:59:46
,某些文章具有时效性,若有错误或已失效,请在下方留言。变量的定义
# 定义变量
name = "Alice"
age = 30
# 使用变量
print("Name:", name)
print("Age:", age)
# 修改变量
name = "Bob"
age = 25
# 使用修改后的变量
print("Updated Name:", name)
print("Updated Age:", age)
# 将名字与年龄打印出来,并在一行
print("Name:", name, "Age:", age)
# 将名字与年龄打印出来,并在一行
# 打印格式为:名字: Alice, 年龄: 30
# 不要使用 f-string
print("名字:", name, ", 年龄:", age)
# 定义几个变量,用于加法运算
a = 5
b = 10
# 进行加法运算
sum_result = a + b
# 打印加法结果
print("Sum of", a, "and", b, "is:", sum_result)
注:使用AI插件的时候,一定要把注释写清楚
逻辑判断优先级
逻辑判断优先级,如下表所示
序号 | 逻辑运算符 | 备注 |
---|---|---|
1 |
* 、/ 、// 、%
|
同等优先级,前边的优先级高。// 代表的是整除
|
2 |
+ 、-
| |
3 |
<< 、>>
| 位的左移、右移 |
4 |
&
| 按位与 |
5 |
^
| 按异或 |
6 |
|
| 按位或 |
7 |
== 、!= 、< 、<= 、> 、>=
| |
8 |
not
| 逻辑非 |
9 |
and
| 逻辑与 |
10 |
or
| 逻辑或 |
优先级顺序由1
-> 10
,依次降低。
# 先计算 2 & 1,然后再计算 4 | 结果
4 | 2 & 1 = 4
# 先计算 1 << 3,再计算 4 | 结果
4 | 1 << 3 = 12
逻辑判断语法
if xxx:
# 代码逻辑
elif xxx:
# 代码逻辑
else:
# 代码逻辑
代码实例
if 4>5:
print("4 is greater than 5")
elif 4<5:
print("4 is less than 5")
else:
print("4 is equal to 5")
# 4 is less than 5
循环
for 循环
# 数组的for循环
for idx in [1, 2, 3]:
...
# 连续空间for循环
for idx in range(1, 10):
...
代码示例
# for 循环
# 数组
for i in [1, 2, 3, 4, 5]:
print(i)
for i in ["a", "b", "c"]:
print(i)
# for 循环的 range 函数
for i in range(5):
print(i)
# 打印结果 为 0 到 4
# for 循环的 range 函数,指定起始和结束值
for i in range(2, 6):
print(i)
# 打印结果 为 2 到 5
# for 循环的 range 函数,指定起始、结束值和步长
for i in range(1, 10, 2):
print(i)
# 打印结果 为 1, 3, 5, 7, 9
while 循环
# while 循环基本语法
while True:
...
代码示例
# while 循环的基本语法
i = 0
while i < 5:
print(i)
i += 1 # 增加 i 的值,避免死循环
# 打印结果为 0, 1, 2, 3, 4
函数
# 函数定义
def func():
# 函数体
...
# 函数调用
func()
代码示例
# func
# 无参函数的定义和调用
def func():
print("无参函数被调用")
# 调用无参函数
func()
# 打印结果:
# 无参函数被调用
# 有参函数的定义和调用
def greet(name):
print("Hello,", name)
# 调用有参函数
greet("Alice")
# 打印结果:
# Hello, Alice
# 有多个参数的函数定义和调用
def add(a, b):
return a + b
# 调用有多个参数的函数
result = add(5, 10)
print("Sum of 5 and 10 is:", result)
# 打印结果:
# Sum of 5 and 10 is: 15
# 函数返回值的使用
def multiply(a, b):
return a * b
# 调用函数并使用返回值
result = multiply(3, 4)
print("Product of 3 and 4 is:", result)
# 打印结果:
# Product of 3 and 4 is: 12
# 函数返回值为多个值
def divide_and_remainder(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder
# 调用函数并使用返回的多个值
quotient, remainder = divide_and_remainder(10, 3)
print("Quotient:", quotient, "Remainder:", remainder)
# 打印结果:
# Quotient: 3 Remainder: 1
# 函数的默认参数
def greet_with_default(name="World"):
print("Hello,", name)
# 调用函数,使用默认参数
greet_with_default()
# 打印结果:
# Hello, World
# 调用函数,传入自定义参数
greet_with_default("Alice")
# 打印结果:
# Hello, Alice
# 函数的可变参数
def variable_args(*args):
for arg in args:
print("Argument:", arg)
# 调用函数,传入多个参数
variable_args("one", "two", "three")
# 打印结果:
# Argument: one
# Argument: two
# Argument: three
类与对象
基本使用
类的方法参数中,self
是必须要传入的。
# 定义一个类 Person,包含两个属性 name 和 age
class Person:
name = ""
age = 0
# 定义构造函数 __init__,用于初始化 name 和 age 属性, self 是类的当前对象
def __init__(self, name: str, age: int):
self.name = name
self.age = age
# 定义一个方法 say,用于打印 name 和 age 属性
def say(self):
print("%s 说:我今年 %d 岁" % (self.name, self.age))
# 创建一个 Person 类的实例
person = Person("Alice", 30)
# 调用 say 方法,打印 name 和 age 属性
person.say()
# 打印结果:Alice 说:我今年 30 岁
# 修改 person 的 name 和 age 属性
person.name = "Bob"
person.age = 25
# 再次调用 say 方法,打印修改后的 name 和 age 属性
person.say()
# 打印结果:Bob 说:我今年 25 岁
类的继承
# 定义一个类 Student,继承自 Person 类
class Student(Person):
# 定义构造函数 __init__,用于初始化 name、age 和 student_id 属性
def __init__(self, name: str, age: int, student_id: str):
super().__init__(name, age) # 调用父类的构造函数
self.student_id = student_id
# 定义一个方法 say,用于打印 name、age 和 student_id 属性
def say(self):
print("%s 说:我今年 %d 岁,学号是 %s" % (self.name, self.age, self.student_id))
# 创建一个 Student 类的实例
student = Student("Charlie", 20, "S12345")
# 调用 say 方法,打印 name、age 和 student_id 属性
student.say()
# 打印结果:Charlie 说:我今年 20 岁,学号是 S12345
复合类型
Python中常见的复合类型
- 列表:
[1,2,3,[4,5]]
- 元组:
(1, 3, 4, 3)
- 集合:
{1, 3, 4, 3}
- 字典:
{"1": "abc", "2": "899"}
,Key
值必须为字符串。
列表
# 创建列表
list1 = [1, 2, 3, 4, 5]
# 打印列表
print("List1:", list1)
# 打印结果
# List1: [1, 2, 3, 4, 5]
# 访问列表元素
print("First element of List1:", list1[0]) # 访问第一个元素
print("Last element of List1:", list1[-1]) # 访问最后一个元素
# 打印结果
# First element of List1: 1
# Last element of List1: 5
# 修改列表元素
list1[0] = 10 # 修改第一个元素
print("Modified List1:", list1)
# 打印结果
# Modified List1: [10, 2, 3, 4, 5]
# 添加元素到列表
list1.append(6) # 在列表末尾添加元素
print("List1 after appending 6:", list1)
# 打印结果
# List1 after appending 6: [10, 2, 3, 4, 5, 6]
# 在指定位置插入元素
list1.insert(2, 15) # 在索引2的位置插入元素15
print("List1 after inserting 15 at index 2:", list1)
# 打印结果
# List1 after inserting 15 at index 2: [10, 2, 15, 3, 4, 5, 6]
# 删除列表元素
list1.remove(3) # 删除元素3
print("List1 after removing 3:", list1)
# 打印结果
# List1 after removing 3: [10, 2, 15, 4, 5, 6]
# 删除指定索引的元素
del list1[1] # 删除索引1的元素
print("List1 after deleting element at index 1:", list1)
# 打印结果
# List1 after deleting element at index 1: [10, 15, 4, 5, 6]
# 弹出列表的最后一个元素
popped_element = list1.pop() # 弹出最后一个元素
print("Popped element:", popped_element)
print("List1 after popping last element:", list1)
# 打印结果
# Popped element: 6
# List1 after popping last element: [10, 15, 4, 5]
# 获取列表的长度
list_length = len(list1) # 获取列表长度
print("Length of List1:", list_length)
# 打印结果
# Length of List1: 4
# 列表的遍历
for index, value in enumerate(list1):
print(f"Element at index {index}: {value}")
# 打印结果
# Element at index 0: 10
# Element at index 1: 15
# Element at index 2: 4
# Element at index 3: 5
# 列表的切片
slicing = list1[1:4] # 获取索引1到3的元素
print("Sliced List1 (from index 1 to 3):", slicing)
# 打印结果
# Sliced List1 (from index 1 to 3): [15, 4, 5]
# 列表的排序
list1.sort() # 对列表进行排序
print("Sorted List1:", list1)
# 打印结果
# Sorted List1: [4, 5, 10, 15]
# 列表的反转
list1.reverse() # 反转列表
print("Reversed List1:", list1)
# 打印结果
# Reversed List1: [15, 10, 5, 4]
# 列表的连接
list2 = [7, 8, 9]
# 连接两个列表
list_combined = list1 + list2
print("Combined List1 and List2:", list_combined)
# 打印结果
# Combined List1 and List2: [15, 10, 5, 4, 7, 8, 9]
# 列表的复制
list_copy = list1.copy() # 复制列表
print("Copied List1:", list_copy)
# 打印结果
# Copied List1: [15, 10, 5, 4]
# 列表的清空
list1.clear() # 清空列表
print("List1 after clearing:", list1)
# 打印结果
# List1 after clearing: []
元组
# 元组的定义
t = (1, 2, 3, 4, 5)
# 元组的访问
print("第一个元素:", t[0]) # 访问第一个元素
print("最后一个元素:", t[-1]) # 访问最后一个元素
# 打印结果:
# 第一个元素: 1
# 最后一个元素: 5
# 切片访问
print("切片:", t[1:4]) # 访问从索引1到索引3的元素
# 打印结果:
# 切片: (2, 3, 4)
# 元组的遍历
for item in t:
print("遍历元素:", item)
# 打印结果:
# 遍历元素: 1
# 遍历元素: 2
# 遍历元素: 3
# 遍历元素: 4
# 遍历元素: 5
# 元组的长度
print("元组的长度:", len(t)) # 获取元组的长度
# 打印结果:
# 元组的长度: 5
# 元组的连接
t2 = (6, 7, 8)
t3 = t + t2 # 连接两个元组
print("连接后的元组:", t3) # 打印连接后的元组
# 打印结果:
# 连接后的元组: (1, 2, 3, 4, 5, 6, 7, 8)
# 元组的重复
t4 = t * 2 # 重复元组
print("重复后的元组:", t4) # 打印重复后的元组
# 打印结果:
# 重复后的元组: (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
# 元组的成员检查
print("是否包含3:", 3 in t) # 检查元素是否在元组中
# 打印结果:
# 是否包含3: True
# 元组的不可变性
# 尝试修改元组中的元素会引发错误
try:
t[0] = 10 # 尝试修改元组的第一个元素
except TypeError as e:
print("错误:", e)
# 打印结果:
# 错误: 'tuple' object does not support item assignment
# 元组的嵌套
nested_tuple = (1, (2, 3), (4, 5, 6)) # 定义嵌套元组
print("嵌套元组:", nested_tuple) # 打印嵌套元组
# 打印结果:
# 嵌套元组: (1, (2, 3), (4, 5, 6))
# 元组的解包
a, b, c = t[:3] # 解包元组的前3个元素
print("解包后的值:", a, b, c) # 打印解包后的值
# 打印结果:
# 解包后的值: 1 2 3
集合
# 集合的创建
# 使用大括号创建集合
s = {1, 2, 3, 4, 5}
# 使用 set() 函数创建集合
s2 = set([1, 2, 3, 4, 5])
# 集合的基本操作
# 添加元素
s.add(6) # 添加单个元素
s2.update([6, 7]) # 添加多个元素
print(s) # {1, 2, 3, 4, 5, 6}
print(s2) # {1, 2, 3, 4, 5, 6, 7}
# 删除元素
s.remove(1) # 删除单个元素,如果元素不存在会抛出异常
print(s) # {2, 3, 4, 5, 6}
s2.discard(2) # 删除单个元素,如果元素不存在不会抛出异常
print(s2) # {1, 3, 4, 5, 6, 7}
# 集合的遍历
for item in s2:
print(item)
# 打印结果
# 1
# 3
# 4
# 5
# 6
# 集合的长度
print(len(s)) # 输出集合 s 的长度 5
print(len(s2)) # 输出集合 s2 的长度 6
# 清空集合
s.clear() # 清空集合
print(s) # set()
s2.clear() # 清空集合
print(s2) # set()
字典
# 创建字典
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# 解包字典
# 解包字典中的键值对
name, age, city = my_dict["name"], my_dict["age"], my_dict["city"]
print(f"Name: {name}, Age: {age}, City: {city}")
# 打印结果:Name: Alice, Age: 30, City: New York
# 添加键值对
my_dict["job"] = "Engineer"
print(my_dict)
# 打印结果:{'name': 'Alice', 'age': 30, 'city': 'New York', 'job': 'Engineer'}
# 修改键值对
my_dict["age"] = 31
print(my_dict)
# 打印结果:{'name': 'Alice', 'age': 31, 'city': 'New York', 'job': 'Engineer'}
# 访问字典中的值
print(my_dict["name"])
# 打印结果:Alice
# 检查键是否存在
if "city" in my_dict:
print("City exists in the dictionary")
# 打印结果:City exists in the dictionary
# 删除键值对
del my_dict["job"]
print(my_dict)
# 打印结果:{'name': 'Alice', 'age': 31, 'city': 'New York'}
# 遍历字典
for key, value in my_dict.items():
print(f"{key}: {value}")
# 打印结果:
# name: Alice
# age: 31
# city: New York
# 字典的键和值
# 获取所有键
keys = my_dict.keys()
print("Keys:", keys)
# 打印结果:
# Keys: dict_keys(['name', 'age', 'city'])
# 获取所有值
values = my_dict.values()
print("Values:", values)
# 打印结果:
# Values: dict_values(['Alice', 31, 'New York'])
# 获取键值对
items = my_dict.items()
print("Items:", items)
# 打印结果:
# Items: dict_items([('name', 'Alice'), ('age', 31), ('city', 'New York')])
# 字典的删除
# 删除字典中的一个键值对
del my_dict["age"]
print("Dictionary after deletion:", my_dict)
# 打印结果:
# Dictionary after deletion: {'name': 'Alice', 'city': 'New York'}
# 删除字典中的所有键值对
my_dict.clear()
print("Dictionary after clear:", my_dict)
# 打印结果:Dictionary after clear: {}
可变变量与不可变变量
可变变量
常见的可变变量:列表
、字典
、集合
# 可变变量的例子
list1 = [1, 2, 3]
list2 = list1 # 引用同一个列表
list2[0] = 100 # 修改 list2 的第一个元素
print("list1:", list1) # 输出: list1: [100, 2, 3]
print("list2:", list2) # 输出: list2: [100, 2, 3]
不可变变量
常见的不可变变量:字符串
、元组
、整数
、浮点数
以及布尔
。
# 不可变变量的例子
str1 = "Hello"
str2 = str1 # 引用同一个字符串
str2 = str2.replace("H", "J") # 修改 str2 的内容
print("str1:", str1) # 输出: str1: Hello
print("str2:", str2) # 输出: str2: Jello
特殊操作
切片
list[起始索引:结束索引:步长]
,不包括结束索引的元素
# 定义列表
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 切片操作
# list[起始索引:结束索引:步长],不包括结束索引的元素
# 从第2个元素到第8个元素,不包括第8个元素
sliced_list = my_list[1:8] # 注意索引从0开始
print("Sliced List (1:8):", sliced_list)
# 打印结果:
# Sliced List (1:8): [2, 3, 4, 5, 6, 7, 8]
# 从第2个元素到第8个元素,不包括第8个元素,步长为2
sliced_list_step = my_list[1:8:2] # 注意索引从0开始
print("Sliced List (1:8:2):", sliced_list_step)
# 打印结果:
# Sliced List (1:8:2): [2, 4, 6, 8]
# 从开始位置到结束位置
sliced_list_full = my_list[:] # 复制整个列表
print("Sliced List Full:", sliced_list_full)
# 打印结果:
# Sliced List Full: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 从开始位置到第5个元素,不包括第5个元素
sliced_list_start = my_list[:4] # 注意索引从0开始
print("Sliced List (:4):", sliced_list_start)
# 打印结果:
# Sliced List (:4): [1, 2, 3, 4]
# 从第5个元素到结束位置
sliced_list_end = my_list[4:] # 注意索引从0开始
print("Sliced List (4:):", sliced_list_end)
# 打印结果:
# Sliced List (4:): [5, 6, 7, 8, 9]
# 整个列表反转
sliced_list_reverse = my_list[::-1] # 逆序切片
print("Sliced List Reverse:", sliced_list_reverse)
# 打印结果:
# Sliced List Reverse: [9, 8, 7, 6, 5, 4, 3, 2, 1]
# 从第8个元素到第2个元素,步长为-1(逆序)
sliced_list_reverse_full = my_list[8:1:-1] # 注意索引从0开始
print("Sliced List (8:1:-1):", sliced_list_reverse_full)
# 打印结果:
# Sliced List (8:1:-1): [9, 8, 7, 6, 5, 4, 3, 2]
列表推导
# 列表推导
list = [i**2 for i in range(10)]
print(list)
# 打印结果:
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 列表推导的条件
list = [i**2 for i in range(10) if i % 2 == 0]
print(list)
# 打印结果:
# [0, 4, 16, 36, 64]
# 列表推导的嵌套
list = [i * j for i in range(3) for j in range(3)]
print(list)
# 打印结果:
# [0, 0, 0, 0, 1, 2, 0, 2, 4, 0, 3, 6]
# 列表推导的嵌套和条件
list = [i * j for i in range(3) for j in range(3) if i != j]
print(list)
# 打印结果:
# [1, 2, 0, 2, 4, 0, 3, 6]
with 语句
使用with
语句对文件操作, 文件的打开和关闭由with语句自动管理
# 使用with语句打开文件
with open('test.txt', 'w') as f:
# 写入内容到文件
f.write("Hello, World!\n")
f.write("This is a test file.\n")
# 读取文件内容
with open('test.txt', 'r') as f:
content = f.read()
print("File content:")
print(content)
解包
使用*
运算符解包
# 函数解包
def func(a, b, c):
print(a, b, c)
# 定义一个列表
my_list = [1, 2, 3]
# 使用 * 运算符解包列表
func(*my_list) # 输出: 1 2 3
© 版权声明
THE END
暂无评论内容