3 The Quick Python overview
This chapter offers a fast, big-picture tour of Python designed to give you a feel for the language’s syntax, semantics, capabilities, and guiding philosophy before diving into details later. It encourages an initial skim to build a conceptual framework and then revisiting examples as the book progresses. The walkthrough samples the core areas you’ll use every day: Python’s built-in data types, control-flow constructs, functions and exceptions, working with files and modules, and the essentials of object-oriented programming.
The chapter surveys Python’s data model and key operations. It covers numbers (integers, floats, complex numbers, Booleans) and arithmetic; sequences like lists and tuples with indexing and slicing, plus list methods; and immutable strings with common methods, printing, and basic formatting (including f-strings) alongside regular expressions for pattern work. It introduces dictionaries for key–value storage, sets and frozensets for membership and uniqueness, and file objects for reading and writing, with supporting utilities from modules such as os and pathlib-style path handling. It also highlights type hints as an optional, tool-checked way to make intent and interfaces clearer in larger codebases.
On program structure and flow, the chapter reviews truthiness, comparisons, logical operators, and branching with if/elif/else, plus structural pattern matching with match/case. It covers iteration with while and for (including break, continue, and optional loop else), function definitions with positional and keyword arguments, defaults, and variadic parameters, and error handling via try/except/else/finally and custom exceptions. It shows safer resource handling with context managers and the with keyword, demonstrates creating and importing your own modules (with docstrings, scripts vs. imports, and package layout), and closes with an OOP primer: defining classes, initializers, instance and class variables, inheritance, and special methods like __str__ for clean object representations.
Summary
- Python has a number of built-in data types including integers, floating point, and complex numbers; lists and tuples; strings; dictionaries; sets and frozensets; and file objects.
- Python also allows the programmer to make optional non-enforced notations of the type expected for variables and function/method parameters and return values.
- Python has a rich set of control flow structures including for and while loops, if-elif-else structures, structural pattern matching, functions, exceptions, and context handlers.
- Modules are just files of Python code that can be used by loading them with the import command.
- Python is an object-oriented language - not only are the built-in data types objects, it’s also easy to create custom classes and inherit from other classes.
FAQ
What built-in data types does Python include, and how are they manipulated?
Core types shown are numbers (int, float, complex, bool), sequences (list, tuple, str), mappings (dict), sets (set, frozenset), and file objects. You work with them using operators (for example +, *, //, in), built-ins (for example len, max, min, round), methods (for example list.append, str.split), and library modules (for example math, re).How do I index and slice lists, and what do +, * and list methods do?
Lists use zero-based indexing from the front (x[0]) and negative indexing from the back (x[-1]). Slices are x[m:n] with an inclusive start and exclusive end; x[:n] starts at the beginning and x[m:] goes to the end. + and * create new lists (don’t mutate the original), while methods like append, extend, insert, pop, remove, reverse, and sort modify a list in place. You can also replace slices to resize a list.What should I know about strings: quoting, immutability, and common operations?
Strings can be delimited by'...', "...", '''...''', or """..."""; the triple-quoted forms can span lines. Strings are immutable; operations return new strings. Useful tools include len, in, concatenation (+), repetition (*), slicing, methods like split and replace, f-strings (f"...{expr}...") for formatting, and the re module for regex-based search/replace.How do dictionaries work, what can be keys, and how do I avoid KeyError?
Dictionaries map keys to values. Keys must be immutable (for example numbers, strings, tuples); values can be any type. Accessing a missing key raisesKeyError, so use dict.get(key, default) to supply a fallback. Common methods include keys, values, items, update, and clear; len returns the number of key-value pairs.How does truthiness and comparison work, and how do if/elif/else and match/case control flow?
Falsey values includeFalse, 0, None, and empty containers like [] or ""; everything else is truthy. Use comparison operators (<, <=, ==, !=, >, >=, in, is, etc.) and logical operators (and, or, not). if / elif / else executes the first true branch; indentation defines blocks. From Python 3.10, match ... case provides structural pattern matching with flexible cases and a wildcard _.What’s the difference between while and for loops, and how do break, continue, and loop else behave?
while repeats while a condition is true; for iterates over items of any iterable (it’s a “foreach”-style loop). continue skips to the next iteration; break exits the loop. An optional else on loops runs only if the loop didn’t exit via break.How do I define functions and pass arguments, and what does return/None mean?
Define functions withdef and return values with return (if no return executes, the function returns None). Arguments can be positional or keyword, with defaults; *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary.How do I work with files safely and handle exceptions?
Open files withopen(path, mode) and prefer with open(...) as f: to ensure automatic cleanup. Handle errors using try / except / else / finally; you can define and raise custom exceptions (for example subclassing Exception). Use modules like os for paths (os.getcwd, os.path.join).How do I create and use modules, and reload them during development?
Any.py file is a module. Document with a module-level docstring, and make scripts runnable with if __name__ == "__main__":. Import with import module and call via module.func(). In the same session, to pick up on-disk changes you can call imp.reload(module) (or, in modern code, import importlib; importlib.reload(module)). Packages let you organize modules hierarchically.What OOP features are demonstrated (classes, initialization, inheritance, and special methods)?
Define classes withclass; initialize instances in __init__ and use self to access instance attributes. Inherit by specifying a base class (for example class Circle(Shape)) and call the base initializer explicitly. Class attributes (for example pi) are shared by instances. Implement __str__ to control how print() displays an instance.
The Quick Python Book, Fourth Edition ebook for free