Python08 循环

复制代码
'''
    循环
    1. while
    2. for

    循环控制
    1.back 退出当前循环
    2.continue 结束本次继续下次循环
'''

i = 0
while i < 10:
    print(f'我正在学习python {i}')
    i+=1 #循环增量
print('while 结束')

while True:
    print(f'我正在学习python {i}')
    if i > 20:
        break #退出循环
    i+=1 #循环增量
print('while2 结束')

# range 参数说明(开始数值,结束数值, 步长),结束数值是必须的,步长不指定默认为1,开始数值 不指定默认为0
print('for')
for i in range(1, 11, 1):
    print(f'for1 {i}')
print('---------------------')
for i in range(1,11):
    print(f'for2 {i}')

print('---------------------')
for i in range(11):#(结束数值),
    print(f'for3 {i}')
复制代码
循环 的 else 用法
复制代码
'''
循环 的 else 用法
循环自己结束,而不是从break中结束时,执行else

while 循环 else 格式
while True:
    XXXXX
else;
    print('3次密码错误,账号冻结,请联系管理员')
'''

for i in range(3):
    password = input('请输入密码:')
    if password == "666":
        print('登录成功')
        break
    else:
        print('密码错误,请重新输入。')
else:
    print('3次密码错误,账号冻结,请联系管理员')

print('程序结束')

for s in 'hello,python':
    print("for out str : ", s)
else:
    print("for out str 正常结束")

sum = 0
index = 1
while index <= 100:
    sum += index
    index += 1 #python 没有 index ++ 的写法,注意
else:
    print('1-100和为:',sum)
相关推荐
曲幽1 天前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户8356290780511 天前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon1 天前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly1 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程1 天前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly1 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风2 天前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风2 天前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风3 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python