Python for Polyglots
Lesson 2 · Basics

Syntax for polyglots

Indentation replaces braces. Most other differences are renamed keywords.

You writePython writes
{ } blocks, ;a : then a 4-space indent; no semicolons
nullNone
true / falseTrue / False
&& || !and or not
else ifelif
c ? a : ba if c else b
i++i += 1
`Hi ${name}` / "Hi $name"f"Hi {name}"
for (i = 0; i < n; i++)for i in range(n):
switchmatch (more powerful, covered later)
// comment# comment
Math.pow(2, 8)2 ** 8
7 / 2 (int division in Java)7 / 2 → 3.5; 7 // 2 → 3
The same function
def describe_age(name: str, age: int) -> str:
    if age < 0:
        return "invalid"
    kind = "adult" if age >= 18 else "minor"
    return f"{name}: {kind}"

Dynamic, but strongly typed

Like JS and PHP, Python variables have no declared type. Unlike JS and PHP, Python doesn't silently convert between types. "1" + 1 is an error, so you convert explicitly with int() or str().

Type hints (name: str) look like TypeScript, but Python ignores them at runtime. A checker such as pyright or mypy enforces them, the same way tsc does for TS.

Truthiness

Empty things are falsy: 0, "", [], {}, set(), None. So you write if not items: instead of if len(items) == 0.

Experiment
print(7 / 2, 7 // 2, 7 % 2, 2 ** 10)
print(True and not False)

for value in [0, "", [], {}, None, "0", [0]]:
    print(repr(value), "->", bool(value))

x = 5
print("big" if x > 3 else "small")
Quiz: What happens?
print("1" + 1)
Quiz: What does this print?
print(bool("0"), bool([]), bool([0]))
Exercise 1: Repeat a greeting

Return a list containing "Hi <name>" repeated times times.

greet("Ana", 3) → ["Hi Ana", "Hi Ana", "Hi Ana"]

Multiplying a list repeats it: [0] * 3 → [0, 0, 0]. The same works for strings: "ab" * 2 → "abab".