Type Conversion & Type Hinting in Python
Type Casting in Python
Type casting in Python refers to converting one data type into another. It's useful when you need to operate on values of different types in a compatible way.
Types of Type Casting
There are two main types:
1. Implicit Type Casting
2. Explicit Type Casting
1. Implicit Conversion
Python automatically converts data types.
a = 5
b = 2.0
c = a + b
print(c)
print(type(c))
Output:
7.0 <class 'float'>
2. Explicit Conversion (Type Casting)
You manually convert data using functions like int(), float(), str(), etc.
a = "10"
b = int(a)
c = float(a)
print(b, type(b))
print(c, type(c))
Output
10 <class 'int'> 10.0 <class 'float'>
Common Conversion Functions:
Function | Description |
---|---|
int() | Convert to integer |
float() | Convert to float |
str() | Convert to string |
list() | Convert to list |
tuple() | Convert to tuple |
dict() | Convert to dictionary |
set() | Convert to set |
bool() | Convert to boolean |
TYPE HINTING (Introduced in Python 3.5+)
Type hinting allows you to declare the expected data types of variables, function arguments, and return values. It helps improve code readability, debugging, and editor support.
Example 1: Function With Type Hints
def greet(name: str) -> str:
return "Hello " + name
print(greet("Alice"))
Output:
Hello Alice
Example 2: Variable Type Hints
age: int = 25
pi: float = 3.14
active: bool = True
Example 3: Complex Function
def add_numbers(a: int, b: int) -> int:
return a + b
print(add_numbers(3, 4))
Output:
7
Benefits of Type Hinting
Benefit | Description |
---|---|
IDE autocomplete | Helps in writing correct code |
Error detection | Tools like mypy can check type errors |
Better documentation | Makes code easier to understand |
Combining Type Hints with Default Values
def welcome(name: str = "Guest") -> str:
return f"Welcome, {name}!"
print(welcome())
Output:
Welcome, Guest!
SUMMARY
Feature | Description |
---|---|
Data Types | Classify values: int, float, str, etc. |
Type Conversion | Implicit & explicit conversion of types |
Type Hinting | Declare variable/function types for clarity |