Chapter 2 · Python Basics
Numbers, Text and True/False
- Page 4 of 20
- 5 min read
Almost all data an AI program handles is one of three things: numbers (scores, prices, token counts), text (prompts, documents, answers) or yes/no facts (is the reply finished? did the call fail?). Python gives each its own type.
Numbers: int and float
Whole numbers are int (integers); numbers with a decimal point are float. The arithmetic operators are what you expect, plus three useful extras:
print(7 + 3) # addition
print(7 - 3) # subtraction
print(7 * 3) # multiplication
print(7 / 2) # division always gives a float
print(7 // 2) # floor division: whole part only
print(7 % 2) # remainder (modulo)
print(2 ** 10) # power10
4
21
3.5
3
1
1024// and % come up often: // tells you how many whole groups fit (how many full pages of 10 results in 47 results?), and % what is left over (is a number even? n % 2 == 0).
A float surprise
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))
price_per_1k_tokens = 0.002
tokens_used = 12_500 # underscores make big numbers readable
cost = tokens_used / 1000 * price_per_1k_tokens
print(f"Cost: ${cost:.4f}")0.30000000000000004
0.3
Cost: $0.02500.1 + 0.2 is not exactly 0.3. Computers store floats in binary, where 0.1 cannot be written exactly — just as 1/3 cannot be written exactly as a decimal. This is true in every programming language. When you display money or scores, round them; when you compare floats, never use == on results of calculations.
Text: strings
A str (string) is text inside quotes. Single '…' and double "…" quotes work the same; triple quotes """…""" let text span several lines, which is handy for long prompts. Strings come with many built-in methods — functions attached to the value, called with a dot:
prompt = " Summarise this article in three bullet points. "
clean = prompt.strip() # remove spaces at both ends
print(clean)
print(len(clean)) # number of characters
print(clean.upper())
print(clean.lower())
print(clean.replace("three", "five"))
print(clean.startswith("Summarise"))
print("article" in clean) # is this text inside?
print(clean.split()[:3]) # split into words, keep the first 3Summarise this article in three bullet points.
46
SUMMARISE THIS ARTICLE IN THREE BULLET POINTS.
summarise this article in three bullet points.
Summarise this article in five bullet points.
True
True
['Summarise', 'this', 'article']Strings are immutable: methods like upper() do not change the original; they return a new string. That is why we store the result: clean = prompt.strip().
Indexing and slicing
Each character has a position, an index, starting at 0. Negative indexes count from the end. A slice [start:stop] takes a piece, and the stop position is not included:
word = "Python"
print(word[0]) # first character (counting starts at 0)
print(word[-1]) # last character
print(word[0:3]) # characters 0, 1, 2 (stop is not included)
print(word[2:]) # from index 2 to the endP
n
Pyt
thonf-strings: the best way to build text
Put an f before the quotes and you can drop values straight into the text with { }. After a colon you can format them:
name = "Nadia"
score = 87.456
tokens = 1234567
print(f"Hello, {name}!")
print(f"Score: {score:.1f}") # one decimal place
print(f"Tokens: {tokens:,}") # thousands separator
print(f"{name!r} scored {score:.0f}%")Hello, Nadia!
Score: 87.5
Tokens: 1,234,567
'Nadia' scored 87%You will build prompts for AI models this way all the time: f"Translate this into Bangla: {text}".
Converting between types
int(), float(), str() and bool() convert values. This matters because input() always returns text:
age_text = "21"
print(age_text + "1") # joining text
print(int(age_text) + 1) # converting to a number first
print(float("3.5") * 2)
print(str(42) + " tokens")
print(bool(0), bool(5), bool(""), bool("hi"))211
22
7.0
42 tokens
False True False TrueForget to convert and Python stops you with a TypeError — it refuses to guess whether you meant to add numbers or join text. The user typed 500:
tokens = input("How many tokens? ")
print(tokens + 100)How many tokens? 500
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(tokens + 100)
~~~~~~~^~~~~
TypeError: can only concatenate str (not "int") to strThe fix is int(tokens) + 100.
True or False: booleans
A bool is either True or False. Comparisons produce booleans, and and, or, not combine them:
tokens = 900
limit = 1000
print(tokens < limit)
print(tokens == 900) # == compares; = assigns
print(tokens != limit)
print(tokens > 0 and tokens < limit)
print(not tokens < limit)True
True
True
True
False| Operator | Means |
|---|---|
== / != | equal / not equal |
< <= > >= | less than, at most, greater than, at least |
and | True only if both sides are True |
or | True if at least one side is True |
not | flips True and False |
Note the last line of the bool() example earlier: 0 and empty text "" count as False (they are "falsy"); any other number or non-empty text counts as True. You will use this on the next pages: if answer: means "if the answer is not empty".
Try it yourself
- A model costs $0.003 per 1,000 tokens. Ask the user how many tokens they used and print the cost with 4 decimal places.
- Ask for a sentence and print how many words and how many characters it has.
- Print the first and last word of a sentence using
split()and indexes.