HW03 判斷敘述式

HW03 判斷敘述式 115103136余廷宥

1.NotebookLM

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:

StepCalculationResult
14225 % 105
24225 // 10422
3422 % 102
4422 // 1042
542 % 102
642 // 104
74 % 104

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

  1. input() asks the user to enter a four-digit number.
  2. int() converts the input into an integer.
  3. % 10 extracts the last digit of a number.
  4. // 10 removes the last digit.
  5. The program repeats these operations to extract all four digits.
  6. The + operator adds the four digits together.
  7. print() displays the original number and the sum of its digits.

🛠️ Requirements

  • Python 3.x

🚀 How to Run

  1. Save the program as sum_of_digits.py.
  2. Open a terminal or command prompt.
  3. 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.

留言

這個網誌中的熱門文章

python作業

HW02 運算子表達式