Python从0到1——⑦循环和判断结构

本文介绍了Python中的循环和判断结构,包括常规while循环、使用set、list进行循环,以及for循环与range、dict的结合使用。同时展示了如何在循环中结合判断语句实现特定逻辑,例如条件输出和循环控制。通过实例代码详细解析了每种循环结构的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python从0到1——循环和判断结构

其他常用操作见:https://blog.youkuaiyun.com/qq_33302004/article/details/112859327

目录

1.常规 while 循环

2.使用set进行while循环

3.使用list进行while循环

4.使用list进行for循环

5.使用range进行for循环

6.使用dict进行for循环

7.循环和判断结合


1.常规 while 循环

temp = 0
while temp < 10:
    print(temp)
    temp += 1

2.使用set进行while循环

temps = {'123', '456', '789'}
print(type(temps),temps)
while temps:
    temp = temps.pop()  # set 是pop第一个,但是set本身的顺序是不一定的
    print(temp)

3.使用list进行while循环

temps = ['123', '456', '789']
print(type(temps),temps)
print(temps[0],temps[2])
while temps:
    temp = temps.pop()  # list 是pop最后一个元素
    print(temp)

4.使用list进行for循环

temps = ['123', '456', '789']
for i in temps:
    print(i)

5.使用range进行for循环

range()可以理解为下标索引

temp = 10
for i in range(temp):
    print(i)

6.使用dict进行for循环

temp = {'math':98, 'chinese':99, 'english':100}
for key in temp.keys():
    print(key, temp[key])

7.循环和判断结合

temp = [1,2,3,4,5,6]
for i in temp:
    if(i%2 == 0):
        print(i)
    elif(i%5 == 0):
        break
    else:
        continue

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值