Python Data Types and Basic Syntax #1.1
Python has built-in types for numbers, text, truth values and None. Assigning creates a variable, but Python does not convert between types for you.
Built-in data types
| Group | Type | How to write it | Mutable? | Can be a dict key? |
|---|---|---|---|---|
| Numbers | int | 42, 1_000_000 | no | yes |
float | 3.14, 1e-3 (= 10⁻³ = 0.001) | no | yes | |
Decimal | Decimal("0.1") (needs import) | no | yes | |
| Logic | bool | True, False (capitalised) | no | yes |
| Nothing | None | None | no | yes |
| Text | str | "hi", 'hi', """multi-line""", f"{x}" | no | yes |
bytes | b"hi" | no | yes | |
| Collections | list | [1, 2] | yes | no |
tuple | (1, 2), (1,) | no | yes (if its items are too) | |
dict | {"a": 1} | yes | no | |
set | {1, 2}, set() | yes | no |
How some other languages compare
| Python | JS / TS | Java | Go |
|---|---|---|---|
int (no size limit) | number, bigint | int, long (fixed 32/64 bit), BigInteger | int, int64 (fixed), math/big.Int |
float | number | double | float64 |
Decimal | none built in (decimal.js library) | BigDecimal | none built in (shopspring/decimal library) |
bool | boolean | boolean | bool |
None | null, undefined | null | nil |
str | string | String | string |
bytes | Uint8Array, Buffer | byte[] | []byte |
list | Array | ArrayList | slice []T |
tuple | none (an array stands in) | closest is a record | none (a struct, or multiple return values) |
dict | Object, Map | HashMap | map[K]V |
set | Set | HashSet | none (use map[T]struct{}) |
Basic syntax and variables
One assignment, taken apart:
max_retry: int = 3 # how many times to retry
| Part | Meaning |
|---|---|
max_retry | the name, written in snake_case by convention |
: int | type hint, optional: for readers and tools (mypy, IDEs); Python does not check it at run time |
= | assignment: evaluate the right side first, then bind the name on the left to the result. The first assignment creates the variable; there is no declaration keyword |
3 | a value, or any expression: a + b, len(items), a function call |
# ... | a comment, from # to the end of the line |
Two rules for every Python file:
- One statement per line, no
;needed. - A block (the body of an
if, afor, a function) starts with:and is indented (4 spaces by convention), not wrapped in{}. Wrong indentation is a syntax error. - A condition is written
if ...:,elif ...:(notelse if),else:. No brackets around the condition.
def greet(name):
if name:
return f"Hello {name}"
return "Hello"
print(greet("Orbit"))
# prints: Hello Orbit
print(greet("")) # an empty string counts as false
# prints: Hello
Common forms of assignment:
count = 0
MAX_RETRY = 3 # a "constant" is only an upper-case convention, it can still be reassigned
a, b = 1, 2 # assign several names at once
count = "zero" # the same name bound to a value of another type: allowed
Python is dynamically typed (a name has no fixed type) but strongly typed (it does not convert types for you). Python raises an error at run time:
print(int("1") + 1)
# prints: 2
print("1" + 1)
# error: TypeError: can only concatenate str (not "int") to str
Numbers: int, float, Decimal
Division and power operators
| Write | Meaning | Example |
|---|---|---|
/ | divide, always returns a float | 7 / 2 → 3.5 |
// | divide, then round down (towards minus infinity) | 7 // 2 → 3 |
% | remainder | 7 % 3 → 1 |
** | power | 2 ** 10 → 1024 |
_ in a number | for readability only | 1_000_000 |
// takes the normal quotient and rounds it down. 7 / 2 = 3.5, rounded down is 3. With negative numbers, watch out:
print(-7 // 2)
# prints: -4
-7 / 2 = -3.5. Rounded down (towards minus infinity) it is -4, not -3.
Why 0.1 + 0.2 is not 0.3
print(0.1 + 0.2)
# prints: 0.30000000000000004
print(0.1 + 0.2 == 0.3)
# prints: False
float stores numbers in the IEEE 754 64-bit format ("double"). The format stores numbers in binary. In binary, 0.1 has infinitely many digits (like 1/3 = 0.333… in decimal), so the machine has to round it. Add two rounded numbers and the error shows.
Decimal: exact decimal numbers, for money
Decimal stores numbers in base ten, so 0.1 is stored as exactly 0.1:
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))
# prints: 0.3
Create a Decimal from a string. Created from a float:
from decimal import Decimal
print(Decimal(0.1))
# prints: 0.1000000000000000055511151231257827021181583404541015625
The reason: Python reads 0.1 as a float first (already rounded in binary), and only then does Decimal receive that slightly wrong number. Decimal copies every digit of it faithfully.
Money in a real system: use Decimal created from a string, or store an integer in the smallest unit (cents, đồng). Never a float.
Strings: str, f-string, bytes
Ways to write a string
| Write | Meaning |
|---|---|
"hi" or 'hi' | the same; pick one style and keep it |
"""...""" | multi-line string (docstrings, LLM prompts) |
f"..." | f-string: a string with expressions inside, like a JS template literal `${x}`, Java String.format or Go fmt.Sprintf |
r"..." | raw string: \ is not processed, used for regex |
b"..." | bytes, not text |
f-string: what goes inside {}
The f before the quote tells Python: "the parts inside {} are expressions; evaluate them and insert the result".
| Write | Meaning | Result with name = "Orbit", n = 1234.5 |
|---|---|---|
{name} | insert the value | Orbit |
{name!r} | insert the repr form: the developer's view, strings keep their quotes | 'Orbit' |
{n:,.2f} | after : comes the format: , groups thousands, .2f keeps two decimals | 1,234.50 |
{n=} | print the name and the value, handy for debugging (Python 3.8+) | n=1234.5 |
name = "Orbit"
n = 1234.5
print(f"Hello {name}")
# prints: Hello Orbit
print(f"{n:,.2f}")
# prints: 1,234.50
print(f"{n=}")
# prints: n=1234.5
!r helps in logs: you can see an empty string '' or stray spaces ' Orbit ' that a plain print hides.
from decimal import Decimal
print(str("Orbit"))
# prints: Orbit
print(repr("Orbit"))
# prints: 'Orbit'
print(str(Decimal("0.1")))
# prints: 0.1
print(repr(Decimal("0.1")))
# prints: Decimal('0.1')
Common operations
print("a,b,c".split(","))
# prints: ['a', 'b', 'c']
print("-".join(["a", "b"]))
# prints: a-b
print(repr(" hi ".strip()))
# prints: 'hi'
print("py" in "python")
# prints: True
Strings are immutable: s[0] = "X" raises an error. To join many pieces use "".join(parts), not += in a loop.
str and bytes
str is text. bytes is raw bytes (network data, binary files, input to a hash function). Converting between them always names an encoding:
print("xin chào".encode("utf-8"))
# prints: b'xin ch\xc3\xa0o'
True, False, None and "empty" values
print(bool([]))
# prints: False
print(bool("0"))
# prints: True
| Python | JS | Java | Go |
|---|---|---|---|
and, or, not | &&, ||, ! | &&, ||, ! | &&, ||, ! |
x is None | x === null | x == null | x == nil |
x or "default" | x || "default" | none | none |
a if condition else b | condition ? a : b | condition ? a : b | none, use if |
Compare with None using is None, never == None.
Type casting
Python does not convert between strings and numbers for you (strong typing, see above). To convert, call the type like a function: int(...), float(...), str(...). You need it whenever data arrives as text: a query string, an environment variable, a CSV file.
| Write | Result | Note |
|---|---|---|
int("42") | 42 | a whole-number string to int |
int("3.5") | ValueError | a string with a decimal point must go through float first |
int(3.9), int(-3.9) | 3, -3 | drops the fraction, does not round |
round(2.5), round(3.5) | 2, 4 | rounds to the nearest even number |
float("1e-3") | 0.001 | a string to float |
str(42) | '42' | every value converts to a string |
bool("False") | True | any non-empty string is true |
int("ff", 16) | 255 | reads the string in base 16 |
list("abc") | ['a', 'b', 'c'] | turns any sequence into a list |
set([1, 1, 2]) | {1, 2} | turns it into a set, dropping duplicates |
raw = "42"
print(int(raw) + 1)
# prints: 43
print(int(float("3.5")))
# prints: 3
print(round(2.5), round(3.5))
# prints: 2 4
print(1 + 2.0, True + 1)
# prints: 3.0 2
print(bool("False"), bool(""))
# prints: True False
def parse_bool(text):
return text.strip().lower() in {"1", "true", "yes"}
print(parse_bool("False"), parse_bool(" TRUE "))
# prints: False True
print(int("3.5"))
# error: ValueError: invalid literal for int() with base 10: '3.5'
text.strip()removes surrounding whitespace,.lower()lowercases it, theninchecks whether the text is in the set.
Key takeaways
- Assigning creates a variable. Python is dynamic but does not convert types for you:
"1" + 1is an error. //rounds down, so-7 // 2is-4./always returns a float.- Floats drift because they are stored in binary. Money uses
Decimal("...")from a string, or an integer in the smallest unit. - f-string:
f"{x}"inserts a value,!rgives the developer's view,:starts the format,=prints the name too. - Empty
[]and{}are false.{}is a dict; an empty set isset(). Compare withNoneusingis. - Convert with
int(),float(),str().int()drops the fraction,round(2.5)is2,bool("False")isTrue.
Sources
- Built-in Types (opens in a new tab): numbers, strings, list, dict, set, truth values.
- Floating Point Arithmetic: Issues and Limitations (opens in a new tab): why 0.1 is not exact.
- decimal (opens in a new tab), f-strings and the format spec (opens in a new tab).
- Every example with a
# printsline was run on Python 3.11.9.
