77.6k views
3 votes
Write a function that asks the user to enter a number (i) between 1 - 1000, then calculate the sum of all numbers from 1 to (i).

1 Answer

1 vote

Answer:

In Python

def sum(num):

total = 0

for i in range(1,num+1):

total = total + i

print(total)

i = int(input("User input [1 - 1000]: "))

if i >= 1 and i <= 1000:

sum(i)

else:

print("Invalid User Input")

Explanation:

The function is declared here

def sum(num):

The sum is initialized to 0

total = 0

The following iteration calculates sum from 1 to the user input

for i in range(1,num+1):

total = total + i

The total is then printed

print(total)

The main begins here

This line prompts user for input

i = int(input("User input [1 - 1000]: "))

The following if condition ensures that user input is between 1 and 1000

if i >= 1 and i <= 1000:

sum(i)

else:

print("Invalid User Input")

User Radu Cojocari
by
5.1k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.