LearnContact
Lesson 925 min read

Type Casting

Learn how Python converts values between types automatically and how to convert them explicitly using int(), float(), str(), and bool().

Introduction

Not every value arrives in the type you need. User input always comes in as text, a price might be stored as a string in a file, or you might need to display a number as part of a sentence. Type casting is how you convert a value from one data type to another.

In this lesson, you will learn the difference between conversions Python performs automatically and conversions you request explicitly, along with the common pitfalls that trip up beginners.

What You Will Learn
  • The difference between implicit and explicit type conversion.
  • How to explicitly cast using int(), float(), str(), and bool().
  • Common errors that happen when casting invalid values.
  • Python's truthiness rules for converting any value to bool().

What is Type Casting?

Type casting (also called type conversion) means changing a value from one data type into another — for example, turning the text "25" into the number 25, or turning the number 25 into the text "25".

Implicit Conversion

Python converts a value automatically, without you asking, usually to avoid losing information.

Explicit Casting

You deliberately convert a value using a function like int(), float(), str(), or bool().

Implicit Type Conversion

Implicit conversion happens automatically when Python combines two different numeric types in one expression. Python always converts the "smaller" type up to the "larger" one to avoid losing precision — so an int combined with a float becomes a float.

whole = 5
decimal = 2.5

result = whole + decimal
print(result)
print(type(result))
Output
7.5
<class 'float'>
Why float Wins

If Python converted 2.5 down to an int, it would lose the .5 and give a wrong answer. Converting 5 up to 5.0 loses nothing, so Python always widens int to float automatically.

Explicit Type Casting

Explicit casting is when you request a conversion yourself, using one of Python's built-in casting functions. This is necessary whenever Python cannot or will not guess the conversion for you — for example, converting user input text into a number.

int(value)

Converts a value into a whole number.

float(value)

Converts a value into a decimal number.

str(value)

Converts a value into text.

bool(value)

Converts a value into True or False.

Casting to int()

int() converts a float (by dropping everything after the decimal point, not rounding) or a numeric string into a whole number.

print(int(9.8))
print(int(9.2))
print(int("42"))
Output
9
9
42
int() Truncates, It Does Not Round

int(9.8) gives 9, not 10. int() always cuts off the decimal part rather than rounding to the nearest whole number. Use the built-in round() function if you need rounding.

Casting to float()

float() converts an int or a numeric string into a decimal number.

print(float(9))
print(float("3.5"))
print(float("10"))
Output
9.0
3.5
10.0

Casting to str()

str() converts almost any value into its text representation — useful when you need to combine a number with text using +.

age = 16
message = "I am " + str(age) + " years old."
print(message)
Output
I am 16 years old.
A Simpler Alternative

While str() works well here, f-strings (covered in a later lesson) let you write f"I am {age} years old." without calling str() at all.

Casting to bool() and Truthiness

bool() converts any value into True or False based on Python's truthiness rules. Most values are considered "truthy," but a specific set of values are considered "falsy."

print(bool(0))
print(bool(0.0))
print(bool(""))
print(bool([]))
print(bool({}))
print(bool(None))
print(bool(1))
print(bool("hello"))
Output
False
False
False
False
False
False
True
True
Falsy ValuesEverything Else is Truthy
0, 0.0Any non-zero number, e.g. 1, -5, 0.1
"" (empty string)Any non-empty string, e.g. "no"
[] (empty list)Any non-empty list, e.g. [0]
{} (empty dict)Any non-empty dict
None

Common Casting Pitfalls

Casting fails loudly, not silently — Python raises an error rather than guessing what you meant. Two mistakes catch almost every beginner at some point.

Casting a decimal string directly to int()
age = int("16.5")  # ValueError!
Casting a non-numeric string to int() or float()
value = int("hello")  # ValueError!
The Correct Fix
text_value = "16.5"

# Wrong: int(text_value) raises ValueError
correct = int(float(text_value))
print(correct)
Output
16

Common Mistakes

Avoid These Mistakes
  • Calling int("3.5") directly — this raises ValueError; go through float() first.
  • Trying to cast a word like "hello" to a number.
  • Forgetting that int() truncates rather than rounds.
  • Assuming an empty string, list, or dict is "truthy" — they are all falsy.
  • Forgetting that "0" (a non-empty string containing a zero) is actually truthy, since any non-empty string is truthy.

Best Practices

  • Always cast input() results before doing math with them.
  • Route decimal-looking strings through float() before int().
  • Wrap risky casts in try/except once you learn exception handling, to handle bad input gracefully.
  • Use bool() intentionally when you want to test if something is empty or missing.
  • Prefer f-strings over str() concatenation once you learn them, for cleaner code.

Frequently Asked Questions

What is the difference between implicit and explicit conversion?

Implicit conversion happens automatically, such as int + float becoming float. Explicit conversion is something you request yourself using int(), float(), str(), or bool().

Why does int("3.5") raise an error?

int() expects a string that looks like a whole number. Since "3.5" contains a decimal point, you must convert it with float() first, then pass that result to int().

Is "0" (a string) truthy or falsy?

Truthy. Only an empty string "" is falsy — any non-empty string, including "0" or "False", is considered truthy.

What values are considered falsy in Python?

0, 0.0, "", [], {}, and None are all falsy. Every other value is considered truthy.

Can I convert a list directly to a string with str()?

Yes, str([1, 2, 3]) gives the text "[1, 2, 3]", though this is mainly useful for printing or debugging, not for meaningful text processing.

Key Takeaways

  • Type casting converts a value from one data type to another.
  • Implicit conversion happens automatically, such as int + float becoming float.
  • Explicit casting uses int(), float(), str(), and bool().
  • int() truncates decimals rather than rounding, and cannot parse decimal-point strings directly.
  • bool() follows truthiness rules — 0, 0.0, "", [], {}, and None are all falsy; everything else is truthy.

Summary

Type casting lets you move values between types safely and predictably, whether Python does it for you implicitly or you request it explicitly with int(), float(), str(), or bool(). Understanding truthiness and the common casting pitfalls will save you from confusing errors down the road.

Next, you will learn about Python's operators — the symbols that let you perform calculations, comparisons, and logical checks on your values.

Lesson 9 Completed
  • You understand implicit versus explicit type conversion.
  • You can cast values using int(), float(), str(), and bool().
  • You know the common pitfalls that raise ValueError.
  • You are ready to learn Python's operators.
Next Lesson →

Operators