Python Program to Get Sum of Natural Numbers codigence

Python Program to Get Sum of Natural Numbers codigence


Python Program to Get Sum of Natural Numbers codigence

  • Python Program to get Sum of Natural Numbers using For Loop.
  • Sum of Natural Numbers in Python using While Loop.
  • Sum of Natural Numbers in Python using Formula.

Overview Natural Numbers in Python

Natural numbers are the whole numbers except 0.Now we will see how to get sum of first natural numbers.

Python Program to get Sum of Natural Numbers using For Loop

  • Define a function to get Sum of n natural numbers.
  • Let's have a function named 'sum_of_n_numbers' and take the argument 'n' for number to get sum.
  • Now Inside the Function,
  • Now initialize a variable,say 'sum' to zero.This will store the Sum of numbers.
  • Using for loop to get the Sum of natural numbers up to n.
  • Call the function to get sum and print the Final results.

#using for loop
def sum_of_n_numbers(n: int):
    sum = 0
    for i in range(n+1):
        sum+=i
    return sum

print(f"sum natural numbers upto  20 = {sum_of_n_numbers(20)}")

Output


sum natural numbers upto  20 = 210

Python Program to get Sum of Natural Numbers using while Loop

  • Define a function to get Sum of n natural numbers.
  • Let's have a function named 'sum_of_n_numbers' and take the argument 'n' for number to get sum.
  • Now Inside the Function,
  • Now initialize a variable,say 'sum' to zero.This will store the Sum of numbers.
  • Using while loop to get the Sum of natural numbers up to n.
  • Call the function to get sum and print the Final results.

#using while loop
def sum_of_n_numbers(n: int):
    sum = 0
    i = 1 # i for iteration
    while i <= n:
        sum+=i
        i+=1
    return sum

print(f"sum natural numbers upto  20 = {sum_of_n_numbers(20)}")

Output


sum natural numbers upto  20 = 210

Python Program to get Sum of Natural Numbers using Formula

  • Define a function to get Sum of n natural numbers.
  • Let's have a function named 'sum_of_n_numbers' and take the argument 'n' for number to get sum.
  • Now Inside the Function,
  • Using formula to get the Sum of natural numbers up to n.
  • Call the function to get sum and print the Final results.

#using formula
def sum_of_n_numbers(n: int):
    return n*(n+1)/2

print(f"sum natural numbers upto  20 = {sum_of_n_numbers(20)}")

Output


sum natural numbers upto  20 = 210.0

Conclusion

Python allows us to calculate Sum of n Natural numbers quickly and effectively through its multiple features.