Overview

4 The absolute basics

This chapter introduces the foundational ideas you need to read and write basic Python: how code blocks are formed by indentation, how to write and interpret assignments and expressions, and how to work with Python’s core data types (numbers, strings, Booleans, and the special None value). It contrasts Python’s block structure with brace-based languages, shows how comments work, and explains that variables are names bound to objects in a dynamic, strongly typed system. It also touches on user input, built-in operators, and the conventions of clean, “Pythonic” style.

A central theme is readability. Indentation defines block scope (such as loop bodies and else clauses), yielding code whose visual layout reflects its structure and avoids brace mismatches. Comments begin with # and are ignored outside strings. Assignments create names without declarations, and the chapter clarifies that names label objects rather than act as storage buckets; deleting a name removes the label, not necessarily the object. You’re introduced to exceptions and tracebacks via simple NameError examples. The chapter also presents optional type hints: they don’t affect runtime, but external tools can use them to catch type mismatches; it outlines when hints help, when they can be overkill, and the idea of adopting them progressively.

On expressions and data, you see standard arithmetic with precedence rules, the distinction between true division and floor division, and explicit type conversions. String basics cover quoting, escaping, and triple-quoted multiline literals. Numbers include arbitrary-precision integers, floats, Booleans, and complex numbers, along with core numeric functions and the role of math and cmath for real and complex math, respectively. None is presented as a unique sentinel for “no value.” For interaction, input() returns a string that you can convert as needed. The chapter closes with practical style guidance drawn from PEP 8: consistent four-space indentation, sensible naming (lowercase_with_underscores for functions and variables, CapWords for classes, ALL_CAPS for constants), and idiomatic boolean checks without comparing directly to True or False.

Summary

  • Python code is organized by using levels of indentation.
  • Python comments can be marked with an initial ‘#’ character.
  • Strings in triple quotes at the beginning of a module, function or method are “docstrings” which explain what the object does and/or how it behaves.
  • The intended types of variables, parameters, and function return values can optionally be marked using Python’s type hints.
  • Python has the usual data types for strings, numbers, as well as data structures like lists, tuples, sets, and dictionaries.
  • The input() function can be used to get input from the user as a string.
  • Python has several built-in operators including +, -, /, //, % *, etc.
  • The preferred Python style can be found in PEP-8 in the online Python documentation.

FAQ

How does Python define code blocks, and why is indentation important?Python uses indentation (leading whitespace) to define a block of code, such as the body of a loop or an if/else. Lines indented one level under a statement (for example, after while n > 0:) belong to that block. Benefits include no missing/extra braces, a visual structure that matches actual structure, and more uniform style across codebases. Most editors auto-indent; remember that unintended leading spaces at the REPL/Jupyter prompt can cause errors.
How do comments work in Python?Everything after # on a line is a comment and ignored by the interpreter—except when the # appears inside a string literal, where it’s just a character. Example: x = 3 # Now x is 3 and x = "# not a comment".
How do variables work in Python (creation, naming, typing, and references)?- Assignment both creates and binds names: no type declarations or line terminators are needed (x = 5).
- Names are case-sensitive; must start with a letter or underscore; contain letters, digits, and underscores.
- Python is dynamically typed: a name can be rebound to objects of different types over time (x = "Hello"; x = 5).
- Names are labels to objects, not “buckets”: multiple names can refer to the same object; mutating that object is visible through all names. Rebinding a name points it to a new object.
- del name removes the name binding (not necessarily the object). Accessing a deleted or never-defined name raises NameError (shown via a traceback).
What are type hints, and do they affect runtime behavior?Type hints annotate expected types for variables, parameters, and return values (for example, p: int, def add(x: int, y: int) -> int:). Python does not enforce them at runtime, but external tools (mypy, pyright, pyre, pytype) and IDEs can report mismatches. Pros: clearer intentions, earlier detection of type issues, better editor assistance. Cons: extra effort for small scripts, potential verbosity. You can add them progressively where they help most.
How are arithmetic expressions evaluated in Python?- / always performs floating-point division (Python 3): 5 / 2 == 2.5.
- Use // for floor (integer) division: 5 // 2 == 2.
- Standard precedence rules apply; use parentheses to control order (for example, (x + y) / 2 vs x + y / 2).
How do I create strings, include quotes, and write multi-line text?- Use single or double quotes interchangeably: 'Hello' or "Hello".
- Escape sequences: \n (newline), \t (tab), \\ (backslash), \" (quote inside "...").
- You cannot split a normal quoted string across lines without escapes.
- Use triple-quoted strings ("""...""" or '''...''') for multi-line text and to include both quote types without escaping.
What numeric types does Python provide, and how do I do advanced math and complex-number operations?- Built-in types: integers (arbitrary precision), floats (typically 64-bit), complex numbers (a + bj), and Booleans (True/False).
- Conversions: int(200.2) == 200 (truncates), float(200) == 200.0.
- Built-ins include abs, round, max, min, etc.
- For real-valued math (trig, logs), use math. For complex-valued math, use cmath (example: import cmath; cmath.sqrt(-1) == 1j). Access complex parts via z.real and z.imag.
- Prefer explicit imports (import math / import cmath) to avoid name conflicts from from module import *.
- For heavy numeric work and arrays, consider NumPy.
What is the None value and when should I use it?None represents “no value.” Functions that don’t explicitly return a value return None. It’s commonly used as a placeholder or sentinel in data structures. There is only one None object; test with identity (is None/is not None), not equality.
How do I get input from a user and turn it into numbers?Use input(prompt) to read a line as a string. Convert as needed: age = int(input("Age? ")) or weight = float(input("Weight? ")). If the user enters an incompatible value, a conversion error will be raised.
What are some key Pythonic style guidelines I should follow?- Follow PEP 8 (python.org/dev/peps/pep-0008/).
- Indentation: 4 spaces per level; avoid tabs.
- Naming: modules/packages/lowercase; functions/variables lowercase_with_underscores; classes CapitalizedWords; constants ALL_CAPS.
- Don’t compare to True/False explicitly; prefer if value: or if not value:.
These conventions make code clearer and more consistent.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Quick Python Book, Fourth Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Quick Python Book, Fourth Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • The Quick Python Book, Fourth Edition ebook for free