用python编写1到100数的相加
您好,以下是 Python 代码,用于计算 1 到 100 的所有数字之和:
total = 0
for i in range(1, 101):
total += i
print("1到100的总和为:", total)
代码解释:
-
我们首先定义一个变量
total,用于存储所有数字的总和,初始值为 0。 -
通过使用
for循环和range函数,我们可以迭代从 1 到 100 的所有数字。 -
在循环的每个迭代中,我们将当前数字添加到
total变量中。 -
最后,我们使用
print函数输出计算结果。
希望对您有所帮助!
原文地址: https://www.cveoy.top/t/topic/q4o 著作权归作者所有。请勿转载和采集!