Skip to content
Fullstack Launchpad

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.

By Published Updated 9 min readPython for Engineers Switching Languages

Built-in data types

GroupTypeHow to write itMutable?Can be a dict key?
Numbersint42, 1_000_000noyes
float3.14, 1e-3 (= 10⁻³ = 0.001)noyes
DecimalDecimal("0.1") (needs import)noyes
LogicboolTrue, False (capitalised)noyes
NothingNoneNonenoyes
Textstr"hi", 'hi', """multi-line""", f"{x}"noyes
bytesb"hi"noyes
Collectionslist[1, 2]yesno
tuple(1, 2), (1,)noyes (if its items are too)
dict{"a": 1}yesno
set{1, 2}, set()yesno

How some other languages compare

PythonJS / TSJavaGo
int (no size limit)number, bigintint, long (fixed 32/64 bit), BigIntegerint, int64 (fixed), math/big.Int
floatnumberdoublefloat64
Decimalnone built in (decimal.js library)BigDecimalnone built in (shopspring/decimal library)
boolbooleanbooleanbool
Nonenull, undefinednullnil
strstringStringstring
bytesUint8Array, Bufferbyte[][]byte
listArrayArrayListslice []T
tuplenone (an array stands in)closest is a recordnone (a struct, or multiple return values)
dictObject, MapHashMapmap[K]V
setSetHashSetnone (use map[T]struct{})

Basic syntax and variables

One assignment, taken apart:

python
max_retry: int = 3  # how many times to retry
PartMeaning
max_retrythe name, written in snake_case by convention
: inttype 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
3a 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, a for, 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 ...: (not else if), else:. No brackets around the condition.
python
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:

python
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:

python
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

WriteMeaningExample
/divide, always returns a float7 / 2 → 3.5
//divide, then round down (towards minus infinity)7 // 2 → 3
%remainder7 % 3 → 1
**power2 ** 10 → 1024
_ in a numberfor readability only1_000_000

// takes the normal quotient and rounds it down. 7 / 2 = 3.5, rounded down is 3. With negative numbers, watch out:

python
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

python
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:

python
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))
# prints: 0.3

Create a Decimal from a string. Created from a float:

python
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

WriteMeaning
"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".

WriteMeaningResult with name = "Orbit", n = 1234.5
{name}insert the valueOrbit
{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 decimals1,234.50
{n=}print the name and the value, handy for debugging (Python 3.8+)n=1234.5
python
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.

python
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

python
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:

python
print("xin chào".encode("utf-8"))
# prints: b'xin ch\xc3\xa0o'

True, False, None and "empty" values

python
print(bool([]))
# prints: False
print(bool("0"))
# prints: True
PythonJSJavaGo
and, or, not&&, ||, !&&, ||, !&&, ||, !
x is Nonex === nullx == nullx == nil
x or "default"x || "default"nonenone
a if condition else bcondition ? a : bcondition ? a : bnone, 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.

WriteResultNote
int("42")42a whole-number string to int
int("3.5")ValueErrora string with a decimal point must go through float first
int(3.9), int(-3.9)3, -3drops the fraction, does not round
round(2.5), round(3.5)2, 4rounds to the nearest even number
float("1e-3")0.001a string to float
str(42)'42'every value converts to a string
bool("False")Trueany non-empty string is true
int("ff", 16)255reads 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
python
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, then in checks whether the text is in the set.

Key takeaways

  • Assigning creates a variable. Python is dynamic but does not convert types for you: "1" + 1 is an error.
  • // rounds down, so -7 // 2 is -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, !r gives the developer's view, : starts the format, = prints the name too.
  • Empty [] and {} are false. {} is a dict; an empty set is set(). Compare with None using is.
  • Convert with int(), float(), str(). int() drops the fraction, round(2.5) is 2, bool("False") is True.

Sources