Computer ScienceTextbook

Introduction to Python Programming

Not rated yetRate this book

Introduction to Python Programming builds practical programming skills through fifteen chapters, progressing from statements and expressions to object-oriented design, files, and introductory data science. This guide connects each concept to a small implementation and a testing habit, helping beginners explain what their programs do rather than merely copy working code.

FormatExternal access
LanguageEnglish
SubjectComputer Science
LevelNot specified
No. of pages—
Published2024

Free reading is available at the official source. Opens in a new tab.

Introduction to Python ProgrammingFree

About this book

Introduction to Python Programming builds practical programming skills through fifteen chapters, progressing from statements and expressions to object-oriented design, files, and introductory data science. This guide connects each concept to a small implementation and a testing habit, helping beginners explain what their programs do rather than merely copy working code.

Chapter-wise summaries and reading tasks

Chapter 1 Statements

Programs begin as ordered statements that receive input, store values, and produce output. The opening chapter introduces variables, strings, numbers, comments, and the basic vocabulary needed to read Python. A variable name lets a program refer to a value, while input and output connect computation to a user. Beginners should distinguish the text of a program from the result it prints and recognize that input commonly needs conversion before arithmetic. Error messages are useful evidence: their location and wording help separate invalid syntax from mistakes in a program’s intended behavior. Comments explain purpose and assumptions; they cannot repair an incorrect operation. The first goal is a short, readable program whose individual steps can be explained.

Study task. Write a program that asks for a name and a quantity, converts the quantity, and prints a meaningful result. Deliberately introduce one syntax error and explain the message before fixing it.

Chapter 2 Expressions

Expressions combine values and operators to calculate a result. This chapter uses the Python shell to investigate type conversion, mixed types, floating-point approximation, integer division, and mathematical functions. The key distinction is between how a value is displayed and how it is represented internally: rounding a display does not necessarily change the stored number. Division, floor division, and remainder answer different questions and require particular care with negative operands. Conversions should be intentional because converting text, integers, and floating-point values can fail or lose information. Reading expressions according to precedence makes calculations predictable. Formatting code consistently also makes it easier to inspect an expression and identify where a mistaken assumption entered the computation.

Study task. Predict the values and types of several mixed arithmetic expressions before running them. Include floor division, remainder, a conversion, and a decimal calculation that reveals approximation.

Chapter 3 Objects

Objects provide a common model for understanding Python values. Strings, lists, and tuples have types, contents, and supported operations, but they do not all permit modification. The chapter revisits variables as references to objects and introduces collections alongside formatted strings. This matters when two names refer to the same mutable list: changing the object through one name can affect what is observed through the other. Tuples offer an immutable sequence structure, while lists support later updates. Formatted strings combine readable text with computed values without confusing representation with calculation. Readers should track both the value associated with each name and the object relationships that explain unexpected changes.

Study task. Create two names for one list, modify the list, and compare the result with two separate lists containing the same values. Explain how a tuple changes the available operations.

Chapter 4 Decisions

Decision statements let a program choose actions from explicit conditions. Boolean values, comparisons, and logical operators form the expressions that control if-else statements, chained alternatives, and nested decisions. Correctness depends on the order of tests as well as the tests themselves: an earlier branch may prevent a later branch from ever running. Boundary values deserve special attention because a missing equality sign can create a gap or overlap between cases. Parentheses can make compound conditions easier to inspect even where precedence already determines the result. Conditional expressions are useful for small choices, but a readable multi-line decision is preferable when the logic becomes complex. The chapter’s central skill is translating a verbal rule into mutually understandable cases.

Study task. Implement a three-band fee or grade rule. Test one value below, at, and above each threshold, then explain why every permitted input reaches the intended branch.

Chapter 5 Loops

Loops repeat actions while a condition holds or for each item in an iterable. The chapter distinguishes condition-controlled while loops from for loops, then introduces nesting, break, continue, and loop else. A useful trace records how state changes on every iteration, including the update that eventually ends repetition. Without that update, a plausible-looking loop may never terminate. Nested loops multiply work and require clear roles for their separate control variables. Break exits the nearest loop, whereas continue skips the rest of its current iteration; neither means the same thing as ending a function. Loop else requires special attention because it is associated with normal completion rather than simply a false condition on an if statement.

Study task. Build a search through a list using a loop and report whether a target was found. Trace cases where it appears first, last, or nowhere, and compare a flag-based version with loop else.

Chapter 6 Functions

Functions package a meaningful operation behind a name, parameters, and an optional returned result. Defining a function does not perform its body immediately; a call changes control flow and creates a context for local variables. Parameters receive arguments, while return sends a value back to the caller. Printing a result and returning it have different consequences for reuse and testing. Scope explains why a name inside one function need not be available elsewhere. Keyword arguments improve clarity when calls contain several options. The chapter encourages breaking large tasks into small operations with clear inputs and outputs, so that each piece can be checked independently before the complete program is assembled.

Study task. Refactor a repeated calculation into a function that returns a value. Test it with ordinary, boundary, and invalid inputs, and show how another function can use the returned result.

Chapter 7 Modules

Modules organize related definitions and allow programs to reuse existing functionality. Import choices determine which names become available and how they are written at the call site. The chapter explains module basics, top-level execution, help information, and ways to find suitable modules. Importing a module can execute its top-level statements, so demonstration code should be separated from reusable definitions when appropriate. Readers should investigate documentation instead of guessing an unfamiliar function’s accepted arguments or result. A module is also a design boundary: a small public interface can hide implementation details from the rest of a program. Clear naming helps prevent confusion between local variables and imported functions.

Study task. Create a small utility module and a separate program that imports it. Check what runs during import, then use help information to document one imported function’s parameters and result.

Chapter 8 Strings

Strings support structured manipulation of textual data. Operations, indexing, slicing, searches, tests, formatting, splitting, and joining allow a program to turn a line of input into useful components. Strings are immutable, so methods that appear to transform text normally produce a new string that must be used or stored. Slice boundaries and negative indexes should be traced carefully, particularly for empty and short inputs. Searching for a substring differs from testing a whole string’s properties. Splitting and joining are complementary tools, but the choice of delimiter affects empty fields and repeated separators. Formatting belongs at the presentation stage so numeric values remain available for calculation.

Study task. Normalize a small collection of names or labels, split a delimited record, and join its fields for display. Include an empty string and extra spaces, explaining every transformation.

Chapter 9 Lists

Lists collect ordered values and support mutation, iteration, sorting, reversal, nesting, and comprehensions. Their flexibility makes them useful for accumulating results, but it also creates opportunities for accidental shared state or index errors. The distinction between a method that modifies a list and an operation that creates another list is essential. Changing a collection while traversing it can skip elements or obscure the intended algorithm. Nested lists introduce a second level of indexing and require care when constructing independent rows. Comprehensions express simple transformations and filters concisely; ordinary loops are often clearer when several actions or conditions are involved. Choosing the clearest form improves both debugging and later maintenance.

Study task. Filter and sort a list of records without changing the original. Then create a small table as nested lists and prove that updating one row does not unexpectedly alter another.

Chapter 10 Dictionaries

Dictionaries organize information through keys rather than positions. Creation, lookup, insertion, update, deletion, membership tests, and iteration make them suitable for counting, indexing, and representing structured records. Readers should distinguish a missing key from a key whose associated value happens to be empty or zero. Iterating over keys, values, or key-value pairs serves different purposes. Nested dictionaries can represent richer relationships, but the program must know the structure before following several lookups. Dictionary comprehensions provide compact construction when the transformation is straightforward. The broader lesson is to choose a data structure that matches the question: direct lookup by an identifier is different from processing a sequence in order.

Study task. Build a word-frequency dictionary from a short passage and test repeated words and missing lookups. Explain how normalization changes the counts and why a dictionary fits this task.

Chapter 11 Classes

Classes combine data and behavior in a reusable model. The chapter moves from object-oriented basics to classes, instances, instance methods, operator overloading, and organizing classes in modules. Separate instances can share the same class definition while maintaining different state. Methods act on that state through the instance reference, which helps explain why calling the same method on different objects can produce different results. Overloading an operator should preserve an understandable meaning rather than merely provide a clever shortcut. Good class design gives an object a coherent responsibility and a predictable interface. Readers should check state before and after method calls instead of judging a class only by its printed output.

Study task. Model a simple counter or inventory item with two independent instances. Define methods with explicit effects, test their state changes, and explain which responsibilities belong outside the class.

Chapter 12 Recursion

Recursion solves a problem by calling the same operation on a smaller or simpler instance. Every sound recursive design needs a base case and a step that moves toward it. The chapter develops mathematical examples, string and list processing, and broader problem-solving applications. A call trace reveals how pending operations accumulate and how results return through earlier calls. A definition can be mathematically elegant yet inefficient if it repeatedly solves the same subproblem. Recursion also uses call-stack resources, so termination alone does not guarantee suitability for very large inputs. Comparing a recursive and iterative solution helps identify when the problem’s structure naturally supports recursive reasoning.

Study task. Write a recursive function over a short list, identify its base case and decreasing measure, and draw the call sequence for three elements. Compare the same task implemented with a loop.

Chapter 13 Inheritance

Inheritance lets a class extend or specialize behavior defined elsewhere. Attribute lookup and method selection determine which implementation is used when parent and child classes offer related functionality. The chapter explores ordinary inheritance, hierarchical relationships, multiple inheritance, and mixin classes. Reuse is only part of the rationale: a subclass should also behave consistently with the expectations established by the broader type. Overriding a method can change behavior, while extending it may retain useful parent functionality. Multiple inheritance requires a careful account of method resolution rather than assumptions based on visual proximity in the code. Composition remains a useful comparison when objects collaborate without forming a meaningful subtype relationship.

Study task. Create a base class and two subclasses with one overridden method. Predict each call’s result and explain whether each subclass can be used wherever the base behavior is expected.

Chapter 14 Files

File handling makes information persist after a program ends. Reading, writing, paths, CSV data, and exception handling connect in-memory computation to external resources. A program must distinguish the location of a file from its contents and choose a mode that matches whether it is reading, replacing, or appending information. Structured CSV processing should respect fields and quoting rather than assume every comma marks a new value. Exceptions communicate failures such as missing resources or invalid input. Handling an anticipated error can make a program helpful, but catching everything without explanation hides defects. Raising an exception can also make an invalid condition explicit at the point where it is detected.

Study task. Read a small CSV file, compute a summary, and write a separate output file. Test a missing input and a malformed value, handling each with a specific, informative response.

Chapter 15 Data Science

The final chapter introduces data science through numerical arrays, tabular data, exploratory analysis, and visualization. NumPy and pandas provide abstractions for working with many values consistently, while plots help reveal distributions, patterns, and possible anomalies. Before drawing conclusions, readers should inspect types, missing values, units, and the meaning of each row. An attractive chart cannot repair inconsistent data or establish causation from an observed association. Exploration is iterative: a question guides a summary, the summary raises a new question, and the analyst documents the choices made along the way. The earlier chapters remain relevant because functions, control flow, and files make an analysis reproducible rather than a sequence of unexplained manual steps.

Study task. Explore a small public or synthetic table: inspect missing values, compute two summaries, and create one clearly labeled plot. Record a finding, a limitation, and a question that the data cannot answer.

How to study this book

  1. Read and predict each example before executing it; compare the actual result with a written explanation of your prediction.
  2. Keep a notebook of errors, their causes, and the smallest input that reproduces each problem. Revisit earlier exercises after learning functions and classes.
  3. Build one modest project in stages: accept input, validate it, organize the logic into functions, store data, and report results. Test each stage before extending it.

Questions for reflection

  • When should a function return a value rather than print it?
  • How do mutation and shared references explain surprising collection behavior?
  • What evidence would make you trust a data analysis beyond its final chart?

Source edition and coverage

This guide follows all fifteen numbered chapters of the OpenStax textbook. Tasks are original practice suggestions; use the linked source for complete examples, exercises, and library-specific details. This original study guide explains the source in new wording and adds learning activities. Read the publisher’s book and complete exercises.

About access & copyright

This page provides book information and study material. Full-text access is provided by the original publisher or authorised source; a listing does not grant permission to republish the book.

Read our Library Access & Copyright policy

Explore the contents

Check the chapters covered in this edition.

Visit the official source

See reading, preview or purchase options.

Save for later

Keep this textbook in your saved collection.

Reader ratings & reviews

Be the first to rate

No ratings yet

0%0%
0%0%
0%0%
0%0%
0%0%

Share your thoughts

Your review helps other students choose the right resources.

Rate this book

How helpful was this book?No sign-up needed. Your rating appears instantly.