2. Variables & data types¶
Beginner · 7 min read
A variable is a name that points to a value. Python works out the type from the value — you don't declare it.
2.1 Variables¶
model = "gpt-4o-mini" # create a variable by assigning a value
max_tokens = 500
max_tokens = 800 # reassigning replaces the old value
print(model, max_tokens) # → gpt-4o-mini 800
# Naming rules: letters, digits and _, can't start with a digit, case-sensitive.
# Convention: snake_case for variables and functions, UPPER_CASE for constants.
API_TIMEOUT = 30
2.2 Numbers: int and float¶
tokens = 1200 # int: whole numbers (any size)
price = 0.15 # float: decimals
print(7 / 2) # → 3.5 true division always gives a float
print(7 // 2) # → 3 floor division
print(7 % 2) # → 1 remainder
print(2 ** 10) # → 1024 power
print(round(0.12345, 2)) # → 0.12
2.3 Strings: str¶
greeting = "Hello" # single or double quotes — both are fine
multi = """Line one
Line two""" # triple quotes for multi-line text
print(len(greeting)) # → 5
print(greeting + " world") # → Hello world
print("ab" * 3) # → ababab
Strings get their own page: 4. Strings.
2.4 Booleans and None¶
is_streaming = True # bool: True or False (capitalised)
api_key = None # None means "no value yet"
print(is_streaming and api_key is None) # → True
print(bool(0), bool(""), bool([])) # → False False False empty/zero values are "falsy"
print(bool("hi"), bool(5)) # → True True
Use is None (not == None) to check for None.
2.5 Checking and converting types¶
print(type(3.0)) # → <class 'float'>
print(isinstance(5, int)) # → True
# Converting: useful when reading numbers from text (input, files, environment variables)
print(int("42") + 1) # → 43
print(float("0.7")) # → 0.7
print(str(100) + "%") # → 100%
int("hello") raises a ValueError — handling errors is covered in 8. Files, JSON & errors.
Why it matters for GenAI
Settings such as temperature or MAX_TOKENS often arrive as strings from environment
variables or config files — convert them with float() / int() before passing them to an API.
Practice¶
- Store a model name, a temperature (
0.2) and a max-token limit in variables and print them on one line. - Convert the string
"1500"to a number and work out how many 500-token chunks it holds using//.