189k views
0 votes
Write a function in python that computes and returns the sum of the digits for any integer that is between 1 and 999, inclusive. Use the following function header: def sum_digits(number): Once you define your function, run the following examples: print(sum_digits(5)) print(sum_digits(65)) print(sum_digits(658)) Note: Do not hard-code your function. Your function should run for any number between 1 and 999. Your function should be able to decide if the number has 1 digit, 2 digits, or 3 digits.

1 Answer

6 votes

Answer:

def sum_digits(number):

total = 0

if 1 <= number <= 999:

while number > 0:

r = int (number % 10)

total +=r

number /= 10

else:

return -1

return total

print(sum_digits(658))

Step-by-step explanation:

Write a function named sum_digits that takes one parameter, number

Check if the number is between 1 and 999. If it is, create a while loop that iterates until number is greater than 0. Get the last digit of the number using mudulo and add it to the total. Then, divide the number by 10 to move to the next digit. This process will continue until the number is equal to 0.

If the number is not in the given range, return -1, indicating invalid range.

Call the function and print the result

User Yuliani Noriega
by
4.2k points