Python · Lesson 1

Python Basics

How Python reads (indentation, names, dynamic types), its numbers and strings, truthiness and None, == versus is, and the loops and conditionals everything else is built from.

7 min read

In short

  • Indentation is the block: four spaces
  • / is a float, // floors, ints never overflow
  • f-strings and slices for text
  • Empty means falsy; check None with is
  • Loop over things; else means no break

Python is the language interviewers reach for when they want to talk about the problem rather than the syntax, and the one data, scripting and backend teams write every day. It is dynamically typed like JavaScript (values have types, variables don't), but it is much stricter about mixing them: "3" + 4 is an error, not "34". It reads almost like pseudocode, and the few rules that make it read that way are what this topic is about.

If you're coming from JavaScript, TypeScript or C#, the big differences are: indentation is the syntax (no braces), None/True/False are capitalised, integers never overflow, / always gives a float, and there's no ++. Type hints (def f(x: int) -> str) exist and the lessons use them, but Python doesn't check them at runtime: they're for readers and tools.

Every python snippet below has a ▶ Try button. It runs real CPython 3.13 in your browser. Guess the output first, then run it.

Indentation is the block

A colon opens a block, and the indented lines under it are the block. Four spaces per level is the universal convention.

▶ Try
def describe(n: int) -> str:
    if n < 0:
        return "negative"
    elif n == 0:
        return "zero"
    else:
        return "positive"


for n in [-2, 0, 5]:
    print(n, describe(n))

There's no switch fallthrough to worry about and no braces to balance. The price is that mixing tabs and spaces, or indenting one line by three spaces, is a syntax error. Let the editor indent for you.

pass is the statement that does nothing, for a block you haven't written yet:

▶ Try
def todo() -> None:
    pass


print(todo())

A function with no return returns None, which is what that prints.

Names point at values

A variable is a name bound to a value. Assignment never copies; it binds another name to the same value.

▶ Try
a = [1, 2, 3]
b = a          # the same list, not a copy
b.append(4)
print(a)

x = 10
x = "ten"      # fine: names don't have types
print(type(x).__name__)

Python has no const. By convention, a name in UPPER_CASE is a constant nobody should reassign. Several assignments can happen at once, which is how you swap without a temporary:

▶ Try
first, second = 1, 2
first, second = second, first
print(first, second)

Numbers

Python has two everyday number types, int and float, and the rules differ from JavaScript's in useful ways.

▶ Try
print(7 / 2)       # true division: always a float
print(7 // 2)      # floor division: rounds DOWN
print(-7 // 2)     # down means towards minus infinity: -4, not -3
print(7 % 3, -7 % 3)   # the remainder takes the sign of the divisor
print(2 ** 10)     # power
print(2 ** 100)    # ints never overflow

// and % always agree: a == (a // b) * b + a % b. That makes % the right tool for wrapping around (a clock, a ring buffer, a day of the week) even with negative numbers, where JavaScript's % would give a negative result.

Floats are the same IEEE 754 doubles as in every language, with the same rounding surprises:

▶ Try
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(round(2.5), round(3.5))    # banker's rounding: halves go to the even neighbour
print(f"{2.675:.2f}")            # 2.675 is really 2.67499999..., so it prints 2.67

For money, store whole cents in an int (or use decimal.Decimal), never a float.

Converting is explicit. int("42") parses, int(3.9) truncates towards zero, str(42) formats, and a bad conversion raises an error instead of producing NaN:

▶ Try
print(int("42") + 1, int(3.9), int(-3.9), float("1.5"))
try:
    int("4.5")
except ValueError as e:
    print("ValueError:", e)

Strings

Strings are immutable sequences of Unicode characters. Single and double quotes mean the same thing, and triple quotes span lines. f-strings are the way to build them:

▶ Try
name, items, total = "Ann", 3, 41.5
print(f"{name} bought {items} items for ${total:.2f}")
print(f"{items:>5}|{name:<5}|")      # width and alignment
print(f"{1234567:,}")                # thousands separator
print(f"{total=}")                    # name=value, handy for debugging

Indexing and slicing work on strings, lists, tuples and ranges. A slice is [start:stop:step], stop is excluded, negative indexes count from the end, and slices never raise for out-of-range bounds:

▶ Try
s = "interview"
print(s[0], s[-1])        # first and last
print(s[:5], s[5:])       # the two halves around index 5
print(s[::-1])            # reversed
print(s[100:])            # empty, not an error

The methods you'll use constantly: strip, lower/upper, split/join, replace, startswith, endswith, find, and the in operator for "contains":

▶ Try
line = "  Alice, Bob ,Carol  "
names = [part.strip() for part in line.split(",")]
print(names)
print(" | ".join(names))
print("Bob" in names, "ob" in "Bob", "carol".title())

Because strings are immutable, every method returns a new string. s.upper() on its own line does nothing useful; assign the result.

Truthiness, None, and == versus is

Every value is either truthy or falsy. The falsy ones are: False, None, zero of any number type, and empty containers and strings ("", [], {}, set(), ()). Everything else is truthy, including the string "False" and the string "0".

▶ Try
for value in [0, 0.0, "", "0", "False", [], [0], None, {}]:
    print(repr(value), bool(value))

None is Python's single "no value" (there's no separate undefined). Check for it with is None, not with truthiness, when 0 or an empty string are valid values:

▶ Try
def label(count: int | None) -> str:
    if count is None:
        return "unknown"
    return f"{count} items"


print(label(None), "/", label(0))

== compares values; is compares identity (the same object). Use is only for None (and sentinels you created), and == for everything else:

▶ Try
a = [1, 2]
b = [1, 2]
print(a == b, a is b)
c = a
print(c is a)

and and or return one of their operands, not necessarily a bool, which is why name or "anonymous" works as a default. not always returns a bool. Comparisons chain, so 0 <= i < len(xs) means what it says.

▶ Try
print("" or "anonymous", "Ann" or "anonymous")
print(0 and "never evaluated", 3 and "both truthy")
i = 4
print(0 <= i < 10)

Loops

for loops over any iterable: a list, a string, a range, a dict (its keys), a file. There's no C-style for (i = 0; ...); use range(stop) or range(start, stop, step) when you need numbers, and enumerate when you need the index too.

▶ Try
for i in range(3):
    print("tick", i)

for i, ch in enumerate("abc", start=1):
    print(i, ch)

n = 27
steps = 0
while n != 1:
    n = n // 2 if n % 2 == 0 else 3 * n + 1
    steps += 1
print("steps:", steps)

break leaves the loop and continue skips to the next item. A loop can also have an else, which runs only when the loop finished without break. It's exactly the "searched and didn't find it" case:

▶ Try
def first_negative(xs: list[int]) -> int | None:
    for x in xs:
        if x < 0:
            print("found", x)
            break
    else:
        print("none found")
        return None
    return x


first_negative([3, -1, 4])
first_negative([1, 2])

The conditional expression is a if condition else b (Python's ternary), and the walrus operator := assigns inside an expression, which saves a line in while loops that read until something runs out.

Functions, briefly

def defines a function. Parameters can have defaults, and callers can pass arguments by name. The Functions and Closures topic goes deep; this is enough for the exercises here:

▶ Try
def greet(name: str, greeting: str = "Hello") -> str:
    return f"{greeting}, {name}!"


print(greet("Ann"))
print(greet("Ann", greeting="Hi"))

Errors

A failure raises an exception, and try/except catches it. You raise your own with raise, and the built-in exception types already cover most needs: ValueError for a bad value of the right type, TypeError for the wrong type, KeyError and IndexError for missing keys and positions.

▶ Try
def parse_age(text: str) -> int:
    age = int(text)          # may raise ValueError on its own
    if age < 0:
        raise ValueError(f"age can't be negative: {age}")
    return age


for raw in ["42", "-1", "abc"]:
    try:
        print(parse_age(raw))
    except ValueError as e:
        print("bad input:", e)

The Errors and Context Managers topic covers designing exceptions properly. In the exercises, when the prompt says "raise ValueError", the tests check the type and usually part of the message.

How the exercises work

Each exercise gives you a starter with the function signatures and raise NotImplementedError bodies. Fill them in and press Run (Ctrl/Cmd + Enter). The tests call your functions and check the results with expect(...), which you can read in the Tests tab. print output shows under the results, so printing is a fine way to debug.

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app