Python Zero to Advanced #2: Variables, Data Types, Operators & f-strings
In Part 1 we installed Python and printed our first lines. Now we need a way to remember values and work with them. That is what variables, data types, and operators are for. We will finish with f-strings, the modern and most readable way to build text in Python.
Variables
A variable is a name that refers to a value. You create one with the assignment operator =. There is no need to declare a type first: Python figures it out from the value.
name = "Budi"
age = 28
height = 172.5
print(name, age, height)
age = age + 1 # reassign using the old value
print("Next year:", age)
x, y, z = 1, 2, 3 # multiple assignment
print(x, y, z)
x, y = y, x # swap without a temp variable
print(x, y)
Output:
Budi 28 172.5
Next year: 29
1 2 3
2 1
Naming rules: names may contain letters, digits, and underscores, cannot start with a digit, and are case-sensitive (age and Age are different). By convention Python uses snake_case for variables, like total_price, and UPPER_CASE for constants, like MAX_RETRIES.
Core data types
Every value in Python has a type. You can inspect it with the built-in type() function.
| Type | Example | Description |
|---|---|---|
int | 42, -7 | Whole numbers of any size |
float | 3.14, 2.0 | Decimal (floating-point) numbers |
str | "hello" | Text, in single or double quotes |
bool | True, False | Logical values |
NoneType | None | "No value" |
print(type(42))
print(type(3.14))
print(type("Siti"))
print(type(True))
print(type(None))
print(2 ** 100)
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'NoneType'>
1267650600228229401496703205376
Python integers never overflow: 2 ** 100 is computed exactly. Floats, however, follow the IEEE 754 standard and can show tiny rounding errors, which we will see shortly.
Operators
Arithmetic
a, b = 17, 5
print(a + b) # addition
print(a - b) # subtraction
print(a * b) # multiplication
print(a / b) # true division, always a float
print(a // b) # floor division
print(a % b) # remainder (modulo)
print(a ** 2) # power
print(0.1 + 0.2)
Output:
22
12
85
3.4
3
2
289
0.30000000000000004
The last line is the classic floating-point surprise. For money, use the decimal module or store amounts as integers (for example, cents or rupiah).
Comparison and logical
Comparison operators return a bool. Logical operators and, or, and not combine them. Python even lets you chain comparisons.
score = 78
print(score >= 75)
print(score == 100)
print(score != 100)
print(60 <= score < 80) # chained comparison
print(score > 50 and score < 70)
print(not score > 50)
Output:
True
False
True
True
False
False
Assignment shortcuts
balance = 100
balance += 50 # same as balance = balance + 50
balance -= 30
balance *= 2
print(balance)
Output:
240
Type conversion
Use int(), float(), str(), and bool() to convert between types. This matters a lot with input(), which always returns a string.
qty = "3"
print(qty * 2) # string repetition!
print(int(qty) * 2) # numeric multiplication
print(float("2.5") + 1)
print(str(100) + " points")
print(int(9.99)) # truncates, does not round
print(round(9.99))
print(bool(0), bool(""), bool("0"), bool([]))
Output:
33
6
3.5
100 points
9
10
False False True False
Note the last line: 0, empty strings, empty collections, and None are falsy. Almost everything else, including the string "0", is truthy.
f-strings
An f-string is a string literal prefixed with f. Anything inside {} is evaluated as a Python expression and inserted into the text. You can add a format spec after a colon.
name = "Siti"
price = 1250000
rate = 0.0725
items = 3
print(f"Hello, {name}!")
print(f"{name} bought {items} items")
print(f"Total: {price * items}")
print(f"Price: {price:,}") # thousands separator
print(f"Rate: {rate:.2%}") # percentage, 2 decimals
print(f"Pi approx: {22 / 7:.3f}") # 3 decimal places
print(f"[{name:>8}]") # right-align in 8 chars
print(f"[{name:<8}]") # left-align
print(f"{items=}") # debug format (3.8+)
Output:
Hello, Siti!
Siti bought 3 items
Total: 3750000
Price: 1,250,000
Rate: 7.25%
Pi approx: 3.143
[ Siti]
[Siti ]
items=3
f-strings are faster and far more readable than concatenation with + and str(), so prefer them whenever you build text.
Common mistakes
- Concatenating str and int:
"Age: " + 25raisesTypeError. Use an f-string orstr(25). - Confusing
=and==:=assigns,==compares. - Expecting
/to return an int:10 / 2is5.0. Use//for integer division. - Forgetting the
fprefix:"Hello {name}"prints the braces literally. - Shadowing built-ins: naming a variable
list,str, orinputhides the built-in function.
Exercise
Write a small receipt calculator: given a unit price, quantity, and a 11% tax rate, print the subtotal, tax, and total with thousands separators.
unit_price = 45000
quantity = 4
TAX_RATE = 0.11
subtotal = unit_price * quantity
tax = round(subtotal * TAX_RATE)
total = subtotal + tax
print(f"Subtotal : Rp{subtotal:>10,}")
print(f"Tax (11%): Rp{tax:>10,}")
print(f"Total : Rp{total:>10,}")
Output:
Subtotal : Rp 180,000
Tax (11%): Rp 19,800
Total : Rp 199,800
Try changing the quantity, or read it from input() (remember to convert it with int()).
Summary
- Variables are names bound to values; Python infers the type automatically.
- Core types:
int,float,str,bool, andNone. - Know the difference between
/,//, and%, and beware of float rounding. - Convert explicitly with
int(),float(),str(); format text with f-strings.
In Part 3 we will make programs that decide and repeat, using if/elif, for, while, and range().
Related articles
PostgreSQL Zero to Advanced #1: Introduction & Setup
Start the series by understanding what a relational database is, installing PostgreSQL locally, and getting comfortable with psql commands like \l, \c and \dt.
PHP Zero to Advanced #1: Introduction & Setup
Start your PHP journey: what PHP is, how to install PHP 8.2+, run the built-in development server, and write your very first script with echo.
Ruby on Rails Zero to Advanced #1: Ruby Basics
Start the Rails journey with the language underneath it: irb, variables, strings, puts vs p, and symbols explained with runnable examples.