Browse Python Topics ▼
Pick a Web Framework

Type Conversion

📂 Variables & Data Types 📘 Lesson 9 of 57

Convert data seamlessly between strings, integers, floats, and booleans using explicit type casting while mastering Python truthiness and error handling.

In types, you learned that Python is strictly strongly typed. It refuses to silently glue numbers onto text strings during calculations.

However, in real-world software engineering, data rarely arrives in the exact format you need:

  • User input from input() is always a text string ("25").
  • Data read from text files, CSVs, or web APIs arrives as raw characters.
  • Configuration settings stored in environment variables are strings ("PORT=8080").

To compute, sort, and process this information, you must convert values from one type to another. This process is called Type Conversion (or Type Casting).


Implicit vs. Explicit Conversion

Python handles type conversion in two distinct ways:

1. Implicit Conversion (Type Coercion)

Python automatically and safely converts types behind the scenes only when there is zero chance of data loss.

The most common example is mixing integers and floats in arithmetic:

integer_val = 10     # int
float_val = 4.5       # float

# Python automatically promotes 10 to 10.0:
result = integer_val + float_val

print(result)        # 14.5
print(type(result))  # <class 'float'>

Python will never implicitly convert between text strings and numbers:

# BROKEN: Python refuses to guess your intent
print("Total: " + 50)
# TypeError: can only concatenate str (not "int") to str

2. Explicit Conversion (Type Casting)

Explicit conversion is when you intentionally convert data using Python’s built-in constructor functions: int(), float(), str(), and bool().


1. Converting to Integers with int()

The int() function converts numbers and text strings into whole numbers:

# From a string of digits:
count = int("42")
print(count, type(count))  # 42 <class 'int'>

# From a boolean:
print(int(True))   # 1
print(int(False))  # 0

Converting Floats to Integers: Truncation

When you convert a float to an int, Python truncates the decimal portion completely (it chops off the numbers after the dot without rounding):

print(int(9.99))   # 9 (NOT 10!)
print(int(-4.85))  # -4

Pro-Tip: If you want standard mathematical rounding to the nearest whole number, use Python’s built-in round() function before converting: round(9.99) evaluates to 10.

The #1 int() Gotcha: Decimal Strings

You cannot convert a string containing a decimal point directly into an int:

# CRASHES with ValueError:
int("19.99")
# ValueError: invalid literal for int() with base 10: '19.99'

Because "19.99" contains a dot, Python’s integer parser rejects it. To fix this, convert the string to a float first, then cast to an int:

# Two-step safe conversion:
whole_dollars = int(float("19.99"))
print(whole_dollars)  # 19

Parsing Other Number Bases

You can pass a second argument to int() to parse numbers written in binary (base 2), octal (base 8), or hexadecimal (base 16):

# Binary to integer:
print(int("1010", 2))  # 10

# Hexadecimal to integer:
print(int("FF", 16))   # 255

2. Converting to Decimals with float()

The float() function converts integers and numeric strings into floating-point numbers:

# From an integer:
speed = float(60)
print(speed)  # 60.0

# From a numeric string:
pi_val = float("3.14159")
print(pi_val)  # 3.14159

# From scientific notation:
distance = float("1.5e4")
print(distance)  # 15000.0

3. Converting to Text with str()

The str() function is the most universal converter in Python. It can convert virtually any Python object into a human-readable text string:

age = 30
price = 19.95
is_member = True

# Convert numbers and booleans into text strings:
message = "User is " + str(age) + " years old."
print(message)  # User is 30 years old.

While concatenating with str() works, the modern, idiomatic Python standard is to use f-strings (formatted string literals), which automatically handle string conversion for you:

# Clean modern f-string (no manual str() calls needed!):
print(f"User is {age} years old and paid ${price}.")

4. Truthiness and Falsiness: Converting with bool()

Every object in Python has an inherent boolean value. When an object is placed inside an if statement or passed to bool(), Python evaluates its truthiness.

The rule in Python is very clean and intuitive:

The “Falsy” Values (Evaluate to False)

Any value that represents zero, empty, or nothing is considered False:

# All of these evaluate to False:
print(bool(0))        # Integer zero
print(bool(0.0))      # Float zero
print(bool(""))       # Empty string
print(bool(None))     # NoneType
print(bool([]))       # Empty list
print(bool({}))       # Empty dictionary
print(bool(set()))    # Empty set

The “Truthy” Values (Evaluate to True)

Virtually everything else is considered True:

  • Any non-zero number (1, -10, 0.001)
  • Any non-empty string ("hello", "0", " ")
  • Any collection with at least one item ([0], ["apple"])
print(bool(42))            # True
print(bool("Hello"))       # True
print(bool(" "))           # True (contains a space!)
print(bool(["anything"]))  # True

The Classic Beginner Trap: bool("False")

Look at this code carefully:

user_setting = "False"
print(bool(user_setting))  # True!

Why does bool("False") evaluate to True? Because "False" is a non-empty string with 5 characters! Python does not read the English meaning of the letters; it only checks if the string is empty or not.

If you need to parse a boolean string from user input or a configuration file, compare the string explicitly:

is_enabled = (user_setting.lower() == "true")
print(is_enabled)  # False

5. Handling Conversion Errors Gracefully

If you attempt to convert invalid text into a number, Python raises a ValueError:

user_text = "forty-two"

try:
    number = int(user_text)
    print("Number:", number)
except ValueError:
    print(f"Could not convert '{user_text}' into a valid integer.")

Output:

Could not convert 'forty-two' into a valid integer.

Using try ... except blocks (covered in depth in errors) protects your application from crashing when users enter invalid keystrokes.


Summary Checklist

FunctionConverts ToExampleOutput
int(x)Integerint("42")42
float(x)Floatfloat("3.14")3.14
str(x)Stringstr(100)"100"
bool(x)Booleanbool("")False
  • Implicit: Python only auto-converts when safe (e.g., int + float = float).
  • Truncation: int(9.99) drops the decimal to become 9.
  • Falsy: 0, "", None, and empty collections evaluate to False.
  • ValueError: Always be prepared for conversion failures when processing human input.

Congratulations on completing Stage 2: Variables & Data Types! You now command Python’s fundamental building blocks.

Next, advance to Stage 3: Strings & Text Processing, starting with comprehensive mastery of strings and text indexing.

Test your understanding of Type Conversion

Quick interactive practice questions with instant feedback.

Take Quiz →