In: Computer Science
python exercise:
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:
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
it asks the sum of the digits such as 21+22=7
Sol: Python code for above problem:
#initiating sunDigits function for number between 1 to n(inclusive)
def sumDigits(n) : 
    result = 0   # initialize result 
    #initiating for loop from 1 to n 
    for x in range(1, n+1) : 
        result = result + sumOfDigits(x) 
    return result 
#initiating sumofDigits function  
def sumOfDigits(x) : 
    sum = 0
    while (x != 0) : 
        sum = sum + x % 10
        x   = x // 10
    return sum
#main function
n=int(input("Enter an integer n"))
if n>0:
    print(sumDigits(n))
else:
    print("Value must be positive")
Sample Output:
