</>
Skip to content
Python lessons (9/45)

Python — Casting

Type conversion functions

Python converts types explicitly with constructor functions:

x = int(3.99)      # 3     — truncates, never rounds!
y = float(5)       # 5.0
z = str(42)        # "42"
b = bool("hi")     # True

int() — the strict one

int("42")       # 42   ✓ digits only
int("3.5")      # ValueError! strings must be whole numbers
int(3.99)       # 3    floats truncate toward zero
int(-3.99)      # -3   (not -4)

Need a decimal string as int? Two-step:

int(float("3.5"))   # 3

input() always returns strings

The most important casting fact for beginners:

age = input("Age? ")     # user types 25
print(age + 1)           # TypeError: can't concat str to int

age = int(input("Age? "))
print(age + 1)           # 26 ✓

Any math on input() results requires conversion first.

str() — for mixing with text

age = 25
print("I am " + str(age))          # works
print(f"I am {age}")               # f-strings convert FOR you — prefer this

float()

float("3.14")    # 3.14
float(7)         # 7.0
float("abc")     # ValueError

bool() — the truthiness machine

bool(0)         # False
bool("")        # False
bool([])        # False
bool("False")   # True!! non-empty string
bool(None)      # False

Falsy values: 0, 0.0, "", [], {}, None, False. Everything else is truthy.

Safe conversion pattern

Wrap risky casts in try/except:

def to_int(text, fallback=0):
    try:
        return int(text)
    except ValueError:
        return fallback

to_int("42")     # 42
to_int("abc")    # 0 — controlled failure instead of a crash

Checking types

type(x) is int          # exact type
isinstance(x, (int, float))   # accepts subclasses/multiple — preferred

Gotchas: int() truncates rather than rounds (int(2.7) → 2; use round(2.7) → 3) · bool("False") is True · implicit coercion basically doesn't exist in Python ("1" + 1 raises, unlike JS).

Mini Practice

  1. Convert "3.7" to an int two ways.
  2. Build an age-asker that survives non-numeric input.
  3. Test bool() on ten values; predict before running.
  4. Show str(4) + "4" vs 4 + 4.
  5. Write is_number(text) returning True/False using try/except.

Next: booleans →

Related Topics

Frequently Asked Questions about Casting

What is Casting in Python?

Casting is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Casting?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Casting.

Why is Casting important in Python?

Casting is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.