Type Casting
In Python, casting is the process of converting a variable from one type to another. Python has built-in functions for converting between data types.
Specify a Variable Typeβ
Python is an object-oriented language, and variables are objects.
You can specify the data type using casting functions:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
int() - Integer Castingβ
Converts a value to an integer. Works with floats and numeric strings.
x = int(1) # 1
y = int(2.8) # 2
z = int("3") # 3
# w = int("abc") # Error
float() - Floating-Point Castingβ
Converts a value to a float. Works with integers and numeric strings.
a = float(1) # 1.0
b = float("2.5") # 2.5
c = float(3.0) # 3.0
str() - String Castingβ
Converts numbers or other types into a string.
x = str("s1") # 's1'
y = str(2) # '2'
z = str(3.0) # '3.0'
Invalid Castingβ
Some values can't be casted directly:
int("hello") # ValueError
float("abc") # ValueError
Use try/except to handle safely:
value = "abc"
try:
number = int(value)
except ValueError:
print("Invalid conversion")
Summary Tableβ
| Function | Converts to | Example Input | Output |
|---|---|---|---|
int() | Integer | "3" | 3 |
float() | Float | "3.5" | 3.5 |
str() | String | 3.5 | "3.5" |
Quick Notesβ
- Use casting to convert types manually.
- Useful when handling user input, math, or data from files.
- Always validate input before casting to avoid errors.