Python Program to Find the Sum of Natural Numbers
ⓘ Sponsored by 10xer.co
Natural numbers are a set of positive integers that are used to count and measure quantities.
Python Code :
The below Python program finds the sum of natural numbers up to a given number:
# Function to find sum of natural numbers up to n
def sum_of_natural_numbers(n):
# Initialize sum to 0
sum = 0
# Iterate over natural numbers up to n
for i in range(1, n+1):
# Add current number to sum
sum += i
# Return sum
return sum
# Example usage
n = 10
sum = sum_of_natural_numbers(n)
print("The sum of natural numbers up to", n, "is", sum)
In the above code, the sum_of_natural_numbers function takes a single argument n, which specifies the upper limit of the natural numbers to be summed. It initializes a variable sum to 0, and then iterates over the natural numbers from 1 to n using a for loop. For each number, it adds the current number to sum.
After iterating over all numbers, the function returns the final value of sum.
Finally, we use the sum_of_natural_numbers function to find the sum of natural numbers up to a given number (in this case, 10) and print the result to the console.
For example :
The sum of natural numbers up to 10 is 55
ⓘ Sponsored by 10xer.co