231k views
0 votes
Write a Python program that prompts the user to enter a positive integer and prints the sum of

each digit in the user-entered integer as shown in the test cases. Your program must ask the
user if they like to repeat the program (yes or no), repeat the program until they enter "no",
and then exit with "Thank you! Good bye!" as shown in the test cases.
Program Inputs
Enter a positive integer:
You can assume that the user always enters a valid input, no input validation needed.
Repeat the program (yes or no)?
A Question for repeating (yes or no)
If user enters "yes," display the initial prompt "Enter a positive integer: "again. If user
enters "no," display the final message "Thank you! Good bye!" and terminate the
program.
Program Output
The sum of each digit in X:...
Replace X with the user input
Replace... with calculated sum of each digit in the user input
Test Cases:
Let's find the sum of each digit in a number!
Enter a positive integer: 12345678910
The sum of each digit in 12345678910:46
Repeat the program (yes or no)? yes
Enter a positive integer: 10000000013
The sum of each digit in 10000000013: 5
Repeat the program (yes or no)?y
Enter a positive integer: 10182022
The sum of each digit in 10182022: 16
Repeat the program (yes or no)?

1 Answer

2 votes

Final answer:

To write a Python program that prompts the user to enter a positive integer and prints the sum of each digit in the user-entered integer, you can follow these steps. Here's an example implementation of this program using a while loop and the input() function.

Step-by-step explanation:

To write a Python program that prompts the user to enter a positive integer and prints the sum of each digit in the user-entered integer, you can follow these steps:

  1. Prompt the user to enter a positive integer using the input() function.
  2. Convert the user-entered integer to a string using the str() function.
  3. Initialize a variable sum_digits to 0.
  4. Use a for loop to iterate through each character in the string representation of the user-entered integer.
  5. Convert the current character back to an integer using the int() function and add it to the sum_digits variable.
  6. Print the sum of the digits using the print() function.
  7. Ask the user if they want to repeat the program. If they enter 'no', print 'Thank you! Goodbye!' and terminate the program. If they enter 'yes', repeat the program from the beginning.

Here's an example implementation of this program:

while True:
num = input('Enter a positive integer: ')
sum_digits = 0
for digit in str(num):
sum_digits += int(digit)
print('The sum of each digit in', num, 'is:', sum_digits)
repeat = input('Repeat the program (yes or no)? ')
if repeat == 'no':
print('Thank you! Goodbye!')
break

User Jessecurry
by
7.6k points