04 - 控制流:if/for/while

想系统提升编程能力、查看更完整的学习路线,欢迎访问 AI Compass:https://github.com/tingaicompass/AI-Compass

仓库持续更新刷题题解、Python 基础和 AI 实战内容,适合想高效进阶的你。

04 - 控制流:if/for/while

学习目标: 掌握条件判断和循环


💻 代码示例

1. if条件判断

python 复制代码
x = 10

# 基本if
if x > 5:
    print("x大于5")

# if-else
if x > 15:
    print("x大于15")
else:
    print("x不大于15")

# if-elif-else
if x > 15:
    print("大")
elif x > 5:
    print("中")  # 输出这个
else:
    print("小")

# ⚠️ Python用缩进表示代码块,不用{}

2. for循环

python 复制代码
# 遍历列表
nums = [1, 2, 3, 4, 5]
for num in nums:
    print(num)

# range循环
for i in range(5):  # 0, 1, 2, 3, 4
    print(i)

# enumerate获取索引
for i, num in enumerate(nums):
    print(f"索引{i}: {num}")

# 遍历字典
scores = {"Alice": 90, "Bob": 85}
for name, score in scores.items():
    print(f"{name}: {score}")

# 嵌套循环
for i in range(3):
    for j in range(3):
        print(f"({i}, {j})", end=" ")
    print()

3. while循环

python 复制代码
# 基本while
count = 0
while count < 5:
    print(count)
    count += 1

# 链表遍历(常用模式)
current = head
while current:
    print(current.val)
    current = current.next

# 双指针
left, right = 0, len(nums) - 1
while left < right:
    # 处理逻辑
    left += 1
    right -= 1

4. break和continue

python 复制代码
# break:跳出循环
for i in range(10):
    if i == 5:
        break  # 循环到5就停止
    print(i)  # 0 1 2 3 4

# continue:跳过本次循环
for i in range(10):
    if i % 2 == 0:
        continue  # 跳过偶数
    print(i)  # 1 3 5 7 9

# 查找元素
nums = [1, 5, 3, 8, 2]
target = 8
found = False
for num in nums:
    if num == target:
        found = True
        break
if found:
    print("找到了")

5. pass:占位符

python 复制代码
# pass表示"什么都不做"
if x > 0:
    pass  # TODO: 以后实现
else:
    print("负数")

# 空函数
def todo():
    pass

# 空类
class MyClass:
    pass

🎯 在算法题中的应用

python 复制代码
# 第7课:移动零 - for + if
def moveZeroes(nums):
    slow = 0
    for fast in range(len(nums)):
        if nums[fast] != 0:
            nums[slow], nums[fast] = nums[fast], nums[slow]
            slow += 1

# 第24课:反转链表 - while
def reverseList(head):
    prev = None
    curr = head
    while curr:
        next_temp = curr.next
        curr.next = prev
        prev = curr
        curr = next_temp
    return prev

# 第9课:三数之和 - 嵌套循环 + 双指针
def threeSum(nums):
    nums.sort()
    result = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i-1]:
            continue  # 跳过重复
        left, right = i + 1, len(nums) - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total == 0:
                result.append([nums[i], nums[left], nums[right]])
                left += 1
                right -= 1
            elif total < 0:
                left += 1
            else:
                right -= 1
    return result

🏋️ 快速练习

练习1:找出1-100中的质数

点击查看答案

python 复制代码
for num in range(2, 101):
    is_prime = True
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            is_prime = False
            break
    if is_prime:
        print(num, end=" ")

🎓 小结

if-elif-else 条件判断

for x in iterable 遍历

while condition 条件循环

break 跳出循环

continue 跳过本次

pass 占位符

常用模式:

python 复制代码
# 遍历数组
for i in range(len(nums)):
    ...

# 遍历索引和值
for i, val in enumerate(nums):
    ...

# 双指针
while left < right:
    ...

下一步 : 05-函数基础.md


如果这篇内容对你有帮助,推荐收藏 AI Compass:https://github.com/tingaicompass/AI-Compass

更多系统化题解、编程基础和 AI 学习资料都在这里,后续复习和拓展会更省时间。

相关推荐
努力学习的小廉2 小时前
我爱学算法之——动态规划(四)
算法·动态规划
北顾笙9802 小时前
day15-数据结构力扣
数据结构·算法·leetcode
AI成长日志3 小时前
【GitHub开源项目专栏】黑客松项目架构模式解析:微服务、事件驱动与Serverless实战
算法
人道领域3 小时前
【LeetCode刷题日记:24】两两交换链表
算法·leetcode·链表
北顾笙9803 小时前
day16-数据结构力扣
数据结构·算法·leetcode
AI成长日志3 小时前
【算法学习专栏】动态规划基础·简单三题精讲(70.爬楼梯、118.杨辉三角、121.买卖股票的最佳时机)
学习·算法·动态规划
wsoz3 小时前
Leetcode子串-day4
c++·算法·leetcode
汀、人工智能3 小时前
[特殊字符] 第27课:环形链表II
数据结构·算法·链表·数据库架构··环形链表ii
会编程的土豆3 小时前
【数据结构与算法】二叉树大总结
数据结构·算法·leetcode