Introduction π
Type casting is the process of converting one data type into another. Python makes type conversion simple and powerful using built-in functions likeint(), float(), str(), list(), and more.
Note
1. Why Do We Need Type Casting? π€
Pythonβs input() function always returns a string. If you want to perform arithmetic operations or convert data formats, you must convert (cast) the value to another type.
need_casting.py
age = input("Enter age: ") # returns "25"
# print(age + 1) # β Error: can't add string and int
age = int(age) # βοΈ Convert to integer
print(age + 1)2. Types of Type Casting π―
π 1. Implicit Type Casting
Python automatically converts one type to another when safe. You donβt need to do anything manually.
implicit_casting.py
x = 5 # int
y = 3.2 # float
result = x + y # int is converted to float
print(result) # Output: 8.2Note
π 2. Explicit Type Casting
You manually convert a value from one type to another using functions like:
- int() β convert to integer
- float() β convert to float
- str() β convert to string
- bool() β convert to boolean
- list() β convert to list
- tuple() β convert to tuple
- set() β convert to set
3. Converting to Integer (int) π’
to_int.py
x = "10"
y = int(x) # "10" β 10
print(y, type(y))Note
4. Converting to Float (float) π§
to_float.py
x = "3.14"
y = float(x)
print(y, type(y))5. Converting to String (str) π
to_string.py
x = 100
y = str(x)
print(y, type(y))6. Converting to Boolean (bool) π₯
bool() follows these rules:
- 0, "", [], , None β False
- Anything else β True
to_bool.py
print(bool(0)) # False
print(bool(5)) # True
print(bool("")) # False
print(bool("hi")) # True7. Converting to List (list) π¦
to_list.py
x = "Python"
y = list(x)
print(y) # ['P', 'y', 't', 'h', 'o', 'n']8. Converting to Tuple (tuple) π
to_tuple.py
x = ["a", "b", "c"]
y = tuple(x)
print(y)9. Converting to Set (set) π―
to_set.py
x = [1, 2, 2, 3]
y = set(x)
print(y) # {1, 2, 3}Note
10. Real-World Example π§ͺ
real_world.py
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello {name}, next year you will be {age + 1}!")11. Common Errors β οΈ
- Trying to cast letters into numbers (e.g., int("abc"))
- Forgetting that input() gives a string
- Converting incorrectly formatted numbers like "10.5" β int β
Note
Conclusion π
You're now ready to work with inputs, calculations, and complex data transformations. Want the next topic? Try Operators, Expressions, Conditional Statements, Loops, or Functions. Just ask! π