If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To calculate the sum of natural numbers in Python, you can use a simple loop or use the formula for the sum of the first n natural numbers. Here are two common approaches:
- Using a Loop: You can use a
for
loop to iterate from 1 to the given number and sum the numbers.pythonCopy code
def sum_of_natural_numbers(n): total_sum = 0 for i in range(1, n + 1): total_sum += i return total_sum # Example usage: n = 10 result = sum_of_natural_numbers(n) print(f"The sum of the first {n} natural numbers is: {result}")
- Using Formula: The sum of the first n natural numbers can be calculated using the formula: sum = (n * (n + 1)) / 2.
pythonCopy code
def sum_of_natural_numbers(n): return (n * (n + 1)) // 2 # Example usage: n = 10 result = sum_of_natural_numbers(n) print(f"The sum of the first {n} natural numbers is: {result}")
Both approaches will give you the same result. The formula-based approach is more efficient as it calculates the sum directly without the need for a loop, making it more suitable for large values of n. However, both methods are valid and will give you the correct sum of the first n natural numbers.
Comments: 0