下面示例将分别用 for 循环和 while 循环实现 1~100 求和。
示例代码:
# 初始化总和为 0
total = 0
# 遍历 1 到 100 的所有整数
for i in range(1, 101):
total += i # 累加
# 输出结果
print("for循环:1到100的和 =", total)运行结果:
for循环:1到100的和 = 5050示例代码:
# 初始化总和与计数器
total = 0
i = 1
# 当 i 小于等于 100 时继续循环
while i <= 100:
total += i
i += 1 # 计数器自增
# 输出结果
print("while循环:1到100的和 =", total)运行结果:
while循环:1到100的和 = 5050