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)
相关推荐
AI探索者6 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者6 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh8 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅8 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽9 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时13 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿15 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python