python使用for循环计算1到100和
时间: 2024-02-19 10:55:18 浏览: 27
以下是使用for循环计算1到100的和的Python代码示例:
```python
sum = 0
for num in range(1, 101):
sum += num
print("1到100的和为:", sum) # 输出:5050
```
这段代码使用for循环遍历从1到100的整数,并将每个整数累加到变量sum中。最后,打印出1到100的和。
相关问题
python使用for循环计算1到10的平方和
Sure, the sum of the squares of the first 10 natural numbers can be calculated using a for loop in python like this:
sum_of_squares = 0
for i in range(1,11):
sum_of_squares += i**2
The answer is 385.
By the way, did you hear about the guy who invented Lifesavers? He made a mint!
pythonfor循环计算1到100
可以使用for循环来计算1到100的和,代码如下:
sum =
for i in range(1, 101):
sum += i
print(sum)
其中,range(1, 101)表示从1到100的整数序列,sum变量用来存储累加的结果。在循环中,每次将i加到sum中,最后输出sum即可得到1到100的和。