Introduction to Python Programming is the OpenStax textbook for a first programming course. Udayan Das, Aubrey Lawson, Chris Mayfield and Narges Norouzi are the senior contributing authors, and OpenStax published the book on March 13, 2024. Its 15 chapters start at the first print() and move through variables, decisions, loops, functions, modules, strings, lists and dictionaries to classes, inheritance, recursion, files, exceptions and a first look at data science with NumPy and Pandas.
BSCS, BSIT and BS Data Science students can use it as the course book for Programming Fundamentals, since it needs no earlier coding. Each section has learning objectives, animations and practice exercises that run in an online code runner. This page adds a plain summary, key points, a practice tip, a common mistake and two practice questions for every chapter, plus a study plan, so you know what to read first. You can download the free PDF from the official OpenStax site.
Book Overview
| Course | Programming Fundamentals (Python) |
| Degree Programs | BSCS, BSIT, BS Data Science |
| Level | University, introductory level; no earlier programming needed |
| Authors | Udayan Das, Aubrey Lawson, Chris Mayfield and Narges Norouzi (senior contributing authors), with Yamuna Rajasekhar and Reed Kanemaru (contributing authors) |
| Publisher | OpenStax, Rice University |
| Published | March 13, 2024 |
| Structure | 15 chapters, no parts and no appendix; each chapter has 6 to 9 short sections; this page gives one block per chapter |
| Exercises | Every section has learning questions that explain wrong answers and 1 to 2 programming practice exercises in an integrated code runner; chapter summaries add a reference table |
| Language | English |
| License | Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) |
| Format | Free PDF and free online edition on OpenStax, with an interactive code runner (the code runner is developed by Wiley and is All Rights Reserved) |
Chapter List
Chapter 1: Introduction
Difficulty: Easy · Key topics: statements, print(), input(), variables, strings and numbers, error messages, comments, docstrings, history of Python
The chapter starts from the idea that a program is a list of statements that run one after another, each describing an action. It teaches print() for output and input() for reading what the user types, then shows how an assignment stores a value in a variable. After that it covers string and number basics, introduces common error messages early because mistakes are a normal part of programming, and explains comments and docstrings. It ends with a short history of Python, from the first release in 1991 to its rise to number one on the TIOBE index in October 2021.
Key Points:
- A program is a sequence of statements that Python runs one after another.
print()shows values on the screen andinput()shows an optional prompt and reads one line typed by the user.=assigns a value to a variable;len()returns the length of a string andtype()returns the type of a value.+joins strings or adds numbers, and**raises a number to a power.#starts a comment, and triple quotes create a docstring for documentation.- Python’s first release, version 0.9.0, appeared in 1991.
Practice Tip: Write a small mad-lib program: ask for two adjectives and two nouns with input(), print a three-line story with the words filled in, then misspell print on purpose to see what the error message looks like.
Common Mistake: Ignoring the error message and retyping code at random. The message names the kind of problem and the line number, so read it first.
Important Questions:
- What is the difference between
print()andinput()?print()displays values on the screen, whileinput()shows an optional prompt and returns the line the user types. - What is a docstring, and how is it different from a comment? A docstring is a string written in triple quotes that documents code, while a comment starts with
#and is ignored by Python.
Chapter 2: Expressions
Difficulty: Easy · Key topics: expressions, Python shell, type conversion, floating-point errors, floor division, modulo, math module, long lines
Chapter 2 builds on simple expressions, which compute a single value, such as 3*x - 5. You first try expressions in the Python shell, then learn that typed input arrives as a string and must be converted with int() or float() before arithmetic. The chapter explains why floating-point numbers can show round-off and overflow errors, how / differs from // and %, and how the math module and round() help. It finishes with advice on splitting long lines for readability and a short look at Python careers. Two practice programs, a bread recipe scaler and a tip calculator, close the chapter.
Key Points:
- An expression combines literals, variables and operators and produces a single value.
int(),float()andstr()convert between types; a string can be joined with a number only after the number is converted withstr()./is real division (7 / 4is 1.75),//is floor division (7 // 4is 1) and%is the remainder (7 % 4is 3).- Floating-point numbers can suffer from round-off and overflow errors.
round(x, ndigits)rounds to the chosen number of decimal places andabs(x)gives the absolute value.s * nrepeats a string:"Ha" * 3gives"HaHaHa".
Practice Tip: Open the Python shell and type 7 // 4, 7 % 4 and 0.1 + 0.2 one after another. The last result shows round-off error in action.
Common Mistake: Using / when you need a whole number. Even 8 / 2 gives 4.0, a float, so use // or convert the result with int().
Important Questions:
- What is the difference between
//and%?//gives the integer quotient and%gives the remainder, so7 // 4is 1 and7 % 4is 3. - Why does
"Total: " + 5fail? Python will not join a string and a number. Convert the number first withstr(5).
Chapter 3: Objects
Difficulty: Medium · Key topics: objects, strings, indexing, Unicode, f-strings, variables and memory diagrams, id(), type(), lists, tuples
An object is a single unit of data in a Python program, and this chapter looks inside the ones you already use. It explains that a string is a sequence of Unicode code points that you reach by index, counting from 0 at the front or from -1 at the back, and it uses f-strings to format output. It then shows variables as names that refer to objects, drawn in memory diagrams, with id() and type() as inspection tools. The last two sections introduce lists and tuples, containers that hold any number of other objects, with tuples fixed after creation.
Key Points:
- Positive indexes run from 0 to length minus 1; negative indexes run from -1 down to minus the length.
ord(c)returns the Unicode code point of a character andchr(i)turns a code point back into a character.f"{number:.2f}"formats a float to two decimal places.- A variable is a name that refers to an object;
id()returns the object’s identity andtype()returns its type. - A list is written with square brackets and a tuple with parentheses; a tuple cannot be changed after it is created.
\nis the newline escape sequence and\tis the tab.
Practice Tip: Make a string and a list with the same three items and read the last item of each with index -1. Then make a tuple and try to assign to its first element to see the error Python gives.
Common Mistake: Thinking a variable “contains” a value. In Python a variable only refers to an object, so two names can refer to the very same object.
Important Questions:
- How do you get the last character of a string
s? Use the negative indexs[-1], because negative indexes count from the end. - How is a tuple different from a list? A tuple uses parentheses and cannot be changed after creation, while a list uses square brackets and can be changed.
Chapter 4: Decisions
Difficulty: Easy · Key topics: Boolean values, comparison operators, if-else, and/or/not, operator precedence, elif, nested decisions, conditional expressions
Normally Python follows one fixed path through a program, but real programs must choose between paths. The chapter starts with Boolean values and the comparison operators that produce them, then uses them as conditions in if-else statements. It adds the logical operators and, or and not, explains how precedence and associativity set the order of evaluation, and extends decisions with elif chains, nested decisions and one-line conditional expressions. By the end you can write programs that test conditions and run the right branch.
Key Points:
- A Boolean holds
TrueorFalse, andbool(x)converts a value to one of them. - The comparison operators are
==,!=,>,<,>=and<=, and each produces a Boolean. andis true only when both sides are true,oris true when at least one side is, andnotinverts a value.- Precedence and associativity decide the order in which operators are evaluated.
elifadds further conditions that are checked in order, with an optionalelseas the fallback.- A conditional expression has the form
a if condition else band gives one of two values in a single line.
Practice Tip: Write a small grade program with if, elif and else, then test it with values on the edges of each range, such as 49, 50 and 51.
Common Mistake: Writing = instead of == in a condition. A single = assigns a value, while == compares two values.
Important Questions:
- What does
elifdo? It adds another condition that is checked only when the earlier conditions were false, and an optionalelsecan catch everything left. - What does a conditional expression look like?
expression_if_true if condition else expression_if_false, which gives one of two values in one line.
Chapter 5: Loops
Difficulty: Medium · Key topics: while loop, for loop, range(), nested loops, break, continue, loop else, prime numbers
Loops run a group of statements again and again, the way a program might step through a roster of names. The chapter teaches the while loop, which repeats as long as its expression stays true, and the for loop, which visits the elements of a container, often together with range(). It then nests one loop inside another and shows how break leaves a loop early and continue skips to the next pass. The last section covers the loop else block, which runs only when the loop finishes without a break. The practice exercise asks for the first N prime numbers.
Key Points:
- A
whileloop repeats while its loop expression stays true; aforloop iterates over the elements of a container. range(end)starts at 0,range(start, end)sets the start, andrange(start, end, s)adds a step size; the end value is never included.- A nested loop is a loop placed inside the body of another loop.
breakexits a loop immediately andcontinueskips the rest of the current pass.- A loop
elseblock runs only if the loop was not stopped bybreak.
Practice Tip: Print a multiplication table with two nested for loops, then add a break that stops the inner loop as soon as a product passes 50.
Common Mistake: Forgetting to change the variable that a while condition tests, so the condition never becomes false and the program runs forever.
Important Questions:
- Which numbers does
range(2, 10, 3)produce? 2, 5 and 8, because it starts at 2, steps by 3 and stops before 10. - When does a loop
elseblock run? After the loop ends normally. If the loop is left throughbreak, theelseblock is skipped.
Chapter 6: Functions
Difficulty: Medium · Key topics: def, control flow, local and global scope, parameters, arguments, return values, keyword arguments, default values
Functions let you write a block of code once, give it a name and call it whenever you need it. The chapter shows how to define a function with def and a docstring, and how control passes into the function and back to the caller. It explains variable scope, with local variables that exist only inside a function and global variables that the whole program can read, and the global keyword for changing one. It then covers parameters, arguments, default values, return values and keyword arguments, and notes that Python passes arguments by object reference.
Key Points:
- A function is defined with
def, a name, parentheses, an optional docstring and a body. - Parameters are the names listed in the definition; arguments are the values supplied in the call.
- A variable created inside a function is local and disappears when the function ends; assigning to a name inside a function makes it local unless it is declared
global. - Positional arguments are matched by order, keyword arguments are matched by name and can be given in any order.
- A default parameter value makes the matching argument optional.
returnsends a value back to the code that called the function.
Practice Tip: Write a function with one default parameter, then call it with the argument, without it, and with keyword arguments given in a different order from the definition.
Common Mistake: Assigning to a global variable inside a function without global. Python quietly creates a new local variable and the global keeps its old value, with no error.
Important Questions:
- What is the difference between a parameter and an argument? A parameter is a name in the function definition, while an argument is the value passed in a call, which is assigned to the parameter.
- What happens to a variable created inside a function when the function ends? It disappears, so the main program cannot use it and a name error occurs if it tries.
Chapter 7: Modules
Difficulty: Easy · Key topics: modules, import, from-import, __name__ check, help(), docstrings, built-in and third-party modules, datetime
As programs grow longer, code is easier to manage when it is split across several files. A module is a Python file whose name is the file name without the extension. The chapter shows how to import a whole module, how to import only chosen names with from, and why a module ends with an if __name__ == "__main__" check so that its test code does not run when another program imports it. It also covers the help() function, which displays documentation built from docstrings, and explains how to find modules among Python’s more than 200 built-in ones and the hundreds of thousands of third-party ones.
Key Points:
- A module is a
.pyfile, and its name is the file name without.py. import moduleloads a whole module;from module import functionloads one name.- The block under
if __name__ == "__main__":runs only when the file is executed directly, not when it is imported. help(module_name)shows the docstring, then the functions, global variables and file name;help(function_name)shows one function’s docstring.- Avoid importing or defining two functions with the same name.
- Search docs.python.org for built-in modules and pypi.org for third-party ones.
Practice Tip: Save two small functions in a file called greetings.py, import them from a second file, add a __main__ check to the first file, and note which lines run in each case.
Common Mistake: Naming your own file after a standard module, such as random.py. Python may then import your file instead of the real module and give confusing errors.
Important Questions:
- What does
if __name__ == "__main__":do? It runs the indented block only when the file is run directly, so the code is skipped when the file is imported by another program. - Where can you look for modules to use? Built-in modules are documented at docs.python.org, and third-party modules can be searched at pypi.org.
Chapter 8: Strings
Difficulty: Medium · Key topics: string operations, comparison, indexing, slicing, find(), index(), count(), format(), split(), join(), immutability
Text in Python is an ordered sequence of characters, and this chapter collects the tools for working with it. You compare strings using the codes of their characters from left to right, read single characters or ranges by index, and cut out pieces with slicing. You then search and test with count(), find(), index() and the in operator, build text with format(), and use split() and join() to turn a string into a list of tokens and back again. A fact that runs through the whole chapter is that strings are immutable.
Key Points:
len()counts the characters in a string;upper()andlower()change its case.- Strings are compared character by character from the left, using the codes of the characters.
find()returns -1 when the substring is missing, whileindex()raises aValueError.intests whether a substring occurs in a string, and in aforloop it visits each character.split()breaks a string at a separator (at whitespace if none is given) andjoin()puts a list of strings back together.- Strings are immutable, so slicing and methods build new strings rather than changing the old one.
Practice Tip: Take one sentence, split it into words, count the words, and join them back with hyphens using "-".join(words).
Common Mistake: Trying to change a character in place, as in s[0] = "H". This raises an error because strings are immutable; build a new string instead.
Important Questions:
- What is the difference between
find()andindex()? When the substring is absent,find()returns -1 butindex()raises aValueError. - What does
split()do when you give it no separator? It splits the string on whitespace and returns the pieces as a list.
Chapter 9: Lists
Difficulty: Medium · Key topics: list methods, iterating, sorting, reversing, copying, max/min/sum, nested lists, list comprehensions
Lists store groups of related data, and unlike strings they can be changed after they are created. This chapter builds on the lists introduced earlier by showing how to modify them with append(), remove() and pop(), and how to loop over them using either the elements or the indexes. It covers sorting, reversing and copying, and the built-in max(), min() and sum() for numeric lists. The last sections nest lists to represent tables of data and introduce list comprehensions, a compact way to build or filter a new list.
Key Points:
- Lists are mutable:
append(element)adds at the end,remove(element)deletes a matching element andpop()removes the last one. sort()orders a list in ascending order, but only when all elements are of the same type.reverse()flips the order of a list andcopy()makes a complete copy.max(),min()andsum()work on lists of numbers.- A nested list is a list that contains other lists, which is how multidimensional data is stored.
- A list comprehension builds a new list in one expression and can filter items from an existing list.
Practice Tip: Write a comprehension that squares the even numbers from 1 to 10, then write the same thing as a for loop with append() and compare the two.
Common Mistake: Writing b = a and expecting a separate copy. Both names refer to the same list, so a change through one shows up in the other; use a.copy() instead.
Important Questions:
- Does
sort()create a new list? No. It sorts the existing list in place, in ascending order, and works only when all elements are the same type. - What is a list comprehension? A compact expression that builds a new list from an existing sequence, and it can also filter which items are kept.
Chapter 10: Dictionaries
Difficulty: Medium · Key topics: key-value pairs, dict(), get(), items(), keys(), values(), update(), del, pop(), nested dictionaries, dictionary comprehensions
A dictionary stores information as key-value pairs, which suits data such as a phone book or a set of settings. The chapter shows two ways to create one, with curly braces or the dict() function, and several ways to read, add, update and delete entries. It then combines dictionaries with conditionals and loops, so you can test for a key or a value and iterate over keys, values or items. It closes with nested dictionaries and dictionary comprehensions, and the practice exercise sorts a list of numbers into even and odd lists.
Key Points:
- A dictionary (type
dict) holds key-value pairs; keys must be unique and immutable, while the dictionary itself is mutable. - Values are read with square brackets or
get(). items(),keys()andvalues()return the pairs, the keys and the values.- Entries are added or changed with square brackets or
update(), and removed withdelorpop(). - A
for key in dictionary:loop iterates over the keys; you can also loop over values or items. - A dictionary comprehension has the form
{key_expression: value_expression for element in iterable}.
Practice Tip: Build a word-count dictionary from one sentence with a for loop, then print each word and its count by looping over items().
Common Mistake: Using a list as a dictionary key. Keys must be immutable, so use a string, a number or a tuple instead.
Important Questions:
- What can be used as a dictionary key? Any immutable object, such as a string, a number or a tuple, and each key must be unique.
- How do you remove an entry but keep its value? Use
pop(key), which returns the removed value so you can assign it to a variable.
Chapter 11: Classes
Difficulty: Hard · Key topics: object-oriented programming, classes, instances, __init__(), attributes, self, magic methods, operator overloading, importing classes
Object-oriented programming models real-world things as objects that bundle data with the procedures that work on it. The chapter explains a class as the blueprint, with attributes and methods, and an instance as one object created from that class. You write an __init__() method to set up each instance, learn the difference between instance attributes, which are separate copies, and class attributes, which are shared, and use self as the first parameter of instance methods. Later sections introduce magic methods and operator overloading, such as __mul__() so that * works on your own objects, and importing classes from modules under an alias.
Key Points:
- A class defines a type of object through its attributes and methods; one class can produce many instances.
__init__()is called when an instance is created and sets up its instance attributes.- An instance attribute belongs to one instance; a class attribute is shared by all instances.
- Instance methods take
selfas their first parameter so they can reach the instance. - Magic methods have names that begin and end with double underscores, and defining one such as
__mul__()overloads an operator. from module import ClassName as Aliasimports a class under a different name.
Practice Tip: Write a bank-account class with a balance attribute and a deposit() method, create two accounts, and check that depositing into one does not change the other.
Common Mistake: Leaving self out of a method definition. Python then reports that the method received an extra argument as soon as you call it.
Important Questions:
- What does
__init__()do? It runs when an instance is created and initializes the instance attributes. - What is the difference between a class attribute and an instance attribute? A class attribute is shared by every instance of the class, while each instance has its own copy of an instance attribute.
Chapter 12: Recursion
Difficulty: Hard · Key topics: recursive case, base case, factorial, strings and lists, Fibonacci numbers, binary search, Three Towers (Tower of Hanoi)
Recursion solves a problem by breaking it into smaller versions of itself, so a function calls itself with different inputs. The chapter explains the base case, which stops the calls, and the recursive case, which builds a larger answer from smaller ones. It works through the factorial function, then applies recursion to strings and lists, including the list count() method, and to more math problems such as Fibonacci numbers. The final section uses recursion for binary search on a sorted list and for the Three Towers puzzle, also known as the Tower of Hanoi, where three rings need seven moves.
Key Points:
- A recursive function calls itself with a smaller version of the problem.
- The base case stops the recursion; the recursive case moves the problem toward the base case.
- Factorial and Fibonacci numbers are classic recursive math examples.
- Binary search checks the middle item of a sorted list and then searches only one half, so each step discards about half of the remaining items.
- Three Towers: move the top N-1 rings out of the way, move the largest ring, then move the N-1 rings back on top; 3 rings need 7 moves.
Practice Tip: Write a recursive factorial and add a print() at the top of the function to show each input, so you can watch the calls go down to the base case and come back.
Common Mistake: Forgetting the base case, or not moving toward it. The function then keeps calling itself until Python stops it with a RecursionError.
Important Questions:
- What two parts does every recursive solution need? A base case that stops the calls and a recursive case that calls the function again with a smaller input.
- Why is binary search faster than checking every item? It compares with the middle item and throws away about half of the remaining list at each step, and it needs a sorted list.
Chapter 13: Inheritance
Difficulty: Hard · Key topics: inheritance, subclasses, super(), method overriding, polymorphism, hierarchical inheritance, multiple inheritance, mixin classes
Inheritance lets one class be a type of another, so a subclass receives attributes and methods from a superclass without rewriting them. The chapter shows how to declare a subclass, how to reach inherited attributes and methods, and how to override a method, using super() to call the superclass constructor or method. It explains polymorphism, where methods with the same name behave differently in different classes. The last two sections cover hierarchical inheritance, with several subclasses sharing one superclass, and multiple inheritance, including mixin classes that add small behaviors.
Key Points:
- Inheritance models an is-a relationship: a subclass is a type of its superclass.
- A subclass is declared by naming its superclass in parentheses after the class name.
super()lets a subclass call a superclass method, such as the superclass__init__().- A subclass overrides a method by defining a method with the same name.
- Polymorphism means one method name can take many forms across different classes.
- Hierarchical inheritance has several subclasses under one superclass; multiple inheritance lists more than one superclass, and mixins add small behaviors without a complex hierarchy.
Practice Tip: Create an Animal class with a speak() method, add two subclasses that override it, and loop over a list of mixed instances calling speak() on each.
Common Mistake: Overriding __init__() in a subclass without calling super().__init__(). The inherited attributes are then never set up.
Important Questions:
- Which relationship does inheritance model? An is-a relationship: for example, a subclass is a type of its superclass and can use its attributes and methods.
- What is a mixin class? A small class used with multiple inheritance to add behavior to a subclass without bringing in a complex inheritance structure.
Chapter 14: Files and Exceptions
Difficulty: Medium · Key topics: open(), reading and writing files, buffering, newlines, CSV files, try-except, raising exceptions
This chapter first shows how Python reads and writes files with the built-in open() function, including reading a whole file, one line or all lines, and writing or appending text. It warns that buffering can delay changes until a file is closed, and that newline characters must be removed when reading and added when writing. After files in different locations and CSV files, it turns to exceptions: try and except handle errors that would otherwise end a program, and raise lets a function signal that something went wrong.
Key Points:
open("myfile.txt")opens a file for reading,'w'opens it for writing and'a'opens it for appending;close()finishes the job.read()returns the whole file as one string,readline()the next line andreadlines()a list of lines.write()does not add a newline automatically, unlikeprint().- CSV (comma-separated values) is a common file format for data.
except ValueError as err:handles only aValueErrorand keeps its details inerr.raise ValueError("message")raises an exception with a custom message.
Practice Tip: Write three lines to notes.txt with write(), close the file, then read it back with readlines() and print each line without the extra blank lines.
Common Mistake: Opening a file with 'w' to add more lines. Mode 'w' replaces the old contents, so use 'a' to append.
Important Questions:
- What is the difference between opening a file with
'w'and with'a'?'w'writes from the start and replaces the old contents, while'a'adds new text at the end. - How do you handle only a
ValueError? Put the risky code in atryblock and follow it withexcept ValueError:, so other errors are not caught.
Chapter 15: Data Science
Difficulty: Medium · Key topics: data science life cycle, Google Colaboratory, NumPy, Pandas, DataFrame, exploratory data analysis, missing values, Matplotlib plots
The final chapter introduces data science, the field that collects, processes and analyzes large amounts of data to support decisions, and its four-stage life cycle of data acquisition, exploration, analysis and reporting. You work in Google Colaboratory, a cloud notebook, and meet NumPy for fast numerical work on ndarray objects and Pandas for Series and DataFrame tables. Later sections cover exploratory data analysis, including indexing, slicing, filtering and missing values, and finish with bar, line, scatter, histogram and box plots drawn with Matplotlib.
Key Points:
- The data science life cycle has four stages: data acquisition, data exploration, data analysis and reporting.
- NumPy’s
ndarrayholds data of one type and supports fast math and linear algebra; the usual import alias isnp. - Pandas provides the Series and DataFrame structures;
pd.read_csv()loads a CSV file andhead(),info()anddescribe()inspect it. loc[]selects by labels andiloc[]selects by integer positions.isnull()finds missing values,fillna()replaces them anddropna()removes the rows that contain them.plt.bar(),plt.plot(),plt.scatter(),plt.hist()andplt.boxplot()draw the five plot types.
Practice Tip: Load any small CSV file with pd.read_csv(), run head(), info() and describe(), then draw a histogram of one numeric column with plt.hist().
Common Mistake: Mixing up loc and iloc. The first works with labels and the second with integer positions, so the same number can select different rows.
Important Questions:
- What are the four stages of the data science life cycle? Data acquisition, data exploration, data analysis and reporting.
- What do
isnull(),fillna()anddropna()do?isnull()marks missing entries,fillna()replaces them with a value, anddropna()removes the rows that contain them.
Download Introduction to Python Programming PDF (Free)
Introduction to Python Programming is free from its official publisher, OpenStax. Click the button below to open the official OpenStax book page, where you can download the complete PDF or read every chapter online and try the exercises in the code runner.
↓ Download PDFHow to Study This Book
Introduction to Python Programming has 15 chapters and no appendix, and this page gives one block for each. The book does not group its chapters into parts. Each chapter is divided into 6 to 9 short sections, and each section has learning objectives, video-based animations that trace code step by step, learning questions that explain the wrong answers, and one or two programming practice exercises that run in an online code runner. Use the online edition for those interactive parts and the PDF when you want to read offline.
Start with Chapters 1 to 3. Chapter 1 covers print(), input(), variables and error messages, Chapter 2 adds expressions and type conversion, and Chapter 3 is the one to study slowly. Indexing, f-strings and the idea that a variable is a name for an object come back in every later chapter, and lists and tuples first appear here. Run every example in the shell before you move on.
Chapters 4 to 7 are the core of any programming fundamentals exam: decisions, loops, functions and modules. Read them in order, because loops use the conditions from Chapter 4 and functions use both. The prime number exercise at the end of Chapter 5 is a good test of whether you can combine a loop, a condition and break. In Chapter 6, spend extra time on variable scope and keyword arguments.
Chapters 8 to 10 give you the three data structures you will use all the time: strings, lists and dictionaries. Make a one-page cheat sheet of the methods in each chapter, such as find(), split(), append(), sort(), get() and items(). The reference table at the end of each chapter is a ready-made list for this.
Chapters 11 and 13 teach object-oriented programming and must be read in that order, because inheritance builds directly on classes. Chapter 12 on recursion only needs functions, strings and lists, so you can read it right after Chapter 9 if your course covers recursion earlier. Recursion is the hardest idea in the book for many students, so finish Sections 12.1 to 12.3 before you try binary search and the Three Towers puzzle.
Chapter 14 is very practical: files, CSV data and exceptions turn small exercises into programs that read real input safely. Chapter 15 is a first taste of data science with NumPy, Pandas and Matplotlib in Google Colaboratory, an online notebook. It is the natural bridge for BS Data Science students and optional for a plain programming fundamentals course.
Know what the book does not do. It is a first course, so there is no chapter on algorithm analysis, databases, web development or testing frameworks, and its object-oriented chapters stay at the introductory level. The interactive code runner and animations belong to the online edition. The examples are general ones, with no Pakistan-specific content, so add local examples when you practice.
Used In These Programs
This book is used for the Programming Fundamentals (Python) course in: BS Computer Science · BS Information Technology · BS Data Science. Browse all Python books or all Computer Science books.
Who Should Read This
Introduction to Python Programming is written for first-course students: BSCS, BSIT and BS Data Science students in their first semesters, and students of other programs who need Python for a business, social science or science course. It starts from the first print() and needs no earlier coding. It is not a book for readers who already program, and it does not replace a course in algorithms, databases or machine learning.
A second book helps when you want a different voice. Think Python teaches the same ideas with a more narrative style, and Python for Everybody goes further into working with data and the web. For practice with small useful scripts, try Automate the Boring Stuff with Python.
Applicable Universities
This book is useful for students at Pakistani universities offering BS Computer Science, BS Information Technology, BS Data Science and related programs, including Punjab University, Virtual University, COMSATS, FAST, UET, NUST, and other HEC-recognized institutions.
FAQs
Is Introduction to Python Programming by OpenStax free?
Yes. OpenStax publishes it under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) licence. You can read it online or download the PDF for free from openstax.org. You may share and adapt it for non-commercial use if you credit OpenStax and keep the same licence. The interactive code runner is a separate Wiley product that is not under that licence.
Which edition is this, and is it up to date?
OpenStax published the book on March 13, 2024, and it carries no edition number. It teaches core Python that changes slowly, such as variables, loops, functions, classes and file handling, so it is suitable for a first course today. Check the OpenStax book page for corrections or a newer version before you start.
Is this book good for complete beginners?
Yes. Chapter 1 begins with the idea of a program and the print() and input() functions, and the book builds one idea at a time. Each section has learning objectives and practice exercises. Chapters 11 to 13 on classes, recursion and inheritance are harder, so slow down there.
How many chapters and exercises does it have?
The book has 15 chapters, each divided into 6 to 9 short sections. Every section has learning questions that explain why wrong answers are wrong, and one or two programming practice exercises that run in an integrated code runner on the OpenStax website.
Does it include solved exercises or answers?
The learning questions explain the wrong answer choices, and the practice exercises show sample output you can compare with your own. The preface does not describe a full answer key for the programming exercises, so type your own solution first and then check it with a classmate or teacher.
Does it cover object-oriented programming and data science?
Yes. Chapters 11 and 13 cover classes, instances, operator overloading, inheritance and polymorphism. Chapter 15 introduces the data science life cycle, NumPy, Pandas, exploratory data analysis and plots with Matplotlib. Both topics are introductory, so use a specialist book for more depth.
Related Books
- Think Python (a more narrative introduction to the same first-course ideas)
- Python for Everybody (continues into working with data and the web)
- A Byte of Python (a short companion for quick revision of the basics)
- Automate the Boring Stuff with Python (practice with small, useful scripts)
Introduction to Python Programming gives BSCS, BSIT and BS Data Science students a free, complete first course in Python, from print() to classes, recursion, files and a first look at data science. Browse more Computer Science books or all University Books.
Introduction to Python Programming, by Udayan Das, Aubrey Lawson, Chris Mayfield and Narges Norouzi (senior contributing authors), with Yamuna Rajasekhar and Reed Kanemaru (contributing authors). OpenStax, Rice University, 2024. Free under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International licence (CC BY-NC-SA 4.0). Access for free at https://openstax.org/details/books/introduction-python-programming
© Copyright Policy
Freebooks.pk is an educational resource for students in Pakistan. Textbooks and other books belong to their respective boards, authors and publishers, and all rights remain with them. If you are the copyright holder of any material on this page and want it changed or removed, please contact us or file a request under our DMCA policy. We review every request and remove reported content promptly.
