HW03 判斷敘述式
HW03 判斷敘述式 115103136余廷宥
2.影片
3.學習卡與測驗
4.寫1個程式需附加說明 Create a README For Github
2. Calculate the Sum of Digits of a Four-Digit Number
📌 Description
This Python program reads a four-digit number from the keyboard and calculates the sum of its individual digits.
For example, if the user enters 4225, the sum of its digits is:
4 + 2 + 2 + 5 = 13
💻 Python Code
num = int(input('Enter 4 digit number: '))
print('Entered number is:', num)
r1 = num % 10
q1 = num // 10
r2 = q1 % 10
q2 = q1 // 10
r3 = q2 % 10
q3 = q2 // 10
r4 = q3 % 10
print('Sum of all the digits within number', num,
'is:', r1 + r2 + r3 + r4)🧮 Logic and Formula
The program uses two mathematical operators:
%(Modulus): Gets the remainder, which is used to extract the last digit.//(Floor Division): Removes the last digit by dividing by 10 and keeping the integer part.
For the number 4225:
| Step | Calculation | Result |
|---|---|---|
| 1 | 4225 % 10 | 5 |
| 2 | 4225 // 10 | 422 |
| 3 | 422 % 10 | 2 |
| 4 | 422 // 10 | 42 |
| 5 | 42 % 10 | 2 |
| 6 | 42 // 10 | 4 |
| 7 | 4 % 10 | 4 |
Sum of digits = 5 + 2 + 2 + 4 = 13
▶️ Example Output
Enter 4 digit number: 4225
Entered number is: 4225
Sum of all the digits within number 4225 is: 13📝 Explanation
input()asks the user to enter a four-digit number.int()converts the input into an integer.% 10extracts the last digit of a number.// 10removes the last digit.- The program repeats these operations to extract all four digits.
- The
+operator adds the four digits together. print()displays the original number and the sum of its digits.
🛠️ Requirements
- Python 3.x
🚀 How to Run
- Save the program as
sum_of_digits.py. - Open a terminal or command prompt.
- Run the following command:
python sum_of_digits.py📚 Learning Objectives
- Reading keyboard input in Python.
- Using the modulus operator (
%). - Using floor division (
//). - Extracting individual digits from a number.
- Performing arithmetic calculations.
📄 License
This project is for educational purposes.












留言
張貼留言