Python Casting
1. What is Casting in Python?
Casting means changing one data type into another.
Example:
-
Text → Number
-
Number → Text
Python uses casting when we need to do calculations or print values correctly.
2. Why Do We Need Casting?
User input is always text (string).
Example:
❌ This gives an error because Python cannot add text + number.
So we use casting.
3. String to Integer (int())
Convert text to whole number.
Example
Output:
User Input Example
4. String to Float (float())
Convert text to decimal number.
Example
User Input Example
5. Integer to Float
Example
Output:
6. Float to Integer
Decimal part is removed (not rounded).
Example
Output:
7. Number to String (str())
Convert number to text.
Example
8. Checking Type After Casting
Use type() to check data type.
Example
9. Common Casting Errors (Beginners)
❌ Invalid Conversion
❌ Error because “hello” is not a number.
✔ Correct Way
10. Simple Practice Examples
Example 1: Add Two Numbers from Input
Example 2: Convert Float to Int
Example 3: Print with String Conversion
11. Summary (Python Casting)
✔ Casting means changing data type
✔ Input is string by default
✔ int() converts to number
✔ float() converts to decimal
✔ str() converts to text
📘 Perfect for Beginner eBook
This chapter is ideal for:
-
Python beginner books
-
School & college students
-
Self-learners
If you want next, I can write:
-
Python Strings (easy)
-
Python Booleans
-
Operators
-
Casting Exercises
-
MCQs with answers
Just tell me 😊
