# GESP等级：三级 | GESP Python 三级考点

"""
第4节：列表切片 [start:stop:step]
===============================
演示6种切片用法 + turtle画半边彩虹
记忆钩子：切片=切蛋糕 [start:stop:step] 含头不含尾
"""

import turtle

# ============================================================
# 一、切片基础 —— 6种核心用法
# ============================================================
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
# 索引:    0       1        2        3       4       5

print("=" * 40)
print("原始列表 colors =", colors)
print("=" * 40)

# ① list[0:3] —— 前三个（含头不含尾）
print("\n① colors[0:3] =", colors[0:3])   # → ['red', 'orange', 'yellow']

# ② list[2:] —— 从索引2到最后
print("② colors[2:]  =", colors[2:])     # → ['yellow', 'green', 'blue', 'purple']

# ③ list[:4] —— 前四个
print("③ colors[:4]  =", colors[:4])     # → ['red', 'orange', 'yellow', 'green']

# ④ list[-3:] —— 后三个
print("④ colors[-3:] =", colors[-3:])    # → ['green', 'blue', 'purple']

# ⑤ list[::2] —— 隔一个取一个
print("⑤ colors[::2] =", colors[::2])    # → ['red', 'yellow', 'blue']

# ⑥ 切片创造新列表（不修改原列表）
sliced = colors[0:3]
print("\n⑥ 切片创造新列表（不修改原列表）")
print("   原列表 colors =", colors)
print("   切片 sliced = colors[0:3] =", sliced)
sliced[0] = "BLACK"  # 修改切片
print("   改切片 sliced[0]='BLACK'后：")
print("   切片 sliced =", sliced)
print("   原列表 colors =", colors)       # 原列表不变！
print("   → 切片是复制品，改切片不影响原列表！")

# ============================================================
# 二、演示：用切片取一半颜色画图
# ============================================================
print("\n" + "=" * 40)
print("二、turtle 演示：切片取一半颜色画彩虹")
print("=" * 40)

t = turtle.Turtle()
t.shape("turtle")
t.speed(6)

# 取前一半颜色 colors[:3] （含头不含尾：索引0,1,2）
half_colors = colors[:3]   # → ['red', 'orange', 'yellow']
print("取前一半颜色 half_colors =", half_colors)

# 用前一半颜色画半圆彩虹
t.penup()
t.goto(-200, 0)
t.pendown()
t.pensize(20)

for c in half_colors:
    t.color(c)
    t.forward(200)
    t.penup()
    t.goto(-200, t.ycor() - 40)  # 向下移动
    t.pendown()

t.penup()
t.goto(0, 0)
t.color("black")
t.write("前半段彩虹: colors[:3]", align="center", font=("Arial", 14, "normal"))

# 再演示：用切片取后一半颜色画图
t.penup()
t.goto(100, 0)
t.pendown()

back_half = colors[-3:]   # → ['green', 'blue', 'purple']
print("取后一半颜色 back_half =", back_half)

for c in back_half:
    t.color(c)
    t.forward(200)
    t.penup()
    t.goto(100, t.ycor() - 40)
    t.pendown()

t.penup()
t.goto(200, 0)
t.color("black")
t.write("后半段彩虹: colors[-3:]", align="center", font=("Arial", 14, "normal"))

t.penup()
t.goto(0, -200)
t.color("purple")
t.write("切片 = 切蛋糕 [start:stop:step]  含头不含尾",
        align="center", font=("Arial", 16, "bold"))

t.hideturtle()
turtle.done()
