本文为 Python 60 Days Challenge 课程学习整理,原作者与原 Notebook 链接见「课程资料」。代码按章节顺序运行;语法示意和故意报错的反例已单独标注。

打卡任务

  • 阅读本节讲义或 Notebook
  • 跑通示例代码
  • 整理 3 个关键点
  • 完成当日打卡输出

课程资料

学习内容

列表的基础操作

# 1. 创建包含三个字符串的列表
tech_list = ["Python", "Java", "Go"]

# 2. 获取第一个元素
first_tech = tech_list[0]

# 3. 向列表末尾添加新元素
tech_list.append("JavaScript")

# 4. 修改第二个元素
tech_list[1] = "Ruby"

# 5. 移除元素"Go"
tech_list.remove("Go")

# 6. 计算列表当前长度
current_length = len(tech_list)

# 7. 使用f-string打印结果
print(f"第一个技术是: {first_tech}")
print(f"当前列表长度: {current_length}")
print(f"最终列表内容: {tech_list}")

循环语句

讲解一下debugger的操作

# 初始化总和变量
total = 0

# 使用for循环累加1到100
for num in range(1, 101):  # range(1,101)表示从1到100(包含100)
    total += num
    # total = total + num
# 打印结果
print(f"1到100的和是: {total}")

​range() 是 Python 内置函数,用于生成一个整数序列,常用于 for 循环中控制循环次数。

基本语法:

以下是语法示意或故意报错的反例,不是需要整段运行的正常程序。

range(stop)              # 从 0 开始到 stop-1
range(start, stop)       # 从 start 开始到 stop-1
range(start, stop, step) # 从 start 开始,步长为 step,到 stop-1

参数说明:

  • ​start: 起始数字(包含),默认为 0
  • ​stop: 结束数字(不包含,这很重要!)
  • ​step: 步长,默认为 1,可以是负数

常见用法示例:

代码 生成序列 说明
​range(5) 0, 1, 2, 3, 4 从 0 到 4
​range(1, 5) 1, 2, 3, 4 从 1 到 4
​range(1, 101) 1, 2, ..., 100 从 1 到 100 ✓ 本题使用
​range(0, 10, 2) 0, 2, 4, 6, 8 每次增加 2
​range(10, 0, -1) 10, 9, 8, ..., 1 倒序递减

range()用来生成数字序列,for可以取出来这个序列。我们把这种可以被for循环取出来的叫做可迭代对象。

实际上列表和字符串也是可迭代序列

for char in "Python":  # 逐个取出每个字符
    print(char)  # P, y, t, h, o, n
for tech in tech_list:  # 逐个取出每个元素
    print(tech)  # 打印每个技术名称

判断语句

score = 85

if score >= 90:
    print("优秀")
else:
    print("不优秀")
temperature = 25  # 可以修改这个值测试不同情况

if temperature > 35:
    print("红色预警:高温天气!")
elif temperature >= 28:
    print("黄色预警:天气炎热")
elif temperature >= 20:
    print("绿色提示:适宜温度")
else:
    print("蓝色预警:注意保暖")

题目答案

# 1. 定义分数列表
scores = [85, 92, 78, 65, 95, 88]

# 2. 初始化变量
excellent_count = 0
total_score = 0

# 3. 遍历列表并计算
for score in scores:
    total_score += score  # 4a. 累加总分
    if score >= 90:      # 4b. 统计优秀分数
        excellent_count += 1

# 5. 计算平均分
average_score = total_score / len(scores)

# 6. 打印结果
print(f"优秀分数个数: {excellent_count}")
print(f"分数总和: {total_score}")
print(f"平均分数: {average_score:.3f}")