Here’s an example Python code to find the sum of natural numbers:
# Get input from user for the last number n = int(input("Enter a positive integer: ")) # Compute the sum of natural numbers using a loop sum = 0 for i in range(1, n+1): sum += i # Display the result print(f"The sum of first {n} natural numbers is {sum}")
In this code, we first prompt the user to enter a positive integer using the input()
function and convert it to an integer using the int()
function. We then use a for
loop to iterate over the range of natural numbers from 1 to the last number entered by the user. Within the loop, we add each natural number to a variable called sum
. Finally, we use the print()
function to display the result to the user using f-strings to format the output.
When you run this code, it should prompt you to enter a positive integer. After you enter a number, it should compute the sum of the natural numbers from 1 to the entered number and display the result, similar to the following:
Enter a positive integer: 10 The sum of first 10 natural numbers is 55
Note that you can modify the messages or the formatting of the output as needed.