第4天:循环结构和列表

学习目标

  • 掌握Python中的循环结构,包括for循环和while循环
  • 理解列表的基本操作和方法
  • 学会使用循环遍历列表
学习内容
1. 循环结构

循环结构用于重复执行代码块,直到满足某个条件。Python中有两种主要的循环结构:for循环和while循环。

for循环

for循环用于遍历序列(如列表、字符串、元组等)。

  • 基本语法:

for element in sequence:
    # 对element进行操作
  • 示例:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
while循环

while循环在条件为True时重复执行代码块。

  • 基本语法:

while condition:
    # 执行代码块
  • 示例:

count = 0
while count < 5:
    print(count)
    count += 1
2. 列表

列表是Python中最常用的数据结构之一,用于存储一系列元素。列表是可变的,可以包含不同类型的元素。

  • 定义列表:

my_list = [1, 2, 3, "apple", True]
  • 列表操作:

    • 访问元素:my_list[index]
    • 修改元素:my_list[index] = new_value
    • 添加元素:my_list.append(element)
    • 删除元素:del my_list[index]my_list.remove(element)
    • 列表长度:len(my_list)
  • 示例:

my_list = [10, 20, 30, 40, 50]

# 访问元素
print(my_list[0])  # 10

# 修改元素
my_list[1] = 25
print(my_list)  # [10, 25, 30, 40, 50]

# 添加元素
my_list.append(60)
print(my_list)  # [10, 25, 30, 40, 50, 60]

# 删除元素
del my_list[2]
print(my_list)  # [10, 25, 40, 50, 60]
3. 使用循环遍历列表
  • for循环遍历列表:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
  • while循环遍历列表:

fruits = ["apple", "banana", "cherry"]
index = 0
while index < len(fruits):
    print(fruits[index])
    index += 1
今日任务
  1. 练习for循环和while循环:

    • 使用for循环和while循环分别打印从1到10的数字。
    • 计算1到100的和。
  2. 操作列表:

    • 创建一个列表,包含一些元素。
    • 练习列表的基本操作:访问、修改、添加、删除元素。
    • 使用for循环和while循环遍历列表,并打印每个元素。
  3. 编写并运行以下示例代码:

# for循环示例
print("for循环示例")
for i in range(1, 11):
    print(i)

# while循环示例
print("while循环示例")
count = 1
while count <= 10:
    print(count)
    count += 1

# 计算1到100的和
print("计算1到100的和")
total = 0
for i in range(1, 101):
    total += i
print(total)

# 列表操作示例
print("列表操作示例")
my_list = [10, 20, 30, 40, 50]

# 访问元素
print(my_list[0])  # 10

# 修改元素
my_list[1] = 25
print(my_list)  # [10, 25, 30, 40, 50]

# 添加元素
my_list.append(60)
print(my_list)  # [10, 25, 30, 40, 50, 60]

# 删除元素
del my_list[2]
print(my_list)  # [10, 25, 40, 50, 60]

# for循环遍历列表
print("for循环遍历列表")
for item in my_list:
    print(item)

# while循环遍历列表
print("while循环遍历列表")
index = 0
while index < len(my_list):
    print(my_list[index])
    index += 1

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值