Python 教程

从零开始,循序渐进掌握 Python 编程

1

Python 基础

变量、数据类型、基本运算

变量与赋值

变量是存储数据的容器。Python 中不需要声明变量类型。

# 变量赋值
name = "字母战争"
score = 100
is_active = True

数据类型

Python 有多种内置数据类型:字符串、数字、布尔值等。

# 数据类型
text = "Hello"      # 字符串
number = 42         # 整数
pi = 3.14           # 浮点数
flag = True         # 布尔值

基本运算

Python 支持算术运算、比较运算和逻辑运算。

# 算术运算
sum = 10 + 5        # 15
diff = 10 - 5       # 5
product = 10 * 5    # 50

字符串操作

字符串是文本数据,可以进行拼接、重复等操作。

# 字符串操作
greeting = "Hello, " + "World"
repeated = "Ha" * 3   # "HaHaHa"
length = len(text)    # 字符串长度
2

控制流程

条件语句、循环结构

if 条件语句

根据条件执行不同的代码块。

if score > 100:
    print("优秀!")
elif score > 60:
    print("及格")
else:
    print("继续努力")

while 循环

当条件为真时重复执行代码块。

while hero.coins < 10:
    coin = find_nearest_coin()
    hero.move_to(coin.x, coin.y)

for 循环

遍历序列中的每个元素。

# 遍历列表
for coin in coins:
    hero.move_to(coin.x, coin.y)

# 指定范围
for i in range(5):
    hero.jump()

break 和 continue

控制循环的执行流程。

for enemy in enemies:
    if enemy.is_friendly:
        continue    # 跳过
    if enemy.distance < 10:
        break       # 退出循环
    hero.attack(enemy)
3

函数与模块

函数定义、参数、返回值

定义函数

函数是可重用的代码块,用于组织代码。

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

message = greet("Player")
print(message)  # Hello, Player

参数与返回值

函数可以接收参数并返回结果。

def calculate_distance(x1, y1, x2, y2):
    dx = x2 - x1
    dy = y2 - y1
    return (dx**2 + dy**2)**0.5

dist = calculate_distance(0, 0, 3, 4)
# dist = 5.0

默认参数

函数参数可以有默认值。

def move(direction, distance=100):
    if direction == "right":
        hero.move_right(distance)
    elif direction == "left":
        hero.move_left(distance)

move("right")      # 移动 100
move("left", 50)   # 移动 50

列表操作

列表是 Python 中常用的数据结构。

# 创建列表
coins = [10, 20, 30, 40, 50]

# 访问元素
first = coins[0]      # 10
last = coins[-1]      # 50

# 切片
subset = coins[1:3]   # [20, 30]

# 长度
count = len(coins)    # 5
4

进阶主题

类、对象、算法入门

类与对象

面向对象编程的基础概念。

class Hero:
    def __init__(self, name):
        self.name = name
        self.health = 100

    def move(self, distance):
        # 移动逻辑
        pass

hero = Hero("Player")
hero.move(100)

字典

键值对存储的数据结构。

# 创建字典
player = {
    "name": "Hero",
    "level": 5,
    "coins": 100
}

# 访问值
name = player["name"]
player["coins"] += 50

异常处理

优雅地处理错误情况。

try:
    result = 10 / 0
except ZeroDivisionError:
    print("不能除以零!")
except Exception as e:
    print(f"发生错误: {e}")
finally:
    print("执行完毕")

列表推导式

简洁的列表创建方式。

# 传统方式
squares = []
for i in range(5):
    squares.append(i**2)

# 列表推导式
squares = [i**2 for i in range(5)]
# [0, 1, 4, 9, 16]

准备好开始练习了吗?

在互动练习场中实践你学到的知识,通过完成关卡来巩固编程技能。

前往练习场