You’ll often want to turn one type into another — a number into a string for printing, or a string typed by the user into a number for maths. Python provides built-in functions for this.

The conversion functions

Each built-in type has a function with the same name:

FunctionTurns something into…
int()an integer
float()a float
str()a string
bool()a boolean

Numbers ↔ strings

The most common conversion in real programs:

# string to number
age_str: str = "30"
age: int = int(age_str)
print(age + 1)   # 31

price_str: str = "9.99"
price: float = float(price_str)
print(price * 2)   # 19.98

# number to string
count: int = 42
message: str = "Count is " + str(count)
print(message)   # Count is 42

Tip: you’ll usually use an f-string instead of + str(...). It’s shorter: f"Count is {count}".

What can go wrong

If the string can’t be parsed as a number, Python raises a ValueError:

int("hello")
ValueError: invalid literal for int() with base 10: 'hello'

int() is also strict — it won’t accept decimals in a string:

int("9.99")   # ValueError

To handle this, parse as float first:

price: int = int(float("9.99"))    # 9 — drops the decimal

We’ll see how to catch these errors in Section 9.

Between numeric types

x: float = 3.7
y: int = int(x)        # 3 — drops the decimal, doesn't round
z: float = float(5)    # 5.0

int(3.7) gives 3, not 4. To round properly:

y: int = round(3.7)    # 4

To and from boolean

bool() follows the truthy/falsy rules from the previous lesson:

print(bool(0))         # False
print(bool(1))         # True
print(bool(""))        # False
print(bool("Hello"))   # True
print(bool([]))        # False
print(bool([1, 2]))    # True

The reverse direction — int(True) or int(False) — gives 1 or 0:

print(int(True))     # 1
print(int(False))    # 0
print(str(True))     # 'True' — string version

Implicit conversion

Python sometimes converts types for you without being asked. The main example: in arithmetic, an int is promoted to a float when mixed:

result = 1 + 2.5   # int + float → float
print(result, type(result))   # 3.5 <class 'float'>

But Python does not convert strings automatically:

"Count: " + 42   # TypeError — you must call str(42) yourself

Some other languages would do this for you — Python deliberately doesn’t, because automatic conversions hide bugs.

A complete example

A small program that asks for a number and doubles it:

text: str = input("Enter a number: ")   # input always returns a string
number: float = float(text)
print(f"Doubled: {number * 2}")

The input() function always returns a string, even if the user types digits — so we have to convert it before doing maths. We’ll meet input properly in the next lesson.

What’s next

Type conversion handles the data you already have. Next, we’ll cover the other half — input and output: reading from the user and printing back to them.

Toggle theme (T)