Python for AIPython for AI
Python Basics

Type conversion

Change values from one type to another

Data often arrives as the wrong type. A number typed by a user arrives as text, and a price read from a file is a string. Type conversion fixes that.

What is type conversion?

Type conversion (also called casting) means turning a value of one type into another type. Python gives you a function for each main type.

FeatureConverts toExampleResult
int()whole numberint("42")42
float()decimal numberfloat("3.5")3.5
str()textstr(99)"99"
bool()True / Falsebool(0)False
The four conversion functions you'll use most.

Checking a type

Before converting, it helps to know what you have. Use type().

python
print(type(10))      # <class 'int'>
print(type(10.0))    # <class 'float'>
print(type("10"))    # <class 'str'>
print(type(True))    # <class 'bool'>

Text to numbers

This is the conversion you'll do most. You can't do math with text, so convert first.

python
a = "5"
b = "3"

print(a + b)             # 53  (joins text!)
print(int(a) + int(b))   # 8   (real math)

price = float("19.99")
print(price * 2)         # 39.98
int() only accepts text that looks like a whole number. int("3.5") and int("hello") both raise a ValueError. Use float() for decimals.

Numbers to text

Use str() when you need to join a number to other text with +. With f-strings, Python does this for you.

python
tokens = 512

print("Used " + str(tokens) + " tokens")
print(f"Used {tokens} tokens")   # same result, no str() needed

Between int and float

python
print(float(7))     # 7.0
print(int(7.9))     # 7   (cuts off the decimals, no rounding)
print(round(7.9))   # 8   (use round() to round properly)

Converting to booleans

bool() follows a simple rule. "Empty" or zero values become False, and everything else becomes True.

python
print(bool(0))        # False
print(bool(""))       # False  (empty string)
print(bool([]))       # False  (empty list)
print(bool(42))       # True
print(bool("hello"))  # True
print(bool("False"))  # True   (it's a non-empty string!)

Real example: settings from text

Configuration values, like those from environment variables, always come in as strings. Convert them before use.

python
max_tokens_text = "300"
temperature_text = "0.7"

max_tokens = int(max_tokens_text)
temperature = float(temperature_text)

print(max_tokens + 100)   # 400
print(temperature * 2)    # 1.4

Common mistakes

  • Adding a number to a string: "Age: " + 30 raises a TypeError. Convert with str() or use an f-string.
  • Using int() on decimal text like "2.5". Use float() first.
  • Expecting bool("False") to be False. Any non-empty string is True.

What's next?

Now that you can convert types, you're ready to read input from a user. Everything a user types arrives as a string.