Day 3 列表、循环与判断语句

@浙大疏锦行

列表的基础操作

列表的基础操作包括增删改查、排序与反转、复制、遍历等。

  • 增:append()末尾添加;insert()指定位置插入;extend([])扩展列表
  • 删:remove()按值删除;del li[0]按索引删除;pop(i);clear()清空
  • 排序:sort()原列表排,无返回值;sorted(li)返回新列表
  • 反转:reverse;reversed返回的是迭代器对象;可用切片实现反转操作,[::-1]
  • 查找索引:index
  • 统计次数
  • 遍历
tech_list = ['Python','Java','Go'] #创建列表
first_tech = tech_list[0] #查找
tech_list.append('JavaScript') #增加
tech_list[1] = 'Ruby' #修改
tech_list.remove('Go') #删除
current_length = len(tech_list)
print(f'第一个技术是:{first_tech}')
print(f'当前列表长度:{current_length}')
print(f"最终列表内容:{tech_list}")

循环for语句

循环语句主要有for循环和while循环两种,均支持break、continue、else。

  • for循环:遍历可迭代对象,已知次数循环
  • while循环:基于布尔条件,未知次数循环
  • range(m,n,k):左闭右开,range(1,101,2)
sum = 0 #初始化求和变量,从0开始累加
for i in range(1,101): #循环从1到100,range函数左闭右开
    sum += i #累加
print(f'总和为:{sum}') #格式化输出结果

判断语句

if-elif-else语句

temperature = 23
#if-elif-else判断语句
if temperature > 35:
    print('红色预警:高温天气!')
elif temperature >= 28 and temperature <= 35:
    print('黄色预警:天气炎热!')
elif 20 <= temperature <= 27:
    print('绿色提示:适宜温度')
else:
    print('蓝色预警:注意保暖')
scores = [85, 92, 78, 65, 95, 88] #创建列表
excellent_count = 0 #分数大于等于90的个数
total_score = 0 #总分数
for score in scores: #遍历
    total_score += score
    if score >= 90: #判断
        excellent_count += 1
average_score = total_score / len(scores) #计算平均分数
print(f'优秀分数个数:{excellent_count}')
print(f'分数总和:{total_score}')
print(f'平均分数:{average_score:.3f}')

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值