In: Computer Science
a. Write a function sumDigits that takes a positive
integer value and returns the
total sum of the digits in the integers from 1 to that number
inclusive.
b. Write a program to input an integer n and call the above
function in part a if n
is positive, else give ‘Value must be Positive’ message.
Sample Runs:
Enter a positive integer: 1000000
The sum of the digits in the number from 1 to 1000000 is
27000001
Enter a positive integer: -642
Value must be Positive
and write e a docstring comment for this
The python program validates the input and print error when the value is not positive. When the value is positive, it will find the sum of the from 1 to N and print the output.
def sumDigits(num):
"""This method will find the sum of numbers from 1 to num."""
sum=0;
# Calculate the sum of number and save to the sum variable
for x in range(1, num +1):
sum+=x
print("The sum of the digits in the number from 1 to ", num, " is : ", sum)
print(sumDigits.__doc__)
num = int(input("Enter a positive integer :"));
# Print the error message if the number is not positive.
if num < 0:
print("Value must be Positive");
else:
sumDigits(num);
Output