beginner

Type Casting & Conversions

5 min readLast updated: 2026-07-12

Overview

Type casting is the process of converting a value from one data type to another.

Learning Objectives

  • Understand the difference between automatic and manual type conversion.
  • Convert string values into integers and floats safely.
  • Handle errors that happen when type casting invalid values.

Concept Explanation

Sometimes Python converts types automatically (like adding an integer to a float). Other times, you must do it manually. You can convert values by using constructor names like int(), float(), and str(). If you try to cast text that is not a valid number, Python raises a ValueError.

Code Examples

Example 1 — Basics

This example introduces the fundamental syntax and concepts.

python
number = int('42')
decimal = float('3.14')
text = str(100)

Example 2 — Everyday Usage

This example demonstrates a realistic scenario handling business parameters.

python
# Calculate total weight
weight_input = '15.5'
total_weight = float(weight_input) + 2.0
print(f'Total weight: {total_weight} kg')

Example 3 — Advanced Example

This example shows clean, production-grade code structure following senior development standards.

python
# Parse input safely with fallback default value
port_input = '8080'
try:
    port = int(port_input)
except ValueError:
    port = 80 # Fallback default if parsing fails
print(f'Server listening on port {port}')

Visual Flow

The following execution flow represents the step-by-step evaluation inside the interpreter:

text
Input value string → Check format compatibility → Create brand new converted object → Return reference

Common Mistakes

Review these common pitfalls when working with this topic:

  • Trying to convert decimal text directly to an integer (e.g. int('3.14') fails; use float('3.14') first).
  • Casting any non-empty text string to boolean expecting False (e.g. bool('False') is True).
  • Expecting type casting functions to permanently change the original variable's type.
  • Forgetting to wrap conversions of user input strings in try-except blocks.

Best Practices

Enforce these Pythonic best practices in your codebase:

❌ Don't
python
x = '10'
y = int(x)
# y is now int, but x is still a string!
✅ Do
python
x = int(x) # Update the variable to hold the converted value

Quick Revision

Use these key summaries for last-minute revision:

  • Python automatically promotes integer and float math to float.
  • Use int(), float(), and str() to convert types manually.
  • Text must match numeric format standards to be cast to numbers.
  • Empty strings cast to False; all other strings cast to True.
  • Type casting creates a brand new value; it does not change the old one.