P_13 Coding Exercises for Beginners in Python | Exercise #3 | Program to add digits of a number
Understanding Type Conversion and Adding Digits in Python
Introduction to the Exercise
- The video begins with a recap of type conversion (or type casting) in Python, emphasizing its importance in programming.
- The coding exercise involves writing a program that adds the digits of a two-digit number input by the user.
Problem Statement
- The task requires users to enter a two-digit number, and the program should output the sum of its digits. For example, entering "12" should yield an output of 3 (1 + 2).
- Viewers are encouraged not to overthink the problem or search for complex solutions; instead, they should focus on using basic programming concepts.
Key Concepts for Implementation
- Users will utilize the
inputfunction to capture user input as a string. Each character can be accessed individually using subscripting.
- A hint is provided about applying type conversion alongside string manipulation techniques learned previously.
Coding Steps
- The instructor suggests creating a new file named
exercise2.pyand prompts users to take input from the user with an appropriate message.
- It is noted that any input taken through
input()will be treated as a string by default, which is crucial for accessing individual characters later.
Accessing Individual Digits
- To extract digits from the entered string, subscripting is used:
numberretrieves the first digit whilenumberretrieves the second digit.
- These extracted characters are stored in variables (
first_digitandsecond_digit) but remain strings at this point.
Converting Strings to Integers
- To perform arithmetic operations, it’s necessary to convert these string representations into integers using
int().
- After conversion, adding these integers together will yield correct results rather than concatenating them as strings.
Final Output and Testing
- The final print statement combines both converted digits and outputs their sum correctly.
- An example run shows that entering "12" produces an output of 3. Further testing with other numbers like "45" confirms functionality.
Conclusion and Encouragement
- Viewers are encouraged to try coding independently before checking solutions and share their code in comments for feedback.