Skip to content

Type Casting & Truthiness

Type Casting is the process of converting an object from one data type to another. Because Python is Strongly Typed, it will not perform risky conversions automatically (like adding a string "5" to a number 5). You must be explicit about your intent.


Python only performs implicit conversion when it is “safe”—meaning no data will be lost. This usually happens when mixing integers and floats.

x = 10 # int
y = 2.5 # float
z = x + y # 12.5 (Python promotes x to float automatically)

You use the constructor functions of the class you want to convert to.

  • int(x): Converts to integer (truncates floats).
  • float(x): Converts to floating point.
  • str(x): Converts to string.
  • bool(x): Converts to boolean.

This is one of the most important concepts in Python logic. Every object in Python has an inherent boolean value. You don’t need a comparison to use an object in an if statement.

Only these values evaluate to False:

  1. Constants: None and False.
  2. Zeroes: 0, 0.0, 0j.
  3. Empty Collections: "" (empty string), [] (empty list), {} (empty dict), set().

Everything else is Truthy.

truth_check.py
def check(val):
if val:
print(f"{repr(val)} is Truthy")
else:
print(f"{repr(val)} is Falsy")
check(0) # Falsy
check(0.1) # Truthy
check([]) # Falsy
check(" ") # Truthy (It contains a space!)

How does Python know if an object is True or False?

When you call bool(obj) or use an object in an if statement, Python follows this priority:

  1. It looks for a method named __bool__() on the object’s class and uses its return value.
  2. If __bool__ isn’t defined, it looks for __len__(). If the length is 0, it’s False; otherwise, it’s True.
  3. If neither exists, the object is always True.

The input() function always returns a str. To do math, you must cast it.

age = int(input("Enter age: "))

Casting a float to an int does not round. it simply chops off the decimal (truncation).

print(int(9.99)) # Output: 9

To round properly, use the built-in round() function instead.

You cannot add an int to a str. You must cast the number to a string first.

score = 100
# print("Score: " + score) # TypeError
print("Score: " + str(score)) # Correct

FromToMethodResult
floatintint(3.8)3 (Truncated)
intfloatfloat(5)5.0
strintint("10")10
anystrstr(True)"True"
listboolbool([])False