1. for 循环:遍历序列的利器
for循环用于遍历任何序列(如列表、元组、字符串、字典、集合)或可迭代对象中的元素。它的结构清晰,非常适合在循环次数已知或需要处理序列中每一个元素时使用。
for item in sequence:
# 执行代码块

1、进度条 while循环
import time
progress = 0
while progress <= 100:
print(f"\r加载中: [{'=' * (progress // 10)}>{' ' * (10 - progress // 10)}] {progress}%", end="")
time.sleep(0.1)
progress += 10
print("\n加载完成!")
2、进度条 for循环
import time
# 使用for循环遍历0到100(步长为10)
for progress in range(0, 101, 10):
# 计算已完成部分和剩余部分的长度
completed = '=' * (progress // 10)
remaining = ' ' * (10 - progress // 10)
# 打印进度条,\r表示回到行首覆盖输出
print(f"\r加载中: [{completed}>{remaining}] {progress}%", end="")
# 暂停0.1秒
time.sleep(0.1)
# 所有进度完成后换行并提示
print("\n加载完成!")
4. 简易密码生成器 (for, random)
循环遍历指定的长度,随机挑选字符来组成密码。
import random
import string
length = 12
# 定义字符集:大小写字母 + 数字 + 特殊符号
characters = string.ascii_letters + string.digits + string.punctuation
password = ""
for _ in range(length):
password += random.choice(characters)
print(f"为你生成的强密码是: {password}")

留留工作室