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

How to find the sum of n terms in Python

爱喝马黛茶的安东尼
Release: 2019-06-25 13:43:05
Original
7757 people have browsed it

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template