Python:Python Type Casting and Conversion with Examples
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:

ParameterTypeDescription
target_typeType constructorint, float, str, bool, list, tuple, or set.
original_valueAny convertible objectThe value to cast.

Ready-to-Run Code Example

Executable in Compilra

Run 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 49

Related Python Tutorials & Compiler

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler