Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Examples
  3. Sum of Natural Numbers

Loops · Python example

Sum of Natural Numbers

Add the first n natural numbers with a loop and compare the closed formula.

Open the compilerAll examples
beginnerloopssumformula

Adding the numbers from 1 to n can be done iteratively or with a closed formula. This example computes both and shows that they agree.

example.py
n = 100

loop_total = 0
for value in range(1, n + 1):
    loop_total += value

formula_total = n * (n + 1) // 2

print(f"Loop result: {loop_total}")
print(f"Formula result: {formula_total}")

How the code works

  • The loop adds every value from 1 to 100 to loop_total.
  • The formula multiplies 100 by 101 and divides by 2.
  • Both results are 5050.

Key ideas

  • range(1, n + 1) includes n.
  • // is floor division, which keeps the formula result an integer.
  • The formula n(n + 1) / 2 is much faster for large n.

Try changing it

  • Sum only even numbers below n.
  • Compare execution time for a very large n.
  • Wrap the loop in a function and use sum(range(1, n + 1)).

Related examples

beginner

Multiplication Table

Print a ten-row multiplication table with a for loop and range().

beginner

Calculate a Factorial

Multiply numbers in a loop to compute n! with a loop.

Previous exampleReverse a NumberNext examplePalindrome Checker

Expected output

Loop result: 5050
Formula result: 5050

Output is compared after trimming trailing whitespace on each line. Run the code to see it produced by CPython in your browser.

Practice next

Apply the same idea with automatic tests or browse a guided project.

ExercisesProjects