Problem 138006 · easy · Level 01 Prerequisites & Setup

Sum of the First N Numbers

loops · range · accumulation

Write a function sum_to_n(n) that returns 1 + 2 + 3 + ... + n using a loop. When n is 0 there is nothing to add, so return 0.

Examples

Input:  n = 4
Output: 10
Explanation: 1 + 2 + 3 + 4 = 10

Input:  n = 0
Output: 0

Constraints

  • 0 <= n <= 10**5

Goals

  • Use a for loop with range() to visit every number from 1 to n
  • Keep a running total in a variable
Starting Python…