Conversion and Type Built-ins

Built-in Functions

Conversion and Type Built-ins

In this tutorial, we'll use int(), float(), str(), bool(), type(), and isinstance().

Some built-in functions help you convert values or inspect their types.

int()

int() converts suitable values into integers:

age_text = "12"
age = int(age_text)

print(age + 1)

It works when the text looks like a whole number. int("12.5") does not work because that is not an integer string.

float()

float() converts suitable values into decimal numbers:

price_text = "4.99"
price = float(price_text)

print(price * 2)

str()

str() converts a value into text:

score = 95
message = "Score: " + str(score)

print(message)

F-strings often make this easier:

print(f"Score: {score}")

bool()

bool() converts a value to True or False:

print(bool(""))
print(bool("hello"))
print(bool(0))
print(bool(5))

Empty values are often false. Non-empty values are often true.

type() and isinstance()

Use type() to inspect:

print(type(42))

Use isinstance() to check:

print(isinstance(42, int))

When These Are Useful

Conversion functions are especially useful with user input, because input() always gives you a string.

quantity = int(input("Quantity: "))

Type-checking functions are most useful while debugging or when accepting data from somewhere uncertain.

Practice

Start with "25" and "3.50". Convert them into useful number types and print their types.