Home  >  Article  >  Backend Development  >  How to find the sum of n terms in Python

How to find the sum of n terms in Python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-25 13:43:057735browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn