Manuals / Python / Ch 3

A · SetupBeginner50 min read

3. Syntax, types & control flow

Python · 52 pages source format

Indentation, variables, strings, f-strings, if/for, lists, dicts. Enough to read test code and write helpers.

What you'll learn

  • Indentation rules
  • f-strings
  • if/elif/else
  • for loops
  • lists and dicts

Variables and f-strings

Dynamic typing — types exist at runtime. f-strings are the readable default for formatting.

username = "standard_user"
password = "secret_sauce"
print(f"Attempting login for {username}")

Do this now

Script that stores username/password and prints formatted login attempt.

Clear?

Control flow

if/elif/else for branching. for item in items for iteration. while sparingly.

Do this now

Loop over 3 invalid passwords; print whether each is empty or too short.

Clear?

Lists and dicts

Lists ordered, dicts keyed. List comprehensions when readable. dict.get(key, default) avoids KeyError.

admins = [u["name"] for u in users if u.get("role") == "admin"]

Do this now

users = [{"name":"A","role":"admin"},{"name":"B","role":"user"}]. Filter admins, print names.

Clear?

Checklist