Chapter 4: The absolute basics
This chapter introduction previews the Python basics covered in the chapter.
After this chapter you will be able to
- Indentation Defines Code Blocks. Explain how Python determines which statements belong to a block, using the while-loop body as an example, and contrast this with languages that use braces.
- Comments and string characters. Explain that text following a # in a Python file is generally a comment disregarded by the interpreter, whereas a # inside a string is a character in that string.
- Variables as object labels. Explain why the section treats Python variables as labels referring to objects rather than buckets containing values.
- Purpose of optional type hints. Explain why type hints can be useful when the types of variables, parameters, or return values are not obvious, especially in large projects.
- Type checker versus Python execution. Describe what the annotations in the section’s example tell mypy to flag, and distinguish those reports from what happens when Python runs the code.
- Benefits of type hints. Explain how type hints reduce confusion about expected types and help catch errors before runtime, particularly in large codebases.
- Type Hinting Tradeoffs. Explain why adding type hints may not be worthwhile in a small, informal script or when exhaustive hints make definitions harder to read.
- Progressive use of type hints. Explain that Python type hints are optional, so they can be added gradually rather than throughout a codebase at once, starting where type information is most useful.
- Division result types. Explain why dividing two integers with / can produce a floating-point result and how // differs.
- Arithmetic precedence and grouping. Explain how arithmetic precedence affects an expression and how parentheses can change its result.
- Single and double quotes. Explain that Python strings can use either single or double quotes, and how choosing one affects whether quotes inside the string need escaping.
- Backslash escape meanings. Describe how a backslash gives characters special meanings in a string, including the examples of newline, tab, backslash, and double quote.
- Triple-quoted multiline strings. Explain why triple-quoted strings are useful when text spans lines or contains both kinds of quote.
- Python numeric types and values. Describe Python’s four kinds of numbers and the basic properties of integers, floats, and Booleans given here.
- Arithmetic result types and division. Explain how integer and float operands affect arithmetic results, including the difference between / and // for integers.
- Advanced numeric functions and math. Explain that advanced functions such as trigonometric and hyperbolic trigonometric functions, along with some constants, come from the standard math module rather than being built into Python, and must be made available at the start of a program or interactive session.
- NumPy for numeric computation. Explain why the core Python installation is not well suited to intensive numeric computation and what NumPy provides instead.
- Complex number notation and type. Explain how Python creates a complex number from a number followed by j, and why a result such as j * j remains a complex-number object even when its value is equivalent to a real number.
- Math and cmath functions. Distinguish the math module’s functions from the similar functions in cmath, and explain why complex numbers have a separate module.
- Explicit complex function names. Explain why the section recommends referring explicitly to cmath functions instead of importing every name from math and cmath.
- None as an empty value. Explain that None is Python’s single special object for representing an empty value, and describe its use as a placeholder for data not yet calculated or as the default return from a function with no explicit return value.
- Prompted input and conversion. Explain how to use input() with a prompt and why numeric input needs conversion with int() or float().
- Range of built-in operators. Describe the range of Python’s built-in operators mentioned here, from standard operators such as + and * to operators for bit shifting and bitwise logical functions.
- Python style and PEP 8. Distinguish Python’s requirement to indent code into blocks from its recommended PEP 8 style conventions, and explain why the author urges programmers to follow PEP 8.
What it builds on
- The while loop (chapter 3) · Introduces the while loop whose body is used as the example here.
- Python synopsis (chapter 3) · Assumes the introductory overview of Python code.
- Built-in data types (chapter 3) · Assumes the overview of Python objects and built-in data types.
- Type hints in Python (chapter 3) · Introduces type hints in the earlier Python overview.
- Strings (chapter 3) · Assumes the earlier overview of strings as a built-in data type.
- Numbers (chapter 3) · The earlier overview of numbers.
Section by section
Introduction
This chapter introduction previews the Python basics covered in the chapter.
4.1 Indentation and block structuring
This section explains how Python uses indentation to define code blocks, why that makes structure easier to read, and where unexpected indentation can cause errors.
- Indentation Defines Code Blocks: Explain how Python determines which statements belong to a block, using the while-loop body as an example, and contrast this with languages that use braces.
Why it matters: Indentation changes what code a loop executes, not just how the code looks. - Benefits of Visible Structure: Explain the readability and consistency benefits the section attributes to indentation-based blocks.
Why it matters: Python’s required indentation makes the structure you see match the structure the interpreter uses. - Interactive Prompt Indentation: Describe the indentation mistake the section warns about when entering commands interactively.
Why it matters: Watching for unintended leading spaces can help you diagnose an error while trying examples interactively.
Key terms: indentation, block structure, body of the while loop, braces, visual structure, real structure, Python coding styles, Jupyter notebook cell, Python shell’s >>> prompt, error message
4.2 Differentiating comments
This section distinguishes Python comments from # characters inside strings.
- Comments and string characters: Explain that text following a # in a Python file is generally a comment disregarded by the interpreter, whereas a # inside a string is a character in that string.
Why it matters: This distinction helps you read comments without mistaking string content for one.
Key terms: comment, interpreter, string
4.3 Variables and assignments
This section explains how Python creates and names variables, how names refer to objects, and what happens when a name is reassigned or deleted.
- Assignment and variable names: Describe how assignment creates a variable in Python and state the naming rules given here.
Why it matters: These rules let you recognize valid assignments and variable names. - Variables as object labels: Explain why the section treats Python variables as labels referring to objects rather than buckets containing values.
Why it matters: The label model explains behavior that would be surprising if each variable were a separate container. - Immutable objects and rebinding: Distinguish changing a shared object from assigning a name to a different immutable object.
Why it matters: This distinction prevents reassignment from being mistaken for a change to every name that previously referred to an object. - Reassignment across object types: Describe how a Python name can be reassigned to objects of different types and why doing so indiscriminately can be confusing.
Why it matters: It explains both Python’s flexibility in assignment and the readability cost of changing what a name refers to. - Deletion and error traceback: Explain what deleting a variable does and describe the information shown when code then tries to access it.
Why it matters: It helps you interpret a common error without assuming that deleting a name necessarily destroys its object.
Key terms: assignment, variable names, case sensitive, variables, labels, objects, namespace, immutable values, integer object, references
4.4 Optional type hints in Python
This section explains why Python offers optional type hints and shows how a type checker can flag mismatches that Python itself will still run.
- Purpose of optional type hints: Explain why type hints can be useful when the types of variables, parameters, or return values are not obvious, especially in large projects.
Why it matters: Type hints help communicate what kinds of values code is intended to use. - Type checker versus Python execution: Describe what the annotations in the section’s example tell mypy to flag, and distinguish those reports from what happens when Python runs the code.
Why it matters: A checker’s warning can reveal a mismatch between intended and actual use even when Python runs the code without complaint.
Key terms: type hints, variables, parameters, return values, type-checking tools, mypy, int, float, annotation
4.4.1 Why use type hints?
This subsection explains how type hints clarify expected types and help catch type-related errors while code is being written.
- Benefits of type hints: Explain how type hints reduce confusion about expected types and help catch errors before runtime, particularly in large codebases.
Why it matters: Type hints can make hard-to-find type errors easier to spot before the code runs.
Key terms: type hints, type information, runtime, editors, IDEs
4.4.2 Why not use type hints?
This section explains when the effort and readability costs of type hints may outweigh their benefits.
- Type Hinting Tradeoffs: Explain why adding type hints may not be worthwhile in a small, informal script or when exhaustive hints make definitions harder to read.
Why it matters: Type hints should help a program, not consume disproportionate effort or make it harder to read. - Timing Changes to Working Code: Justify leaving working code alone rather than changing it solely to add type hints, and describe when adding hints may fit better.
Why it matters: You can improve typing when you already have a reason to work on the code.
Key terms: type hints, human readability, completeness of typing, working code, maintenance, refactoring
4.4.3 Progressive typing
This subsection explains that optional type hints can be introduced gradually where they are most useful.
- Progressive use of type hints: Explain that Python type hints are optional, so they can be added gradually rather than throughout a codebase at once, starting where type information is most useful.
Why it matters: You can get value from type hints without adding them everywhere immediately.
Key terms: type hints, progressively, type information
4.5 Expressions
This section introduces Python expressions, showing how division and arithmetic precedence affect results and noting that expressions can use nonnumeric values.
- Division result types: Explain why dividing two integers with / can produce a floating-point result and how // differs.
Why it matters: Choosing the division operator affects the result you get. - Arithmetic precedence and grouping: Explain how arithmetic precedence affects an expression and how parentheses can change its result.
Why it matters: Parentheses let you make the intended calculation explicit. - Nonnumeric expression values: State that Python expressions can use values other than numbers, including strings and Boolean values.
Why it matters: Expressions are useful beyond arithmetic.
Key terms: division, floating-point number, integer division, //, arithmetic precedence, parentheses, expressions, strings, Boolean values
4.6 Strings
This section explains how Python string literals use quotes, backslash escapes, and triple quotes.
- Single and double quotes: Explain that Python strings can use either single or double quotes, and how choosing one affects whether quotes inside the string need escaping.
Why it matters: Choosing a convenient quote delimiter makes strings containing quotes easier to write. - Backslash escape meanings: Describe how a backslash gives characters special meanings in a string, including the examples of newline, tab, backslash, and double quote.
Why it matters: Escapes let you put characters in a string that would otherwise be difficult to write directly. - Triple-quoted multiline strings: Explain why triple-quoted strings are useful when text spans lines or contains both kinds of quote.
Why it matters: Triple quotes provide a straightforward way to write text that spans several lines.
Key terms: strings, single quotes, double quotes, backslash, escape characters, \n, \t, \\, \", triple-quoted strings
4.7 Numbers
Introduces Python’s numeric types and the behaviors of arithmetic, division, and explicit numeric conversions.
- Python numeric types and values: Describe Python’s four kinds of numbers and the basic properties of integers, floats, and Booleans given here.
Why it matters: These distinctions help you anticipate what kind of value a numeric expression uses. - Arithmetic result types and division: Explain how integer and float operands affect arithmetic results, including the difference between / and // for integers.
Why it matters: Choosing a division operator changes the kind of result you get. - Explicit numeric conversion effects: Describe what happens when a float is explicitly converted to an int or an int to a float.
Why it matters: An explicit conversion can discard a fractional part or change how a number is represented.
Key terms: integers, floats, complex numbers, Booleans, division (/), // division symbol, float, integer, explicit conversions, truncate
4.7.1 Built-in numeric functions
4.7.2 Advanced numeric functions
This section identifies the standard math module as the source of advanced numeric functions and constants and says they must be made available before use.
- Advanced numeric functions and math: Explain that advanced functions such as trigonometric and hyperbolic trigonometric functions, along with some constants, come from the standard math module rather than being built into Python, and must be made available at the start of a program or interactive session.
Why it matters: It tells you where to find these numeric tools and why they are not immediately available like built-in functions.
Key terms: math, standard module, trig functions, hyperbolic trig functions
4.7.3 Numeric computation
This section explains why intensive numeric computation often calls for NumPy rather than the core Python installation.
- NumPy for numeric computation: Explain why the core Python installation is not well suited to intensive numeric computation and what NumPy provides instead.
Why it matters: It helps you recognize when core Python may be too slow for numeric work and what NumPy is designed to provide.
Key terms: core Python installation, NumPy, array operations, multidimensional matrices, fast Fourier transform
4.7.4 Complex numbers
This section explains Python’s notation for complex numbers, why their arithmetic results remain complex objects, and how to access their components.
- Complex number notation and type: Explain how Python creates a complex number from a number followed by j, and why a result such as j * j remains a complex-number object even when its value is equivalent to a real number.
Why it matters: A complex result can look like an ordinary number without becoming an integer or float. - Real and imaginary components: Describe how to access the real and imaginary parts of a Python complex number and what numeric type those parts have.
Why it matters: You can inspect a complex number’s components without assuming they are integers.
Key terms: complex numbers, j, complex-number object, real, imag, floating-point numbers
4.7.5 Advanced complex-number functions
This section explains why complex-number calculations use cmath rather than math and why explicit module names help keep their functions distinct.
- Math and cmath functions: Distinguish the math module’s functions from the similar functions in cmath, and explain why complex numbers have a separate module.
Why it matters: Choosing the appropriate module lets you perform calculations involving complex numbers without changing the expected behavior of math functions. - Explicit complex function names: Explain why the section recommends referring explicitly to cmath functions instead of importing every name from math and cmath.
Why it matters: Explicit module names help both Python and readers tell which version of a function your code uses.
Key terms: math module, cmath module, complex numbers, from <module> import *, name conflicts, override
4.8 The None value
This section explains what None represents, where it appears, and why it is easy to recognize.
- None as an empty value: Explain that None is Python’s single special object for representing an empty value, and describe its use as a placeholder for data not yet calculated or as the default return from a function with no explicit return value.
Why it matters: Recognizing None helps you interpret missing data and functions that return no explicit value. - The single None object: State that Python has only one instance of None, so every reference to None points to the same object, and None is equivalent only to itself.
Why it matters: This explains why the presence of None is easy to test.
Key terms: None, empty value, placeholder, instance, references
4.9 Getting input from the user
This section explains how to prompt a user for input and convert the resulting string when a number is needed.
- Prompted input and conversion: Explain how to use input() with a prompt and why numeric input needs conversion with int() or float().
Why it matters: Knowing that input starts as text helps you use a user's answer as the right kind of value.
Key terms: input(), prompt string, string, int(), float()
4.10 Built-in operators
This section notes that Python has familiar arithmetic operators as well as less common operators, without explaining how they work.
- Range of built-in operators: Describe the range of Python’s built-in operators mentioned here, from standard operators such as + and * to operators for bit shifting and bitwise logical functions.
Why it matters: It helps you recognize the scope of Python’s operators without expecting this section to explain each one.
Key terms: built-in operators, bit shifting, bitwise logical functions
4.11 Basic Python style
This section distinguishes Python’s few mandatory style rules from the recommended PEP 8 conventions and explains why following those conventions helps readers understand code.
- Python style and PEP 8: Distinguish Python’s requirement to indent code into blocks from its recommended PEP 8 style conventions, and explain why the author urges programmers to follow PEP 8.
Why it matters: Following shared conventions makes your Python code easier for you and others to read.
Key terms: indentation, PEP 8, Pythonic style
4.12 Summary
Where this is used later
- Statements, blocks, and indentation (chapter 8) · Applies indentation to statements and blocks in control flow.
- The if-elif-else statement (chapter 8) · The earlier section introduces indentation and block structuring.
- The while loop (chapter 8) · Python uses indentation to structure blocks.
- Nested lists and deep copies (chapter 5) · Assumes familiarity with variables and assignments.
- Mutable objects as arguments (chapter 9) · Supports reasoning about mutable objects passed as arguments.
- Introduction to exceptions (chapter 14) · Introduces an exception and traceback that the later exceptions chapter treats in more detail.
- Duck typing (chapter 17) · The earlier introduction to optional type hints provides context for the alternative mentioned here.
- Special characters and escape sequences (chapter 6) · Builds on the distinction between quote delimiters and quotes written inside strings.
Concepts explained in this chapter
- PythonPython is a high-level general-purpose programming language with an interpreted execution model and dynamic features.
- 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.
- assignmentAssignment is a programming-language operation that binds or stores an evaluated value in a variable, property, or other assignable location.
- indentationWhitespace placed at the beginning of source lines to visually align code and, in Python, delimit nested blocks.
- 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.
- bindingA binding is an association between an identifier and an object in a namespace.
- referenceAn object reference is a binding or pointer-like association through which a name identifies a runtime object.
- floating-point arithmeticA floating-point number is a numeric value represented using a finite-precision floating-point format.
- integer divisionInteger division is division whose result is truncated to an integer value.
- blockA code block is a sequence of one or more statements grouped as a syntactic unit and executed under a common control structure.
- whitespace characterWhitespace is non-printing character spacing, such as spaces, tabs, and line breaks, that can separate or structure source code.
- integerAn integer is a whole-number value with no fractional component and, in Python, arbitrary magnitude subject to available memory.
- operatorAn operator is a language construct that performs an operation on one or more operands, including path construction with pathlib operands.
- stringA string is an immutable sequence of characters represented as a Python value.
- functionA function is a callable program unit that performs an operation, may accept inputs, and can produce a result or side effect.
- 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.
- wildcard importA wildcard import is an import statement form that brings the names exported by a module directly into the importing namespace.
- input()input() is Python's built-in function for obtaining a line of text from the user through standard input.
- booleanA boolean value is a truth-valued value that is either true or false.
- commentA comment is source text ignored during program execution that explains or annotates code for human readers.
- escape characterA backslash is the character used in Python string literals and regular-expression patterns to introduce escape sequences or special interpretations.
- escape sequenceAn escape sequence is a character sequence in a string literal that represents a character or control function using a backslash-based notation.
- NoneNone is Python's singleton object representing the absence of a 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.
- del statementA del statement is Python syntax for deleting names, items, or slices from objects that support deletion.
- immutable collectionImmutability is the property of an object or data structure that prevents its contents from being changed after creation.
- newlineA newline is a character or character sequence that marks the boundary between consecutive lines of text.
- tab characterA tab character is a whitespace character that represents horizontal spacing in source text.
- refactoringRefactoring is the systematic restructuring of existing source code to improve its internal qualities without changing its externally observable behavior.
- MapA map is an associative data structure that stores key-value pairs and supports retrieving values by key.
- list()The list function is a Python built-in constructor that creates a new list from an iterable or sequence of elements.
- tupleA tuple is an ordered, immutable collection that can contain multiple values, including values of different types.
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.
