Python•Type Conversion
Python Type Casting and Conversion with Examples
Python provides explicit conversion constructors like int(), float(), str(), bool(), list(), and set() to transform data safely between incompatible types.
Syntax
new_value = target_type(original_value)
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| target_type | Type constructor | int, float, str, bool, list, tuple, or set. |
| original_value | Any convertible object | The value to cast. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Python locally:
# Explicit Type Casting in Python
raw_price = "49.95"
quantity_str = "3"
# Convert strings to float and int
unit_price = float(raw_price)
quantity = int(quantity_str)
subtotal = unit_price * quantity
# Boolean truthiness conversion
empty_list = []
active_items = ["Laptop", "Mouse"]
print(f"Unit Price: ${unit_price} ({type(unit_price).__name__})")
print(f"Quantity: {quantity} ({type(quantity).__name__})")
print(f"Subtotal: ${subtotal:.2f}")
print(f"Empty list bool: {bool(empty_list)}")
print(f"Active items bool: {bool(active_items)}")Expected Output:
Unit Price: $49.95 (float) Quantity: 3 (int) Subtotal: $149.85 Empty list bool: False Active items bool: True
How It Works: Step-by-Step
- Lines 6-7: Converts numeric strings into float and int primitives.
- Line 8: Multiplies numeric float by integer successfully.
- Lines 15-16: Demonstrates Python truthiness: empty containers evaluate to False.
Key Concepts
- float("49.95") parses decimal numbers from text.
- int("3") extracts integer values; passing non-digit strings raises ValueError.
- bool() converts empty strings, 0, None, and empty collections to False.
Common Mistake: Passing a floating-point string directly to int()
int("49.95") throws ValueError. Convert to float first, then int.
❌ Incorrect
price = int("49.95") # ValueError: invalid literal for int()✅ Correct
price = int(float("49.95")) # Correct: turns 49.95 into 49Related Python Tutorials & Compiler
Python Variables and Data Types with Examples
Variables in Python are containers for storing data values. Python is dynamically typed, so you do not need to declare types explicitly.
Python Operators: Arithmetic, Comparison & Logical
Operators are special symbols that carry out computations on values and variables in Python.
Python Input and Output (I/O) with print() and input()
Learn how to display outputs to the console using print() and receive interactive user input with input().
Python Online Compiler
Open in Compilra IDE
Run and test Python on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.