Home > Article > Backend Development > How to find the sum of n terms in Python
How to find the sum of n terms in python? Here are two methods:
Method 1. Use for loop
def accSum(n): sum = 0 for i in range(1, n+1): #[1,n+1) sum += i return sum
Related recommendations: "Python Video Tutorial》
Method 2, use while loop
def accSum2(n): i = 1 sum = 0 while i <= n: sum += i i = i + 1 return sum
The above is the detailed content of How to find the sum of n terms in Python. For more information, please follow other related articles on the PHP Chinese website!