197k views
0 votes
Write a program that will ask the user for a positive integer value. Use a loop to validate the input. (Python)

The program will find and display the sum of even integers from 1 up to the number entered.

Note:

The Project must use functions. The following functions need to be used in your project. If you like to add more functions, it will be great.

• getIntegerData() – a function that will validate the user’s entry of a positive integer

• main()

Write a program that will ask the user for a positive integer value. Use a loop to-example-1
User Khalifa
by
8.4k points

1 Answer

3 votes

Answer: Your welcome!

Step-by-step explanation:

def getIntegerData():

# This function will validate the user's entry of a positive integer

while True:

try:

num = int(input("Enter a positive integer: "))

if num > 0:

return num

else:

print("Please enter a valid positive integer")

except ValueError:

print("Error: Invalid input. Please enter a valid positive integer")

def main():

# Main Function

num = getIntegerData()

# Initialize the sum

even_sum = 0

# Use a loop to calculate the sum of even integers from 1 up to the number entered

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

if i % 2 == 0:

even_sum += i

# Print the sum

print(f"The sum of even integers from 1 to {num} is {even_sum}")

# Call the main function

main()

User Enric Agud Pique
by
8.7k points