Python Type Conversion & Checking: A Beginner’s Guide
Python Data Types: Checking & Conversion
A quick, modern guide to managing variable types in Python.
1. How to Check a Variable's Type
In Python, you can easily inspect the data type of any variable using the built-in type() function. If you need to verify a type for conditional logic, isinstance() is the preferred, more robust method.
# Using type() to inspect x = 42 print(type(x)) # Output: <class 'int'> # Using isinstance() for validation name = "Alice" print(isinstance(name, str)) # Output: True
2. Type Conversion (Typecasting)
Python supports two types of conversion: Implicit (done automatically by Python) and Explicit (done manually by you using built-in functions).
Implicit Conversion
Python automatically converts one data type to another to prevent data loss (e.g., adding an integer to a float).
num_int = 10
num_flo = 5.5
result = num_int + num_flo
print(type(result))
# Output: <class 'float'>
Explicit Conversion
You manually convert types using functions like int(), float(), str(), list(), or tuple().
str_num = "123" # Convert string to integer actual_num = int(str_num) print(type(actual_num)) # Output: <class 'int'>
Common Conversion Functions
| Function | Description | Example |
|---|---|---|
int(x) |
Converts x to an integer. Fractions are truncated. |
int(4.8) → 4 |
float(x) |
Converts x to a floating-point number. |
float(5) → 5.0 |
str(x) |
Converts x into a string representation. |
str(100) → "100" |
list(x) |
Converts a sequence (like a tuple or string) to a list. | list("abc") → ['a', 'b', 'c'] |
Comments
Post a Comment