Chapter 3: The quick Python overview
This chapter introduction frames the coming Python overview as a first impression rather than a detailed lesson, with specifics covered in later chapters.
After this chapter you will be able to
- Built-in types and operations. Describe examples of Python’s built-in data types and the ways they can be manipulated.
- Classes and Python objects. Explain that programmers can define classes and that Python uses “object” for instances of any data type, not only programmer-defined classes.
- Range of built-in types. Describe how Python’s built-in data types range from scalars such as numbers and Booleans to more complex structures such as lists, dictionaries, and files.
- Python number types. Describe Python’s four number types—integers, floats, complex numbers, and Booleans—and explain how Booleans behave in numeric contexts.
- Arithmetic and integer division. Distinguish / from // when dividing integers, and describe the limit on integer size. Identify the arithmetic operators introduced in the section.
- List indices and slices. Describe how positive and negative indices locate list elements and how slice boundaries select a subsegment.
- Slice replacement and list size. Explain how slice notation can change a list and when replacing a slice changes its length.
- Tuple immutability and operations. Explain how tuples resemble lists while differing in mutability: familiar operations can inspect or produce results from a tuple, but its elements cannot be added, removed, or replaced.
- Immutable String Sequence Operations. Explain how strings resemble lists and tuples in their operations while differing in whether their elements can be changed.
- Dictionary keys and values. Explain that a dictionary provides associative-array functionality using key-value pairs and hash tables, with immutable keys and values that can be any kind of object.
- Missing key access. Describe what happens when a dictionary key is absent and how get can provide a user-definable value instead.
- Set uniqueness and membership. Explain that a set is an unordered collection used when uniqueness and membership matter, and describe how to create one from a sequence and test membership.
- File object read write cycle. Describe how the example uses a file object to write two lines to a file, closes it, and opens the same file again for reading.
- Purpose of Python type hints. Explain why type hints are useful when Python does not require typed variables or return values, especially in large projects.
- Type checking versus Python errors. Distinguish what type-checking tools can report from what Python itself does when type hints are not followed.
- Truth values of Python objects. Explain which values Python treats as false and how it treats other values in a Boolean context.
- First true branch selection. Explain that Python executes the block after the first True if or elif condition, or the else block if no condition is True. State that elif and else are optional and that any number of elif clauses may appear.
- Match statement purpose. Explain that Python 3.10 and later provide a match statement for flexible pattern matching, superficially similar to switch statements in C++ and Java but with more complex options.
- While loop condition. Explain that a while loop keeps executing as long as its condition is True, using x > y as the section’s example.
- Iteration over iterable items. Explain that a Python for loop visits each item of an iterable, such as a list or tuple, assigning each item to the loop variable in turn.
- Skipping and ending iterations. Distinguish continue from break in the example that searches for the first integer divisible by 7: continue skips the rest of the current iteration for a non-integer, while break ends the loop once a suitable integer is found.
- Function definitions and returns. Explain that def defines a function and return supplies its result, which can be of any type; if execution reaches no return statement, the function returns None.
- Argument passing and collection. Distinguish passing arguments by position or by keyword from using * and ** parameters to collect extra arguments into a tuple and a dictionary, respectively.
- Exception handling flow. Explain what happens when an exception occurs in a try block, when the else and finally clauses run, and what happens if an exception is not caught.
- Context manager file cleanup. Explain how `with` uses a context manager when opening a file and why the file is closed even if an exception occurs.
- Creating and importing modules. Explain that your own module can be imported like a library module when its file is in the current directory or on the module search path, and that its functions are called using module attribute syntax.
- Script execution and reloading. Describe how the example module can also be run as a command-line script, and what happens when its file changes during an interactive session.
- Class initialization and inheritance. Describe how the shapes example defines classes with class, initializes instance variables in __init__, and makes Circle a subclass of Shape. State that the subclass initializer must explicitly call its base class initializer.
- Instance method calls and self. Explain how methods are defined and called, including what self refers to and why an inherited Shape method can be called on a Circle instance.
Section by section
Introduction
This chapter introduction frames the coming Python overview as a first impression rather than a detailed lesson, with specifics covered in later chapters.
3.1 Python synopsis
This section sketches Python’s data types, objects, control flow, exception handling, and flexible variables.
- Built-in types and operations: Describe examples of Python’s built-in data types and the ways they can be manipulated.
Why it matters: This is the starting point for understanding the types the book explores next. - Classes and Python objects: Explain that programmers can define classes and that Python uses “object” for instances of any data type, not only programmer-defined classes.
Why it matters: It prevents a common misunderstanding when the book calls built-in values objects. - Control flow and functions: Describe the control-flow constructs and function capability named in this overview.
Why it matters: These are the basic ways the overview says Python code can branch, repeat, and be organized into functions. - Raising and handling exceptions: State how the overview says Python raises and handles exceptions.
Why it matters: It distinguishes causing an exception from responding to one. - Flexible variable references: Explain what Python variables can refer to and whether they must be declared.
Why it matters: It shows the range of things a Python name can refer to.
Key terms: built-in data types, language operators, built-in functions, library functions, methods, classes, class instances, object, if-elif-else, while
3.2 Built-in data types
Introduces the range of Python’s built-in data types, from scalars to more complex structures.
- Range of built-in types: Describe how Python’s built-in data types range from scalars such as numbers and Booleans to more complex structures such as lists, dictionaries, and files.
Why it matters: This distinction gives you a starting point for the built-in types described next.
Key terms: built-in data types, scalars, numbers, Booleans, lists, dictionaries
3.2.1 Numbers
This section introduces Python’s four number types and shows basic arithmetic, complex-number attributes, and ways to call numeric functions.
- Python number types: Describe Python’s four number types—integers, floats, complex numbers, and Booleans—and explain how Booleans behave in numeric contexts.
Why it matters: These types are the starting point for understanding the section’s numeric examples. - Arithmetic and integer division: Distinguish / from // when dividing integers, and describe the limit on integer size. Identify the arithmetic operators introduced in the section.
Why it matters: The choice between / and // changes the kind of result an integer calculation produces. - Complex number components: Describe how the section writes a complex number and how to access its real and imaginary parts.
Why it matters: The notation lets you recognize a complex value and refer to its two parts. - Numeric function access: Distinguish calling an always-available built-in function from calling a function in an imported numeric library module.
Why it matters: It explains why some numeric functions can be called by name while others need an imported module name.
Key terms: integers, floats, complex numbers, Booleans, True, False, arithmetic operators, /, //, exponentiation
3.2.2 Lists
This section introduces what Python lists can hold and how to access and change them with indices, slices, operators, and methods.
- Mixed list elements: Explain that a Python list can contain elements of different types, including other lists.
Why it matters: This helps you recognize the variety of values a list can hold. - List indices and slices: Describe how positive and negative indices locate list elements and how slice boundaries select a subsegment.
Why it matters: These rules let you locate an element or select part of a list. - Slice replacement and list size: Explain how slice notation can change a list and when replacing a slice changes its length.
Why it matters: A slice can change a list’s contents and length, not just retrieve part of it. - List operators and methods: Distinguish the effect of + and * on lists from the section’s description of calling list methods, and explain why some named operations are useful alongside slices.
Why it matters: It helps you tell when an operation produces a new list and why a named operation may be clearer than slicing.
Key terms: list, elements, positive indices, negative indices, slice, slice notation, replace, operators, list methods, attribute notation
3.2.3 Tuples
This subsection introduces tuples as immutable, list-like sequences and shows how to create and convert them.
- Tuple immutability and operations: Explain how tuples resemble lists while differing in mutability: familiar operations can inspect or produce results from a tuple, but its elements cannot be added, removed, or replaced.
Why it matters: Immutability tells you which familiar list operations are safe to expect from a tuple. - Tuple creation and contents: Describe the comma required for a one-element tuple and the variety of types a tuple can contain.
Why it matters: These details help you recognize a single-element tuple and avoid assuming all its elements must have the same type. - List and tuple conversion: State how to convert a list to a tuple and a tuple to a list using the built-in functions named in the section.
Why it matters: Conversion lets you choose between the two sequence types when you need one or the other.
Key terms: tuple, immutable, index, slice, count, in, one-element tuple, comma, elements, list
3.2.4 Strings
This subsection surveys how Python strings are written, used as immutable sequences, processed, and printed.
- String Delimiters and Escapes: Describe the quotation styles used to delimit strings and identify tab and newline characters in strings.
Why it matters: These are basic ways to recognize and write string values. - Immutable String Sequence Operations: Explain how strings resemble lists and tuples in their operations while differing in whether their elements can be changed.
Why it matters: This distinction explains why reading part of a string works but changing it in place does not. - Regular Expression String Processing: Describe the role of the re module in working with strings.
Why it matters: It identifies where Python offers more sophisticated string-pattern tools. - Printing and Formatting Strings: Explain how print handles strings and other objects, and name the formatting operator introduced here.
Why it matters: It connects printed output with object-to-string conversion and formatted strings.
Key terms: strings, single, double, triple single, triple double, tab (\t), immutable, in, +, *
3.2.5 Dictionaries
Introduces dictionaries as key-value collections and explains their key restrictions, basic operations, and behavior when a key is missing.
- Dictionary keys and values: Explain that a dictionary provides associative-array functionality using key-value pairs and hash tables, with immutable keys and values that can be any kind of object.
Why it matters: The distinction between keys and values helps you choose what can go on each side of a dictionary entry. - Missing key access: Describe what happens when a dictionary key is absent and how get can provide a user-definable value instead.
Why it matters: This distinction lets you anticipate a failed lookup and choose when to supply a fallback value. - Basic dictionary operations: State how len and del apply to dictionaries and recognize that dictionaries also have methods for common operations.
Why it matters: These operations give you a starting point for inspecting and changing dictionaries.
Key terms: dictionary, associative array, hash tables, key-value pairs, immutable, KeyError, get, len, del, dictionary methods
3.2.6 Sets, frozensets
Introduces sets as unordered collections for uniqueness and membership, and frozensets as immutable sets.
- Set uniqueness and membership: Explain that a set is an unordered collection used when uniqueness and membership matter, and describe how to create one from a sequence and test membership.
Why it matters: Sets are useful when you care whether an item is present, rather than where it appears or how many times it occurs. - Frozenset immutability: Distinguish a frozenset from a set by describing what cannot be done after a frozenset is created.
Why it matters: The name signals that a frozenset's contents stay fixed after creation.
Key terms: set, unordered collection, membership, uniqueness, in, frozenset, immutable
3.2.7 File objects
This section introduces file objects through a write-and-read example, explains how absolute paths preserve access after a directory change, and names other Python input/output facilities.
- File object read write cycle: Describe how the example uses a file object to write two lines to a file, closes it, and opens the same file again for reading.
Why it matters: This is the section’s basic example of accessing a file for writing and then reading. - Absolute pathname file access: Explain why the example can still access the file after moving to another directory.
Why it matters: It explains why changing directories does not prevent the example from finding the file. - Other input output facilities: State what other input/output capabilities the section attributes to input, sys, struct, and Pickle.
Why it matters: These names show that Python has input/output facilities for different kinds of data and streams.
Key terms: file object, open, write ("w") mode, read ("r") mode, current working directory, os module, absolute pathname, input, sys, stdin
3.3 Type hints in Python
This section explains why Python offers type hints and distinguishes checks by external tools from errors raised by Python itself.
- Purpose of Python type hints: Explain why type hints are useful when Python does not require typed variables or return values, especially in large projects.
Why it matters: Type hints help make type expectations visible when the code alone may not make them obvious. - Type checking versus Python errors: Distinguish what type-checking tools can report from what Python itself does when type hints are not followed.
Why it matters: This distinction prevents you from mistaking a hint for a rule that Python enforces.
Key terms: type hints, typed variables, return values, type-checking tools, runtime exception, compile time
3.4 Control flow structures
3.4.1 Boolean values and expressions
This subsection explains which Python values count as true or false and names the operators used to form Boolean expressions.
- Truth values of Python objects: Explain which values Python treats as false and how it treats other values in a Boolean context.
Why it matters: This lets you predict how a value will be treated when Python needs a true-or-false result. - Comparison and logical expressions: Describe the two groups of operators the subsection gives for creating Boolean expressions, with examples of each.
Why it matters: These operators let you express true-or-false questions in Python code.
Key terms: False, True, None, empty values, comparison operators, logical operators, and, not, or
3.4.2 The if-elif-else statement
Explains how an if-elif-else statement selects a block to execute and how indentation defines its blocks.
- First true branch selection: Explain that Python executes the block after the first True if or elif condition, or the else block if no condition is True. State that elif and else are optional and that any number of elif clauses may appear.
Why it matters: This lets you predict which part of a conditional statement will run. - Indented conditional blocks: Describe how indentation, rather than braces or brackets, marks the blocks in an if-elif-else statement and how statements within a block are laid out.
Why it matters: Indentation shows which statements belong to a chosen branch.
Key terms: if, elif, else, True, indentation, blocks, statements
3.4.3 Structural pattern matching with match
Introduces Python’s match statement as a pattern-matching feature available from Python 3.10.
- Match statement purpose: Explain that Python 3.10 and later provide a match statement for flexible pattern matching, superficially similar to switch statements in C++ and Java but with more complex options.
Why it matters: This gives you a starting point for recognizing match without treating it as just another language’s switch statement.
Key terms: match statement, pattern matching, switch statements
3.4.4 The while loop
This subsection introduces condition-controlled repetition with while and distinguishes break from continue.
- While loop condition: Explain that a while loop keeps executing as long as its condition is True, using x > y as the section’s example.
Why it matters: This is the basic rule for understanding when a while loop repeats. - Break and continue effects: Distinguish break, which ends the loop, from continue, which stops the current iteration and returns to the start of the loop block.
Why it matters: These statements change whether the loop ends or moves on from its current iteration.
Key terms: while loop, condition, True, break, continue, iteration
3.4.5 The for loop
This section explains how a Python for loop visits items in an iterable and how continue and break affect that loop.
- Iteration over iterable items: Explain that a Python for loop visits each item of an iterable, such as a list or tuple, assigning each item to the loop variable in turn.
Why it matters: This is the basic pattern for processing the contents of a Python sequence. - Skipping and ending iterations: Distinguish continue from break in the example that searches for the first integer divisible by 7: continue skips the rest of the current iteration for a non-integer, while break ends the loop once a suitable integer is found.
Why it matters: These statements let a search ignore unsuitable items and stop when it finds a match.
Key terms: for loop, iterable, sequence, foreach loop, continue, break, iteration
3.4.6 Function definition
This subsection summarizes how Python functions are defined, return values, and receive arguments.
- Function definitions and returns: Explain that def defines a function and return supplies its result, which can be of any type; if execution reaches no return statement, the function returns None.
Why it matters: This gives you the basic vocabulary for describing what a Python function produces. - Argument passing and collection: Distinguish passing arguments by position or by keyword from using * and ** parameters to collect extra arguments into a tuple and a dictionary, respectively.
Why it matters: This helps you recognize the argument forms a Python function can accept.
Key terms: def statement, return statement, None, positional arguments, keyword arguments, *, **, tuple, dictionary
3.4.7 Exceptions
Introduces how Python catches exceptions, handles errors it defines itself, and uses else and finally clauses.
- Exception handling flow: Explain what happens when an exception occurs in a try block, when the else and finally clauses run, and what happens if an exception is not caught.
Why it matters: These rules let you follow what a program does when an operation succeeds or fails. - User defined exceptions: Describe how the example defines and raises its own exception and how that exception can be handled.
Why it matters: Exception handling is not limited to errors supplied by Python.
Key terms: try-except-else-finally, try block, except block, else clause, finally clause, uncaught exception, Exception, EmptyFileError, raise
3.4.8 Context handling using the with keyword
This section introduces `with` and context managers as a streamlined way to ensure cleanup when working with a file, even if an exception occurs.
- Context manager file cleanup: Explain how `with` uses a context manager when opening a file and why the file is closed even if an exception occurs.
Why it matters: It explains why a file opened in this `with` example does not need a separate close step in the block.
Key terms: with keyword, context manager, try-except-finally pattern, cleanup action
3.5 Module creation
This section explains how to create and import a module, run it as a script, refresh it after edits, and group modules into packages.
- Creating and importing modules: Explain that your own module can be imported like a library module when its file is in the current directory or on the module search path, and that its functions are called using module attribute syntax.
Why it matters: It lets you reuse functions from your own files in the same way you use library functions. - Module documentation and comments: Distinguish docstrings from comments as described in the example module.
Why it matters: The distinction helps you describe what a module does and clarify particular parts of its code. - Script execution and reloading: Describe how the example module can also be run as a command-line script, and what happens when its file changes during an interactive session.
Why it matters: It explains both how to run the example directly and why an interactive session may not reflect edits to its file. - Packages for grouping modules: Explain the section's basic description of packages as a way to group modules in larger projects.
Why it matters: Packages provide a way to organize related modules as a project grows.
Key terms: module, module search path, sys.path, import statement, attribute syntax, documentation strings, docstrings, comments, script, import
3.6 Object-oriented programming
Introduces Python’s object-oriented syntax through a shapes example, showing how classes are initialized, inherited methods are called, and special methods are used implicitly.
- Class initialization and inheritance: Describe how the shapes example defines classes with class, initializes instance variables in __init__, and makes Circle a subclass of Shape. State that the subclass initializer must explicitly call its base class initializer.
Why it matters: These are the basic relationships behind the Shape and Circle example. - Instance method calls and self: Explain how methods are defined and called, including what self refers to and why an inherited Shape method can be called on a Circle instance.
Why it matters: It explains both method-call syntax and why Circle can use Shape’s move method. - Implicit special method use: Explain that __str__ supplies a string version of an instance that print uses implicitly, and identify the other uses of special method attributes mentioned here.
Why it matters: It shows how ordinary operations can call methods without an explicit method call.
Key terms: class, __init__, instance variables, subclass, base class, method, def, self, move, attribute syntax
3.7 Summary
Where this is used later
- Variables and assignments (chapter 4) · Assumes the introductory overview of Python code.
- Types are objects too (chapter 17) · Builds on the broad use of objects and types.
- Managing various data types (chapter 19) · Familiarity with Python’s built-in data types.
- Numbers (chapter 4) · Develops the treatment of Python numbers.
- Boolean values and expressions (chapter 8) · Develops the treatment of Boolean values and expressions.
- Complex numbers (chapter 4) · Develops the treatment of complex numbers.
- Advanced numeric functions (chapter 4) · Covers more advanced numeric functions.
- The import statement (chapter 10) · Develops the import statement.
Concepts explained in this chapter
- tupleA tuple is an ordered, immutable collection that can contain multiple values, including values of different types.
- import statementAn import statement is a source-code declaration that makes names or definitions from another module, package, or namespace available in the current scope.
- complex floating-point typeA complex number is a number consisting of a real component and an imaginary component, represented in Python with an imaginary component suffixed by j.
- floating-point arithmeticA floating-point number is a numeric value represented using a finite-precision floating-point format.
- integerAn integer is a whole-number value with no fractional component and, in Python, arbitrary magnitude subject to available memory.
- immutable collectionImmutability is the property of an object or data structure that prevents its contents from being changed after creation.
- MapA map is an associative data structure that stores key-value pairs and supports retrieving values by key.
- moduleA module is a distinct, bounded software unit that groups related code or functionality and provides an organizational or interaction boundary within a larger system.
- file objectA data file is a stored file whose contents provide data for retrieval, processing, or analysis.
- stringA string is an immutable sequence of characters represented as a Python value.
- primitive data typeA primitive data type is a fundamental, language-provided type for representing a basic value, rather than a composite of multiple values.
- PythonPython is a high-level general-purpose programming language with an interpreted execution model and dynamic features.
- exceptionAn exception is an abnormal runtime event represented in Python by an object that can interrupt normal execution and be handled by exception-handling constructs.
- conditional logicA conditional statement is a programming-language construct that selects code for execution based on a condition.
- booleanA boolean value is a truth-valued value that is either true or false.
- loopA for loop is a control-flow construct that iterates over the items supplied by an iterable.
- list()The list function is a Python built-in constructor that creates a new list from an iterable or sequence of elements.
- inheritanceInheritance is an object-oriented mechanism by which a class derives behavior and structure from another class, forming a hierarchy of related classes.
- Class_Class_ is a book-specific example class containing methods and class variables for demonstrating namespace lookup.
- type hintsA type hint is syntax that annotates the intended type of a value associated with a variable, parameter, return value, or similar program element.
- integer divisionInteger division is division whose result is truncated to an integer value.
- docstringA docstring is a string literal attached to a module, function, method, or class to provide documentation accessible to development tools and runtime introspection.
- packageA package is a structured collection of software modules organized under a common namespace.
- reloadreload is a Python operation that re-executes a previously imported module's code in an existing interpreter session.
- sys.pathA module search path is the ordered set of directories that a language runtime searches to locate importable modules and packages.
- slicingSlicing selects or partitions a portion of an indexed sequence or multidimensional array, often along specified indices or dimensions.
- constructor method__init__ is Python's conventional instance-initialization method invoked when an object is initialized.
- methodA method is a function associated with a class or object and invoked in the context of that class or object.
- self parameterself is the conventional first parameter name that refers to the instance on which a Python method is invoked.
- functionA function is a callable program unit that performs an operation, may accept inputs, and can produce a result or side effect.
- operatorAn operator is a language construct that performs an operation on one or more operands, including path construction with pathlib operands.
- rere is Python's standard-library module for matching and processing text with regular expressions.
- NoneNone is Python's singleton object representing the absence of a value.
- openopen() is Python's built-in function for opening a file and returning a file object.
- osThe os module is a Python standard-library module that provides operating-system interfaces, including filesystem and pathname operations.
- with statementA with statement is a Python control-flow construct that establishes a context manager-controlled block and performs its exit actions when the block ends.
- dict.getThe dictionary get method retrieves the value associated with a key and can return a specified fallback when the key is absent.
- command-line argumentA command-line argument is a value supplied to a program when it is invoked through a command-line interface.
- positional argumentA positional parameter is a function argument identified by its ordinal position in the argument list.
- indentationWhitespace placed at the beginning of source lines to visually align code and, in Python, delimit nested blocks.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
