Python基本语法速览

基本类型和变量赋值

x = 10
y = 3.14
name = "Alice"
other_name = 'Alibe'
is_active = True
is_not_active = False
n = None

数据结构

# 列表(List) - 可变
lst = [1, 2, 3]
empty = []
nested = [[1, 2], [3, 4]]

lst[0]      # 第一个元素
lst[-1]     # 最后一个元素
lst[1:3]    # 切片,取索引1和2的元素,第一个是开始坐标,第二个是终止坐标,但不包含

lst[0] = 100

lst.append(4)        # 末尾添加一个元素
lst.insert(1, 999)   # 在索引1处插入元素
lst.extend([5, 6])   # 批量添加多个元素(拼接)


lst.append(4)

del lst[0]           # 删除指定索引元素
lst.pop()            # 弹出并返回最后一个元素
lst.pop(1)           # 弹出索引1的元素
lst.remove(3)        # 删除值为3的第一个元素
lst.clear()          # 清空整个列表

lst.index(2)         # 查找值为2的索引(找不到会报错)
2 in lst             # 判断某值是否存在
lst.count(2)         # 某个值出现的次数

lst.sort()               # 原地升序排序
lst.sort(reverse=True)   # 降序排序
sorted(lst)              # 返回排序后的新列表

lst.reverse()            # 原地反转
reversed(lst)            # 返回一个反转的迭代器

copy1 = lst[:]               # 切片复制
copy2 = lst.copy()           # 调用copy方法
copy3 = list(lst)            # 转换复制

for item in lst:
    print(item)

# 带索引
for i, item in enumerate(lst):
    print(i, item)

squares = [x**2 for x in range(5)]             # [0, 1, 4, 9, 16]
even = [x for x in lst if x % 2 == 0]          # 条件过滤



# 元组(Tuple) - 不可变
tpl = (1, 2, 3)

# 集合(Set) - 无序不重复
s = {1, 2, 3}
s.add(4)

# 字典(Dict) - key-value 对
d = {"name": "Alice", "age": 25}
d["age"] = 26

条件判断

if x > 0:
    print("Positive")
elif x == 0:
    print("Zero")
else:
    print("Negative")

循环

# for loop
for i in range(5):  # 0~4
    print(i)

# while loop
i = 0
while i < 5:
    print(i)
    i += 1

函数定义

def greet(name):
    return "Hello, " + name

print(greet("Bob"))

异常处理

try:
    result = 10 / 0
except ZeroDivisionError:
    print("除以0错误")
finally:
    print("完成")

类和对象

class Person:
    def __init__(self, name):
        self.name = name

    def say_hello(self):
        print("Hello, my name is", self.name)

p = Person("Alice")
p.say_hello()

列表推导式

squares = [x**2 for x in range(5)]  # [0, 1, 4, 9, 16]

常用内置函数

len(lst)
type(x)
int("123")
str(456)
sorted([3, 1, 2])
sum([1, 2, 3])

Scroll to Top