PCEP Student Book
PCEP Student Book
ut
ib
Certified Entry-
tr
Level Python
is
D
Programmer
(PCEP™) or
e
at
lic
up
D
ot
N
o
D
e
ut
Part Number: 094027
Course Edition: 1.0
ib
Acknowledgements
tr
PROJECT TEAM
is
Author Content Editor
D
Jason Nufryk Michelle Farney
Logical Operations wishes to thank the Logical Operations Instructor Community for their instructional and technical expertise
during the creation of this course.
Notices
or
e
DISCLAIMER
at
While Logical Operations, Inc. takes care to ensure the accuracy and quality of these materials, we cannot guarantee their
accuracy, and all materials are provided without any warranty whatsoever, including, but not limited to, the implied warranties of
merchantability or fitness for a particular purpose. The name used in the data files for this course is that of a fictitious company. Any
lic
resemblance to current or future companies is purely coincidental. We do not believe we have used anyone's name in creating this
course, but if we have, please notify us and we will change the name in the next revision of the course. Logical Operations is an
independent provider of integrated training solutions for individuals, businesses, educational institutions, and government agencies.
The use of screenshots, photographs of another entity's products, or another entity's product name or service in this book is for
up
editorial purposes only. No such use should be construed to imply sponsorship or endorsement of the book by nor any affiliation of
such entity with Logical Operations. This courseware may contain links to sites on the Internet that are owned and operated by third
parties (the "External Sites"). Logical Operations is not responsible for the availability of, or the content located on or through, any
External Site. Please contact Logical Operations if you have any concerns regarding such links or External Sites.
D
TRADEMARK NOTICES
Logical Operations and the Logical Operations logo are trademarks of Logical Operations, Inc. and its affiliates.
ot
®
Python is a registered trademark of the Python Software Foundation (PSF) in the U.S. and other countries. All other product and
service names used may be common law or registered trademarks of their respective proprietors.
Copyright © 2023 Logical Operations, Inc. All rights reserved. Screenshots used for illustrative purposes are the property of the
N
software proprietor. This publication, or any part thereof, may not be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying, recording, storage in an information retrieval system, or otherwise, without
express written permission of Logical Operations, 1150 University Avenue, Suite 20, Rochester, NY 14607, 1-800-326-8724 in the
o
United States and Canada, 1-585-350-7000 in all other countries. Logical Operations’ World Wide Web site is located at
www.logicaloperations.com.
D
This book conveys no rights in the software or other products about which it was written; all use or licensing of such software or
other products is the responsibility of the user according to terms and conditions of the owner. Do not make illegal copies of books
or software. If you believe that this book, related materials, or any other Logical Operations materials are being reproduced or
transmitted without permission, please call 1-800-456-4677 in the United States and Canada, 1-585-350-7000 in all other countries.
e
ut
(PCEP™)
ib
tr
is
D
Lesson 1: Setting Up Python and Developing a Simple
or
Application.............................................................. 1
Topic A: Set Up the Development Environment............................... 2
e
Topic B: Write Python Statements................................................. 15
at
e
Appendix A: Mapping Course Content to PCEP™ – Certified Entry-
Level Python Programmer (Exam PCEP-30-02)............................ 151
ut
Mastery Builders................................................................................. 153
ib
Solutions............................................................................................ 165
tr
Glossary............................................................................................. 169
Index.................................................................................................. 173
is
D
or
e
at
lic
up
D
ot
N
o
D
e
ut
ib
Python® is one of the most widely used languages in software development today,
particularly within the fields of data science, machine learning, and web development.
tr
Seasoned programmers and new programmers alike can apply Python skills to accomplish
many different business goals. Python is an excellent choice of language for most
is
professionals, and it's especially valuable as a first language for anyone wanting to get into
programming.
D
In this course, you will apply the fundamentals of the Python 3 language and create simple
scripts that process data types and structures; interact with the user; perform tasks based on
decision-making logic; structure code for reuse; and handle errors.
Course Description or
Target Student
e
This course is designed for anyone with basic end-user computing skills who wants to start
at
learning the Python programming language in preparation for developing a wide range of
applications.
lic
This course is also designed to assist students in preparing for the Python Institute's
PCEP™ – Certified Entry-Level Python Programmer (PCEP-30-02) credential.
up
Course Prerequisites
Some experience programming in an object-oriented language is helpful, but not required.
This course will be useful to anyone new to programming.
D
To ensure your success in this course, you should have at least a foundational competence
with personal computing. You can obtain this level of skills and knowledge by taking one of
the following Logical Operations courses:
ot
Course Objectives
o
In this course, you will develop simple command-line programs in Python. You will:
D
e
• Classroom: A link to your training provider's classroom environment.
ut
• eBook: An interactive electronic version of the printed book for your course.
• Files: Any course files available to download.
• Checklists: Step-by-step procedures and general guidelines you can use as a reference during
ib
and after class.
• Assessment: A course assessment for your self-assessment of the course content.
tr
• Social media resources that enable you to collaborate with others in the learning community
using professional communications sites such as LinkedIn or microblogging tools such as
is
Twitter.
Depending on the nature of your course and the components chosen by your learning provider, the
D
CHOICE Course screen may also include access to elements such as:
• LogicalLABs, a virtual technical environment for your course.
• Various partner resources related to the courseware.
or
• Related certifications or credentials.
• A link to your training provider's website.
• Notices from the CHOICE administrator.
e
• Newsletters and other communications from your learning provider.
• Mentoring services.
at
Visit your CHOICE Home screen often to connect, communicate, and extend your learning
experience!
lic
As You Learn
This book is divided into lessons and topics, covering a subject or a set of related subjects. In most
cases, lessons are arranged in order of increasing proficiency.
D
The results-oriented topics include relevant and supporting information you need to master the
content. Each topic has various types of activities designed to enable you to solidify your
understanding of the informational material presented in the course. Information is provided for
ot
download from the CHOICE Course screen. In addition to sample data for the course exercises, the
course files may contain media components to enhance your learning and additional reference
materials for use both during and after the course.
o
Checklists of procedures and guidelines can be used during class and as after-class references when
D
As You Review
Any method of instruction is only as effective as the time and effort you, the student, are willing to
invest in it. In addition, some of the information that you learn in class may not be important to you
immediately, but it may become important later. For this reason, we encourage you to spend some
time reviewing the content of the course after your time in the classroom.
As a Reference
The organization and layout of this book make it an easy-to-use resource for future reference.
e
Taking advantage of the glossary, index, and table of contents, you can use this book as a first
source of definitions, background information, and summaries.
ut
Course Icons
ib
Watch throughout the material for the following visual cues.
Icon Description
tr
A Note provides additional information, guidance, or hints about a topic or task.
is
D
A Caution note makes you aware of places where you need to be particularly careful
with your actions, settings, or decisions so that you can be sure to get the desired
results of an activity or task.
or
Checklists provide job aids you can use after class as a reference to perform skills
e
back on the job. Access checklists from your CHOICE Course screen.
at
lic
Social notes remind you to check your CHOICE Course screen for opportunities to
interact with the CHOICE community using social media.
up
D
ot
N
o
D
e
ut
Application
ib
Lesson Time: 2 hours, 30 minutes
tr
is
D
Lesson Introduction
or
Before you start developing programming projects in Python®, you must set up a computer
with the tools you need. Once you have done so, you can create a new programming
project, and start writing and testing your code.
e
Lesson Objectives
at
lic
TOPIC A
Set Up the Development Environment
In this topic, you will acquaint yourself with the major versions of Python, as well the various
development environments available to you. With a development environment set up from the start,
you'll be able to write code more easily and efficiently.
e
ut
Types of Programs Developed in Python
Types of Programs Python is a general-purpose programming language and can be used to develop many different
ib
Developed in Python kinds of applications. Examples of the types of applications developed in Python include:
• Data analysis and forecasting tools
tr
• Artificial intelligence
• Web apps
is
• Video games
• Audio/video apps
D
• Mobile apps
• Networking apps
• Scientific/mathematical apps
• Security utilities
• Educational apps or
Python is one of the most popular programming languages in the world and many well-known
e
organizations use Python in developing their software. Google™, National Aeronautics and Space
Administration (NASA), and many others have used Python. The following is a list of apps you may
at
be familiar with that have been developed wholly or in part using Python.
• Instagram®, a popular photo/video-sharing social media app.
lic
History of Python
History of Python Python was created by Guido van Rossum in the late 1980s. He wanted to design a language that
ot
It's fine if students are was easy to read and required minimal lines of code as compared to other languages. Early versions
unfamiliar with these of the language were released over the next few years, but version 1.0 was not released until January
concepts. Some of them of 1994.
N
course is based on and assignment, list comprehension, and support for Unicode strings.
uses Python 3. The last release of Python 2 was Python 2.7.18 in April 2020. Although it was superseded by Python
D
Python was named after 3 many years ago, for various reasons some developers stayed with Python 2. This is especially true
British comedy troupe in enterprise environments that rely on specific libraries that were not immediately ported to Python
Monty Python. 3.
Python 3 is the most recent major version of the language. Python 3.11.6 was released in October
2023 and is being continually updated.
e
level language is the opposite—it offers little to no abstraction, making it harder for humans to read
ut
but easier for machines to understand.
So, a compiler translates source code into a lower-level programming language. The result is code
that is executable by the machine (saved as an .exe file, for example) before the program runs. This
ib
is also called an ahead-of-time (AOT) compiler, because all of the source code is translated before
execution. Interpreters, on the other hand, run source code directly. The definition of "interpreter"
tr
is somewhat fuzzy, and different types of interpreters accomplish this in different ways. However,
the main point is that interpreters execute code while the program is running (for example, line by
line).
is
Because of these differences, there are some tradeoffs between using compilers and interpreters.
Because the executable file is essentially ready to run directly on the machine, compiled programs
D
tend to run very quickly. Interpreted programs tend to run more slowly than compiled code due to
extra processing overhead needed at runtime. Also, code that includes certain types of errors that
prevent a program from running properly will not be visible to the programmer right away when the
or
code is being interpreted. Compare this to a compiled program, which must be compiled
successfully into an executable file without these errors. Of course, other types of errors may exist in
a program that successfully compiles.
e
There are, however, advantages to using an interpreter. Interpreters are generally easier to use than
compilers, particularly for those new to programming. Interpreted programs are generally more
at
"portable" than compiled programs. For example, the same Python script might run on a Windows®
or Linux® computer, whereas a compiled program would typically need to be recompiled from the
lic
source code in order to run it on a different operating system. Interpreted programs may be more
convenient to maintain and use in environments where software behavior must be frequently
revised, such as web servers, process automation, data analysis, and so forth.
up
D
ot
Compiler Interpreter
Operates on
N
source code so
• Translates code in it can be • Executes code
advance, compiling it executed directly, interpreting
o
Python Implementations
Python Implementations Over the years, numerous interpreters and compilers have been developed for Python. Here is just a
You may want to point handful of the many examples in use today.
out that just-in-time • CPython—The most widely used interpreter, with the interpreter itself developed using the C
compilers like PyPy
programming language.
combine the functionality
of traditional ahead-of- • Stackless Python—A fork of CPython that enables you to run hundreds of thousands of small
time (AOT) compilers tasks concurrently.
e
with interpreters. • PyPy—A just-in-time (JIT) compiler that translates only the code that the program needs
when it needs it, making it faster than CPython in some implementations.
ut
• Jython—An implementation of the Python language that runs on the Java virtual machine
(JVM), enabling seamless use of third-party Java™ libraries and other Java-based applications.
• ActivePython—A distribution of Python bundled with many supporting packages, hardened for
ib
cybersecurity, and with other features to support enterprise application development.
• IronPython—An implementation of the Python language developed in C# and based on
tr
Microsoft's .NET framework, enabling it to interact with .NET objects.
is
CPython
D
CPython The default interpreter implemented in Python is CPython, written in the C programming language.
Point out that CPython is CPython translates your Python code into bytecode—intermediary code designed to be efficiently
the interpreter used in executed by an interpreter—and this bytecode is executed by the CPython virtual machine.
this course.
distributions.
or
CPython is compatible with most major operating systems, including Windows, macOS®, and Linux
Note: Technically, the intermediate step of translating source code into bytecode is done by a
e
compiler. The CPython virtual machine is the core component of the interpreter. Still, Python is
considered an interpreted language because of that final interpretation step.
at
(compilation) (interpretation)
Python code 0 LOAD_NAME Program output
3 LOAD_CONST
up
6 CALL_FUNCTION
print("Hello, world!")
9 PRINT_EXPR
Hello, world!
12 LOAD_CONST
15 RETURN_VALUE+
D
duplicates the using software like VirtualBox and Hyper-V®. In the world of programming interpretation, a VM
functionality of a refers to an environment that controls the execution of intermediary code (like bytecode). It is
complete computer sometimes referred to as process or application virtualization to distinguish it from system or hardware
o
system. virtualization.
D
IDLE
IDLE IDLE is the default cross-platform integrated development environment (IDE) that comes with
certain installations of Python.
The IDLE source-code editor is very basic and is rarely used for serious coding. However, it does
include the following features:
• Code completion
• Smart indentation
• Syntax highlighting
Along with a source-code editor, IDLE also comes with a command shell for quick code execution
and a debugger for finding and testing errors.
Note: Python comes pre-installed on most Linux distributions, but IDLE is not necessarily
installed alongside it.
e
ut
ib
tr
is
D
Figure 1-3: The IDLE shell and source-code editor.
or
e
at
application is geared toward data cleaning and transformation, numerical simulation, statistical
modeling, data visualization, machine learning, and education. written.
• Python Tools for Visual Studio (PTVS)—A free plugin for Visual Studio®, developed by Ask students if they've
used any of the IDEs
ot
Microsoft® to provide rich support for all actively supported versions of Python. The tool
listed here. If they have,
supports Visual Studio's extensive feature set, including IntelliSense®; debugging; code
encourage them to
navigation, formatting, cleaning, and refactoring; variable explorer; test explorer; code snippets; share their opinions.
N
folding, smart language detection and code intelligence, debugging, split views, variable
highlighting, code snippets, macros, and user scripts.
D
IDE Configuration
IDE Configuration As a Python developer, you might have to work with programs written in various versions of
Python and would, therefore, have multiple versions of Python installed on your development
computer. You also have a choice when it comes to which IDE you will use.
Python interpreters and IDEs are typically separate software products, installed separately. For this
reason, when you are setting up a Python development environment, it is often necessary to
configure the IDE to be able to find the various interpreters installed on the computer.
e
Python Projects
ut
Python Projects Programming projects written in Python can become large and complex and may contain multiple
files. To keep things organized, they are often stored in a project folder. IDEs such as PyCharm
ib
typically include features that enable you to automatically create a new project folder when starting a
programming project.
tr
In addition to keeping things organized, the project folder has another purpose—to store support
files that enable you to configure the programming project with important information, such as
is
which version of Python should be used to interpret your source code.
Code written for one version of Python will not necessarily run on a different version of Python. To
D
enable your software development environment to know which Python interpreter to use, when you
create a new software project, you need to configure it to use a particular interpreter. This ensures
that the Python source code you are writing will be processed by the interpreter (and version of the
or
Python language) that you intend to use.
e
at
lic
up
D
ot
N
o
D
ACTIVITY 1-1
Running a Python Script
Data File
e
/home/student/094027Data/Setting Up Python and Developing a Simple Application/Finished/
ut
inventory_entry.py
ib
You have access to the course's Linux VM. Python and PyCharm are already installed in the VM.
Scenario
tr
The Fuller & Ackerman (F&A) publishing firm publishes a wide variety of books in various formats. Activity: Running a
F&A's product managers regularly access an inventory database that contains information about Python Script
is
each book title that F&A publishes. The data-entry system they currently use is slow, prone to
errors, and has limited functionality.
D
IT has collaborated with the product managers to produce a list of requirements for a new data-
entry program. They've also drafted a flow chart that shows how the program might be
implemented.
no
or The InventoryEntry
Program Flow Chart
Make sure students
e
Prompt user
no
program's logic.
selection
no no
menu
yes More no
Get next book Output book
Loop
yes
End of loop
no yes
doing behind the
scenes.
ot
Program Requirements
N
1. Prompts the user to select a task from a set of five main tasks.
• The set of tasks should be shown to the user in a menu.
o
• The user should be able to select a task quickly by entering a number associated with that
task, or by entering a verb of that task (e.g., "add" to add a book).
D
• The program should continually ask the user to select a task until the user deliberately exits
the program.
2. Prompts the user to add a book title to the inventory.
• The program should prompt the user to enter the ID and name of the book they're entering,
as well as the quantity and price of the book.
• The user must enter an ID of exactly 4 characters and cannot enter a book name longer than
30 characters.
• The user must enter valid quantity and sales numbers (e.g., no "half" quantities).
3. Prompts the user to update a book title in the inventory.
• The program should prompt the user for the ID of the book they want to update.
• The program should also prompt the user to update the name, quantity, and price.
• The user must enter a book ID that already exists, or else they won't be able to update
anything.
e
4. Prompts the user to delete a book title in the inventory.
ut
• The program should prompt the user for the ID of the book they want to delete.
• The user must be shown what book they're about to delete, and the user must confirm
deletion.
ib
5. Shows a table of all book titles in the inventory, along with their details.
• The table should have a header with column labels for each field.
tr
• The table should print each book title as a row, with each field displayed.
6. Summarizes the books in the inventory using various statistics.
is
• The program should output the total number of book titles in the inventory.
• The program should output the total quantity of all books in the inventory.
D
• The program should output the average price of all book titles in the inventory.
To see an example of a working Python program and to get familiar with the one you'll build in this
or
course, you'll start by running a copy of the finished program. As this is a proof of concept, it
doesn't currently connect to the product database; you plan to do that later.
e
1. Start the VM and launch a Linux command shell.
at
c) Wait as the virtual machine finishes loading and the operating system starts.
up
D
ot
N
o
D
d) On the desktop, double-click the QTerminal icon to launch the command shell.
This changes the current working directory to the location where the course data files are located. If You may need to slow
they have been set up in a different location, your instructor will guide you through the steps to down and explain these
navigate to the right location. steps as some students
b) Type ls -l and press Enter to see a directory listing of this location. may have little or no
experience issuing
e
commands at a
command shell/prompt.
ut
ib
tr
is
D
or
Caution: This command uses the lowercase letter "L", not the number one.
e
at
This lists the files and subdirectories contained in the current working directory. Each directory
contains the files for a lesson in the course. The project that contains the script you want to run is
located within the Setting Up Python and Developing a Simple Application folder. This is a long
lic
name for a directory, but to reduce some typing, you can use tab completion.
c) Type cd Set and then press Tab.
The rest of the folder name is completed automatically.
up
This directory contains a finished version of the project you will create in this course. It has one file:
inventory_entry.py. This file is a Python script that contains the actual program you will run.
e
ut
ib
• This issues the python3 command, which loads the Python interpreter. Linux distributions often
come with both Python 2 and Python 3; loading the former is usually done by entering the
tr
python command, without a number.
• Because you passed in the name of the script inventory_entry.py, that script is loaded into
is
the Python interpreter, translated into bytecode, and then executed by the Python virtual
machine.
• The program displays a welcome message and a menu for selecting the desired task.
D
b) Type 1 and press Enter.
A prompt appears, asking what the ID is of the book you'd like to add to the inventory.
c) Type F123 and press Enter.
or
You are then prompted to enter the name of the book.
d) Type The Open Boat and press Enter.
You are then prompted to enter the quantity of the book.
e
e) Type 100 and press Enter.
at
e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D
ACTIVITY 1-2
Setting Up the Python Development
Environment
e
Scenario
ut
Activity: Setting Up the As you've seen, you can run a Python program directly from a Linux shell, or any other command
Python Development shell for that matter. With a simple text editor, you can create your own Python applications and run
Environment them from the command shell. However, there are benefits to using an integrated development
ib
environment (IDE) like PyCharm, particularly when you are first learning Python.
The Python 3.10 interpreter and the PyCharm IDE have both been installed in the VM. Before you
tr
start developing any project, you need to configure the IDE with the directory paths to any Python
interpreters that you plan to use for development. Then when you create a new project, you can
is
identify the specific Python interpreter you will use to develop your program.
D
1. Start creating a new project.
a) From your Linux desktop, double-click the PyCharm shortcut.
or
Note: PyCharm defaults to a dark color theme, but the screenshots in this
course show a light color theme for readability purposes. If desired, you can
change the theme by selecting Customize from the left menu.
e
b) From the Welcome to PyCharm window, select New Project.
at
c) On the New Project page, to the right of the Location text box, select the Browse button.
d) In the Select Base Directory dialog box, select the /home/student/094027Data/Setting Up Python
and Developing a Simple Application directory as shown.
lic
up
D
ot
N
o
D
e
ut
ib
f) For the folder name, type InventoryEntry and select OK.
The InventoryEntry folder is created and automatically selected.
g) Select OK to specify the InventoryEntry folder you just created as the base directory for the project.
tr
h) Verify that this location is now populated in the Location text box.
is
2. Select the appropriate Python interpreter and create the project.
a) Select Previously configured interpreter.
D
b) Select Add Interpreter, then select Add Local Interpreter. A discussion of virtual
c) In the Add Python Interpreter dialog box, from the menu on the left, select System Interpreter. environments is beyond
the scope of this course,
d) Verify that /usr/bin/python3.10 is listed in the text box.
e) Select OK.
The interpreter is now selected.
or
This is the location of the Python interpreter installed in the Linux-based virtual machine.
so students will just use
the base Python
installation. You may
want to mention that, in
e
f) Uncheck the Create a main.py welcome script check box. a production
environment, using
at
g) Select Create.
virtual environments is a
h) If the Tip of the Day dialog box is shown, check the Don't show tips on startup check box, then best practice.
select Close.
lic
d) Verify that the editor pane is open to your newly created file, inventory_entry.py.
e
ut
ib
The inventory_entry.py file is currently empty. This is where you will begin typing your Python code
in the activities to follow.
tr
4. Leave PyCharm open.
is
D
or
e
at
lic
up
D
ot
N
o
D
TOPIC B
Write Python Statements
Now that you have your development environment set up and ready to go, you can begin writing
Python code. Before you tackle a full-fledged application, however, you should become familiar with
how Python works by executing basic and common statements.
e
ut
Interactive Mode
Most programs are written in a source-code editor and saved to a file. The Python interpreter then Interactive Mode
ib
executes all of the code in this file. This is considered the normal mode of operation. However, you
can also invoke the interpreter in interactive mode. The interpreter is in interactive mode when it
tr
presents a command prompt/shell to the user. The user is able to type statements directly into the
interpreter and receive immediate feedback for each statement. This is true of statements that
wouldn't otherwise provide feedback if run in normal mode. For example, running 2 + 2 in the
is
interactive shell will return 4 as a result. Executing that same statement and nothing else in normal
mode will not return anything, despite it running the computation.
D
Interactive mode uses >>> to signify that it is ready to receive a command from the user. After
typing a statement and pressing Enter, it will return a value, if applicable. Either way, it will offer
another >>> prompt to the user. Interactive mode also enables you to type in multi-line statements;
or
the ... symbol signifies a prompt that is continued from the previous one.
Interactive mode is useful as a way to test out certain commands without having to create an entirely
new file for the interpreter to run. The feedback that the interactive shell provides is also beneficial
e
for debugging snippets of code.
at
lic
Statement entered
up
Result returned
Next prompt
D
ot
N
o
D
Help
While in interactive mode, you can invoke the help() function in order to search Python's Help
documentation. This is particularly useful if there's a topic you want more information on, or if
there's an object in your code you want to learn more about. To begin an interactive help session,
simply enter help(). You'll then be greeted by the help utility and from here you can search more
about specific objects and topics.
You can also directly access help information about objects that you've defined. To do this, enter
help(object) at the interactive shell, replacing object with whatever object you want more
information on.
e
ut
Interactive
help
ib
tr
is
D
Getting help
or
e
on a variable Variable identified
as an integer
at
lic
Python Syntax
D
Python Syntax All programming languages have a syntax, or the rules that define how you write the code. Each
language has its own syntax, but many share a few commonalities. Python's syntax has a lot in
common with languages like C, Java, and Perl. Nevertheless, there are differences. For example,
ot
Perl's design philosophy suggests that there should be more than one way to write code to
accomplish the same task. Python's philosophy is that there should be only one obvious way to do
something.
N
Another core principle of Python is that it should be easily readable. Whereas many languages use
curly braces {} to block off code in multiple lines, Python makes explicit use of indentation. In
o
Python, you are required to indent certain blocks of code. The amount of spaces or tabs you use to
create the indent can vary, but you must be consistent in each block. For example, observe the
D
Another way that Python attempts to improve readability is by using English words where other
languages would use punctuation. Python's simplistic syntax makes it an excellent first programming
language for beginners.
e
Python's semantics defines the meaning of its tokens and of larger statements comprising multiple
ut
tokens. It influences how the interpreter interprets the lines of code that the programmer has
written.
ib
Variables and Assignment
tr
A variable is any value that is stored in memory and given a name, known as an identifier. In your Variables and
code, you can assign values to these variables. Assignment
is
Many programming languages, like C, require you to define the type of variable before you assign it
to a value. Examples of types include integers, floats, strings, and more. Essentially, these types
D
define exactly what kind of information the variable holds. However, in Python, you don't have to
declare variable types. Instead, once you assign a value to a variable, that type is defined
automatically.
or
To assign a value to a variable, you use an equals sign (=). The element to the left of the = is the
identifier or name of the variable, and the element to the right of the = is its value. Take a look at the
following code:
Let students know that
they will learn more
about variable types
later in the course.
e
count = 1
This instructs Python to name the variable count and assign it a value of 1. Because 1 is an integer,
at
proposes a new feature be added to the language. Community members can write a PEP based on
the existing standard, and, if approved, it will become officially part of Python's documentation.
Python creator Guido van Rossum has the final say on whether or not a PEP is approved.
ot
Python has many active PEPs, each of which is numbered. One of the most useful PEPs is PEP 8,
officially titled "Style Guide for Python Code." This style guide prescribes a wide array of best
N
practices for writing code in Python to enhance readability, as decided by both van Rossum and
community consensus. While adhering to these conventions is not required for programmers, the
Python community generally follows them.
o
Based on PEP 8, you should always define variables in lowercase format. If necessary, you can
D
Constants
Constants are identifiers with values that should not be changed. In Python, you create a constant
the same way you create a variable, but signify that it should be treated as a constant value by using
uppercase letters.
e
• Correct: PI_CONSTANT = 3.14159
• Incorrect: pi_constant = 3.14159
ut
Note: Creating a variable with an uppercase name does not prevent its value from being
changed. It is simply a reminder to the programmer. You may be familiar with other
ib
programming languages that enable you to define a constant value that cannot be changed. In
Python, you store such values in a variable, and you must be careful not to inadvertently change
the value once you've initialized it.
tr
is
Keywords
Although you can typically use whatever words you like to identify your variables and other objects,
D
Keywords
some words are reserved by Python. If you try to use any of these reserved words, also known as
keywords, to define your own objects, Python will give you an error and your code will fail to
execute. The following table lists the reserved words.
False
None
elif
else
or lambda
nonlocal
e
True except not
at
and finally or
as for pass
lic
class if try
continue import while
D
def in with
del is yield
ot
These words are case sensitive. You could conceivably create a variable named true or For, but this
is a poor coding practice.
N
Arithmetic Operators
o
Arithmetic Operators Operators are objects that can evaluate expressions in a variety of ways. The values that are being
operated on are called the operands. A simple example is in the expression 2 + 4. The + symbol is
D
e
//
operand and returns the nearest whole
ut
number that is less than or equal to the
division result. This is called floor
division.
ib
% Divides the left operand by the right 13 % 4 will return 1.
operand and returns the remainder.
tr
This is called modulo.
** Performs exponential calculation using 2 ** 4 will return 16.
is
the left operand as a base and the right
operand as an exponent.
D
Arithmetic Order of Operations
or
When programming languages like Python evaluate expressions, they don't always do so from left to
right. Instead, certain operators are executed before others. This order of operations, also known
as operator precedence, determines what parts of a complex expression are acted on first, second,
Arithmetic Order of
Operations
Consider having
e
third, and so on. For example, without a clear order of operations, this expression: students open up a
Python shell and play
2 + 4 * 8
at
order of operations.
• Evaluated with multiplication first, the answer is 34.
Python has the following order of operations for arithmetic, from first to last:
up
• **
• * / // %
• +-
D
As you can see, some operators are on the same level as others. In deciding between these, Python
evaluates from left to right. For example, 4 / 2 * 6 will result in 12. This is because both
multiplication and division are at the same order, so Python evaluates 4 / 2 first, then multiplies
ot
that result by 6.
When you chain multiple exponents together, such as in 4 ** 3 ** 2, Python actually evaluates
these from right to left. The result in this case is 262144.
N
In these types of instances, you can also force Python to evaluate certain chunks of an expression
over others. You can do this by wrapping the chunk in parentheses. For example, 4 / (2 * 6) will
o
now result in .333 repeating because the parentheses are telling Python to evaluate 2 * 6 first.
D
Python also supports an alternative unary mode. In unary operations, an operator performs an
operation on a single operand.
There are two types of operators that can work with unary operations, but really only one is
relevant. The first is addition with a single operand. For example:
+4
The result is 4. The + operator in this case is just making the number positive. That's all its unary
operation does. The thing is, numbers without a minus sign are by default considered positive, so
this construction is not useful in most cases.
e
The other unary operation uses the minus sign - to make an operand negative. For example:
ut
-4
The result is -4. So why might you use this? Consider the following two expressions:
ib
4 - 6
4 + -6
tr
Both result in -2. The first expression subtracts 6 from 4, whereas the second adds −6 to 4. In some
cases, you may want to negate the values you're working with so that you don't have to change the
is
other operators in the expression. This negation is a unary operation.
D
Quotes and String A string literal is any value that is enclosed in single (') or double (") quotation marks. Which you
Literals
String formatting is
discussed in greater
depth in a later lesson.
a = "Hello"
b = 'Hello'
or
choose is up to you, but you must be consistent within the string itself. For example:
Both a and b are the same. a = "Hello' will cause an error because the string literal is not enclosed
e
properly. However, you can still use both characters within a properly enclosed string literal. For
at
a = """Hello,
world!"""
up
When printed to the screen, this will show "Hello," and "world!" on separate lines.
Escape Codes
D
Escape Codes When creating string literals, there are times when you'll want to include characters that are difficult
to represent. For example, say you want to include double quotes ("") within the string literal itself,
while still wrapping it in double quotes:
ot
instance of the double quotes, but the text continues. This is where escape codes, also known as
escape characters, come in handy. Python interprets escape codes in a string literal as a certain
command, and executes that command on the string. Using double quotes as an example:
o
The \" character is the escape code, and this particular escape code is telling Python to add a double
quote at two different locations. The output would be:
This is a "string literal."
All escape codes begin with a backslash (\). The following table lists some of the escape codes in
Python.
\\ Backslash character.
\' Single-quote character.
\" Double-quote character.
\b Backspace character.
\f Page-break character.
e
\n Line-break character.
ut
\r Carriage-return character.
\t Horizontal-tab character.
ib
\v Vertical-tab character.
tr
Note: For more Python escape codes, see https://docs.python.org/3.9/reference/
lexical_analysis.html#string-and-bytes-literals.
is
D
or
e
at
lic
up
D
ot
N
o
D
ACTIVITY 1-3
Writing Python Statements
e
PyCharm is running and the InventoryEntry project is open.
ut
Scenario
Activity: Writing Python Now that you have your environment set up, you're ready to begin writing Python code. A good
ib
Statements place to start practicing your code is from the interactive shell, as this will give you immediate
feedback. In this activity, you'll work with some of the fundamentals of coding that all apps are built
on—creating variables, assigning values, and performing operations.
tr
Throughout this activity,
encourage students to
is
guess the results of their 1. Open the interactive shell.
input before they enter
the code into the
D
a) Select the Main Menu icon in the top left of the PyCharm window, then select Tools→Python or
command prompt.
Debug Console.
b) Examine the Python Console tab shown at the bottom of the PyCharm window.
or
e
at
lic
up
• The Python console provides an interactive shell, a text-based console in which you can type
commands and see results immediately.
• The variable list is a debugging tool that provides status information about data values you are
ot
working with.
a) Select the Show Variables button a few times, and observe the effect it has on the layout of the
Python console.
e
Show Variables
ut
ib
tr
is
D
This is a toggle button that changes the visibility of the variable list, like an on/off switch.
b) Verify that the three toggle buttons are selected as shown.
Soft-Wrap or
e
Scroll to End
at
Show Variables
lic
up
D
ot
N
• Enabling the Soft-Wrap setting causes lines of text in the Python console to wrap around when
the text reaches the right edge. If this option was not selected, you might have to scroll
horizontally to see text that has run past the right edge.
o
• Enabling the Scroll to End setting causes the Python console to scroll automatically as new text
is output to the console to ensure you're always looking at the most recent prompts and
D
messages.
• Enabling the Show Variables setting displays the values of variables in your program as you run
it, which can be helpful for testing and debugging.
b) In the console itself, select the text highlighted in green that says Python Console.
e
ut
ib
Show info
tr
is
By default, PyCharm hides some of the console information at the top, including the first input.
Selecting this highlighted text shows that information and your input again.
c) At the command prompt, type b = 10 and press Enter.
D
d) Observe the current state of the variables.
or
e
at
lic
c) In the space provided, write your prediction of the value that should be returned by the statement:
a + b * a / b
______________________________________
d) Enter a + b * a / b and compare the result to the value you predicted.
Students should get
5. Output a string literal to the console. 10.0 as the result.
Explain how this is
a) Right-click the Python console and select Clear All.
produced based on the
b) In the variable list, examine the values shown for a and b.
e
order of operations. If
Even though you cleared the output, the values of a and b have been retained. students ask about the
ut
c) At the command prompt, enter a = "Hello, world!" decimal point, let them
know they'll learn more
d) Verify that, in the variable list, the variable a changed.
in a later lesson.
e) At the command prompt, enter a
ib
f) Verify that Python outputs 'Hello, world!' to the console.
tr
6. From the Python Console tab, select Close tab.
is
Close tab
D
or
e
at
lic
up
D
ot
N
o
D
TOPIC C
Create a Python Application
You're ready to move beyond simple statements and into the world of self-contained applications.
In this topic, you'll write code that is common to nearly all Python applications.
e
Python Scripts and Files
ut
Python Scripts and Files Python's normal, non-interactive mode of operation is to save source code to a file. This file is also
called a script and typically has the extension .py. The Python interpreter executes all of the code in
ib
this script and runs the program. In interactive mode, you typically stay inside the Python shell, but
you can enter into a separate user interface by executing a script. This is how most developers create
tr
their Python applications.
Python source code can only be run if the Python interpreter is installed on the operating system.
is
However, certain tools are available that enable you to convert your source code into OS-specific
executables that don't require Python in order to run. For example, Windows does not come with
Python; there are tools that can convert a .py to a .exe, enabling a Windows user without Python to
D
run the application.
Figure 1-7: The file properties of a Python script alongside the contents of that script.
ot
Comments
Comments Comments are the programmer's way of annotating the source code that they are writing. The main
purpose of comments is to make code easier to understand to human developers. The interpreter
(or compiler) will ignore comments, and only someone with access to the source code will see them.
There are several different ways programmers use comments:
• To clarify how or why a line of code does something.
• To clarify how or why a block of code does something or how it can be used elsewhere.
• To indicate any areas where code can be improved or expanded upon in the future.
Comments are, therefore, essential to every app, especially large, complex apps that will be handled
by multiple developers. However, you should exercise careful judgment in using comments.
Comments that state the obvious are a waste of space and do not add to the overall readability of
e
code. For example, initializing a variable eye_color = "blue" is self-explanatory and would
usually not warrant a comment.
ut
In Python, you use the number sign (#) to declare that a line is going to contain comments for the
interpreter to ignore. For example:
ib
# User hasn't yet exited the window.
done = False
tr
This is called a block comment. You can also place comments on lines that already contain
interpretable code, called an inline comment. For example:
is
done = False # User hasn't yet exited the window.
According to Python's style guide, block comments are preferable to inline comments.
D
Most IDEs will clearly differentiate the color of comment text from the color of normal code.
Functions
or
A function is a block of code that you can reuse to perform a specific task. This is a vital part of
writing efficient code, as calling a function can save you from having to write out the same or similar
Functions
Defining and calling
e
code over and over. You can define your own functions, and Python has a number of built-in functions will be
functions that you can call at any time. discussed in a later
at
lesson.
Like variables, you define a function with a unique identifier. After this identifier, you must place
open and closing parentheses (). For example, the help utility mentioned earlier, help(), is a
lic
function.
Note: For a complete list of built-in functions, see https://docs.python.org/3.9/library/
functions.html.
up
The print() function is a built-in function that outputs a given value to the command line. As it is The print() Function
a function, it must end with open and closing parentheses. Inside these parentheses, you can place Function arguments/
ot
whatever you wish to output. For example, print("Hello, world!") will output the text parameters will be
Hello, world! The print() function can also output other data types, as well as the value of discussed in a later
variables. Take this code: lesson.
N
a = 1
print(a)
You are assigning variable a to an integer with a value of 1. You then print the value of a, so the
o
number 1 is output to the command line. The following is what it looks like running from
D
interactive mode.
e
ut
Separators and End Characters
Separators and End You can also exercise more control over how the print() function works by supplying separators
ib
Characters and end characters.
You can supply more than one value to the print() function at a time as long as you separate each
tr
value by a comma. For example:
a = "Hello"
is
b = "world"
print(a, b)
D
The result is: Hello world
The print() function combined the two variables using the default separator: a space. However,
you can change this separator by using sep= and then supplying any string literal you want to
separate by. For example:
print(a, b, sep=", ")
The result is: Hello, world
or
e
The sep=", " instructed the print() function to add a comma and a space between a and b.
at
You can also add characters to the end of the print() output by using end= and then supplying any
string literal. For example:
lic
Note: The default end= value is "\n", which is the escape code for a line break. Supplying
end="!" will remove this line break. You could write end="!\n" to include the line break
after the exclamation point.
D
The input() Function Most applications are designed to accept some type of user input. The input() function enables
you to present the user with a command prompt and accept the value that they enter into that
prompt. The following is an example of input() syntax:
N
string. The following is what it looks like running from a script, with the user's name printed back to
D
them.
e
ut
Prompt
User input
ib
Printed output
tr
is
Figure 1-9: Accepting user input and printing it back to them.
D
Multiple input() Functions
Multiple input() functions execute in sequential order as they appear in the source code. For
example:
name = input("What is your name?\n")
quest = input("What is your quest?\n")
color = input("What is your favorite color?\n")
or
e
The program will first prompt the user for their name. After receiving the user's input, the program
at
will then do the same for their quest and then their favorite color.
lic
up
D
ot
N
o
D
ACTIVITY 1-4
Creating a Python Application
e
PyCharm is running, the InventoryEntry project is open, and the empty script inventory_entry.py
ut
is open in the editor.
Scenario
ib
Activity: Creating a You've reviewed the requirements of the InventoryEntry project, and have a good idea of the
Python Application functionality it needs to provide. You've already created a Python project, including a file to contain
the main script, where you'll start writing Python code to implement the InventoryEntry program.
tr
You'll start by writing code to perform simple input and output tasks.
is
Note: You'll be developing this program all throughout the course.
D
1. Add comments that describe the program's function.
or
a) In the editor, type the comments as shown.
e
at
lic
b) Verify that PyCharm grays out and italicizes the two lines, indicating a comment.
up
PyCharm's code-
completion pop-ups as
they type. This course
assumes students won't
ot
be using code
completion, so you may
want to encourage
N
use code completion, be When the program runs, the user will type the ID of the book they want to add to the inventory. This
prepared to help them statement assigns the variable book_id to whatever the user types in.
D
e
ut
• Line 6, a comment, explains what the next line does.
• Line 7 prints the user's input to the console.
ib
4. Run your Python script.
tr
a) Within the inventory_entry.py editor pane, right-click and select Run 'inventory_entry.py'.
Note: You don't need to manually save the source code yourself. PyCharm
is
automatically does this after any change.
D
PyCharm opens the Run pane at the bottom of the screen.
b) Examine the Run pane.
or
e
at
lic
up
• In the Run pane, you can see the command that PyCharm issued behind the scenes to run the
D
Python interpreter (pyhon3.10). The program file that you wanted to run (inventory_entry.py) was
passed to the interpreter.
• Based on the source code you wrote, the Python interpreter created an executable program and
ot
ran it, and the running program has produced output in the Run pane.
• The prompt you produced using the input() function is displayed in the Run pane.
c) Click in the Run pane to select it for typing.
N
o
D
e
ut
ib
tr
e) Verify that Python returned your input back to you.
is
Note: Process finished with exit code 0 means that Python was able to
exit the program without any errors. Other exit codes like 1 or -1 would
D
indicate errors.
or
a) In the editor pane, type additional input and print statements on lines 9 through 19 as shown.
e
at
lic
up
D
ot
N
o
D
Rerun
'inventory_entry'
e
ut
ib
tr
The text in the Run pane is cleared, and the new version of the program runs.
is
6. Test out the program.
a) At the first prompt, enter 1234
D
or
e
at
As before, the input is sent back to you. However, a new input prompt opens up directly after.
b) At the second prompt, enter The Open Boat
lic
Close tab
D
ot
N
o
D
e
and can be accessed
and executed directly
ut
from the operating
system like any other
file.
ib
tr
is
D
or
e
In addition to the Python file that contains your source code, the PyCharm editor automatically
at
Note: Normally, you would not need to directly edit the files in the .idea folder,
which are maintained automatically by the IDE.
lic
e
ut
ib
tr
is
D
• This is the Python script you were just working on, saved as an individual file.
•
or
It has the typical properties of a file, including the size, the creation date, and the default program
it opens with.
f) Close the File Properties dialog box.
e
8. Examine the project files from the command line.
at
outside of an editor like PyCharm, you might view the Python project files from the terminal, like this.
This command uses the Python interpreter directly to run your script. The script runs, and the first
prompt is displayed in the command console.
Note: When Linux was installed, the directory path for the Python installation
was added to the computer's environment variables, so you don't have to type
the complete path every time you run a Python command.
b) At the various prompts, enter the same input you did before.
e
ut
ib
The program completes, and you are returned to the terminal.
Note: When running from the terminal like this, the return code is not shown.
tr
c) Enter the exit command to quit the terminal.
is
d) Select Yes to confirm.
e) Close the file-browser window and return to the PyCharm IDE.
D
or
e
at
lic
up
D
ot
N
o
D
TOPIC D
Prevent Errors
Whether you're new to programming or have been coding for years, you're bound to make mistakes.
In this topic, you'll learn about the different types of errors you'll encounter in Python. Then, you'll
put good coding practices into use to stop errors from arising. As you develop your program
e
throughout this course, you'll be better equipped to stop errors from becoming an obstacle to your
ut
progress.
Errors
ib
In a program, an error refers to some sort of incorrect or unintended result after the execution or Errors
tr
attempted execution of code. Errors are an unavoidable reality in programming, and Python is as Exceptions are
susceptible to these pitfalls as any other language. In Python, errors are usually put into three discussed at the end of
categories: the course.
is
• Syntax errors
• Logic errors
D
• Exceptions
Syntax Errors
or
A syntax error occurs when Python is unable to interpret some piece of code that you've written.
These are relatively common, as human programmers often mistype or misspell statements, or they
Syntax Errors
e
forget to add proper indentation and other formatting to their lines. Syntax errors almost always
at
result in the program failing to execute and tend to be relatively obvious to spot and easy to correct.
Thankfully, most modern IDEs will immediately anticipate syntax errors before you execute the
program. Many will highlight the offending words or statements, usually in red, to signify that you
lic
Figure 1-10: A syntax error (missing colon) identified in the IDE as the code is being written.
N
Logic Errors
o
A logic error is much more difficult to find and predict. These produce unintended results due to Logic Errors
D
incorrectly implemented code. Even though the code is free of syntax errors and executes without
fail, what the code actually does is wrong. Therefore, Python won't necessarily warn you that you
have a problem that needs fixing. Take the following code as an example:
fav_number = input("What is your favorite number?")
fav_color = input("What is your favorite number?")
print(fav_number)
print(fav_color)
The code will execute without any syntax errors, but the fav_color input is asking the wrong
question. This will confuse the user and the program will fail to perform its intended function.
Therefore, the program is in error. These types of errors are why complex programs require
extensive testing before they are finalized.
e
Use the following guidelines to help you prevent errors in your Python programs.
ut
Guidelines for
Preventing Errors Note: All Guidelines for this lesson are available as checklists from the Checklist tile on the
CHOICE Course screen.
ib
Loops, conditional
statements, and other Prevent Syntax Errors
tr
objects will be discussed
later in the course.
To prevent errors in syntax:
is
• Use an IDE with error indicators to detect syntax errors before execution.
• Use an IDE with code suggestion or completion to help you resolve syntax errors.
D
• Type carefully, and always remember to indent loops, conditional statements, function
definitions, and other such statements.
• Remember to add a colon at the end of the first line of most of these statements.
or
• Know Python's keywords list so you don't accidentally try to use one as a variable.
• Try to envision how a block of code could affect the whole program if it fails to execute as
intended.
lic
or uncommon input.
D
ot
N
o
D
ACTIVITY 1-5
Preventing Errors
Data File
e
/home/student/094027Data/Setting Up Python and Developing a Simple Application/Errors/
ut
inventory_entry.py
ib
PyCharm is running and the InventoryEntry project is open.
Scenario
tr
Making mistakes is perfectly normal, and fortunately, IDEs like PyCharm are great for helping you Activity: Preventing
spot and resolve these errors. In this activity, you'll open a slightly different version of Errors
is
inventory_entry.py that contains some errors. With PyCharm's help, you'll fix the errors and get
the program running properly.
D
1. Open a version of the InventoryEntry project that contains errors.
a) In PyCharm, select Main Menu→Close Project.
or
This closes the project you were working on, but leaves PyCharm running. You are returned to the
Welcome to PyCharm window.
e
b) Select Open, and beneath the /home/student/094027Data/Setting Up Python and Developing a
Simple Application directory, select the Errors directory.
at
c) Select OK.
d) In the Trust and Open Project 'Errors'? dialog box, check the Trust projects in... check box, then
select Trust Project.
lic
e) Select OK.
f) In the Project pane, double-click inventory_entry.py to open the file for editing.
up
2. Attempt to run the program, and verify that Python produces a syntax error in
the console.
a) Within the inventory_entry.py editor pane, right-click and select Run 'inventory_entry'.
D
b) At the top right of the source code, examine the error count.
Error count
e
ut
ib
tr
PyCharm has found numerous errors in the code.
c) Along the right edge, examine the markers showing lines that contain errors.
is
D
or
e
at
lic
up
d) Point at the error marker at the end of line 9, and wait a moment.
D
Point
ot
here
N
o
Marker
gone
e
ut
ib
tr
5. Fix the remaining syntax errors.
is
a) On line 11, point at the underlined word println.
D
or
e
at
Python's print function is just print(). There is no println() function in the language.
lic
You didn't define bookquant, but you did define a book_quant variable (notice the underscore).
Mistakes like these are often the result of typos or forgetting the exact name of a variable. If the
o
e
ut
ib
Note: You may need to select elsewhere in the source code for the error
indicator to go away.
tr
Make sure students
is
have fixed all of the 6. Test your program to make sure it runs properly.
syntax errors before
a) Run the program.
proceeding.
D
b) Enter 1234 at the first prompt.
c) When you're asked to enter the book name, enter The Open Boat
d) Observe that the resulting print line isn't repeating your The Open Boat answer, but says 1234.
7.
e)
or
In your source code, examine the print statement on line 11.
Why does the program print the wrong value? How can you fix this statement
e
to get the program to print the right value?
at
A: The print statement prints book_id, which is the first input. You can change the statement to say
print(book_name) to get the program to print the second input.
Make sure students
lic
e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D
Summary
In this lesson, you set up your Python environment to better prepare yourself for development. You
then explored some fundamental variable assignments and math operations in the interactive shell.
Finally, you used the code editor to save and run a Python script. These tasks are the foundation on
which you will build your Python applications.
Encourage students to
What about Python is different from the other programming languages you've
e
use the social
networking tools used or have heard of?
ut
provided on the CHOICE A: Answers will vary. Programmers coming from a language like C or Java may be tripped up by Python's
Course screen to follow requirement for indentation. As they progress through the course and learn about loops, functions,
up with their peers after
etc., they will need to be mindful of this. Students may also recognize that Python places more of an
ib
the course is completed
emphasis on readability and brevity than other languages. While some programming languages are
for further discussion
and resources to support geared toward one or a few use cases, Python is general purpose, so it can be used to write many
tr
continued learning. different kinds of software.
When do you think you'll use interactive mode versus running a Python script
is
normally?
A: Answers will vary. Students will likely want to test out new functions or statements in an interactive
D
shell first, as this will give them instant feedback. They may also prefer the shell when they need to do
arithmetic or evaluate other expressions. Students will probably write their more complex source code
in an editor and save it as a file. This will also enable them to run the same code on multiple
or
occasions, as well as enable them to share and publish their applications.
Note: Check your CHOICE Course screen for opportunities to interact with your classmates,
peers, and the larger CHOICE online community about the topics covered in this course or
e
other topics you are interested in. From the Course screen you can also access available
resources for a more continuous learning experience.
at
lic
up
D
ot
N
o
D
e
ut
Lesson Time: 1 hour, 30 minutes
ib
tr
is
Lesson Introduction
D
In any programming language, knowing how to work with data types is essential. Not all
data types are the same, and being able to recognize what you can and can't do with each
or
will help you make the most of your Python® code.
Lesson Objectives
e
at
TOPIC A
Process Integers and Strings
Both strings and integers are among the most common of simple data types. In this topic, you'll
learn how to leverage the power of both in your Python applications.
e
Data Types
ut
Data Types Data types refer to how particular variables are classified and stored in memory. Classifying
Students will learn about variables in different ways is useful because it enables programmers to set rules for what operations
ib
numbers and strings in can be performed on those variables. For example, a variable that is of type integer can be used in
this lesson. In the next arithmetic. A variable that is of type string can be used to display text to the screen. There are many
lesson, they will learn
tr
uses for the different data types.
about sequences,
dictionaries, and sets. The following are the five most common data types in Python:
is
• Numbers
• Strings
D
• Sequences
• Dictionaries
• Sets
or
Unlike in many other programming languages, in Python, you do not need to explicitly define data
types when you create variables. Python sets data types automatically based on the values you assign
to variables. Python will interpret a = 1 as an integer and a = "1" as a string.
e
Note: This is called dynamic typing, as opposed to the static typing of languages like C.
at
lic
Numbers
Numbers Numbers, as the name suggests, are variables with numeric values. When you explicitly define
up
number variables in your code, you simply type the number to the right of the equals sign. No other
symbol is required. The primary purpose of numbers is arithmetic. All of the arithmetic operators
you learned previously can be performed on number variables to evaluate expressions and produce
results.
D
Python categorizes numbers into additional subtypes. The most common are:
• Integers
ot
• Decimals
• Floats
N
Integers
o
Integers One of the most common number subtypes is an integer. Integers are either positive or negative
whole numbers that do not contain a decimal point. All of the following variables are integers:
D
a = 56
b = -72
c = 0
d = 5893849
e = 2
f = -1
With some data types, like numbers, there are times when you'll need to convert one type or subtype
to another—a process called type casting. For example, say you have defined a string literal
containing a series of digits and want to convert it to an integer so you can perform arithmetic on it.
To do this, you need to call Python's built-in int() function:
num_string = "635502"
new_num = num_string + 3 # This statement fails.
new_num = int(num_string) + 3 # This statement succeeds.
The int() function turns the string literal into an integer. Keep in mind that converting from one
e
data type to another requires the value you're converting to be in the proper format. The code
int("Hello") will not work, because alphabetical characters cannot be converted to integers.
ut
Strings
ib
A string is a data type that stores a sequence of characters in memory. A string value typically Strings
represents these characters and cannot be used as part of an arithmetic operation. Therefore, strings
tr
are distinct from numeric values like integers.
As you've seen before, string literals are variables with values enclosed in quotation marks. This is
is
the way that strings typically appear in source code. While a programmer may write a string literal a
= "Hello", the Python interpreter will convert a into a string object at runtime. This happens
D
behind the scenes, and for all intents and purposes, your use of strings will be confined to string
literals.
Even though strings often represent alphabetical text, they can also represent other symbols and
characters. For example:
a = "Count to 3." or
Even though 3 is a number, here it is part of the string because it is enclosed within the quotation
e
marks.
at
You can use the str() function to convert a value or variable into a string. For example:
num = 635502
print("The number is " + num) # Fails.
lic
The second print statement converts the number to a string before it is added to the string. Since
the + operator in the second print statement is operating on two strings, the operation can be
completed successfully. When you apply the + operator to two strings, they are concatenated. The
second print statement would produce the following message.
D
String Operators
Although strings are not subject to arithmetic operations, they do have their own special operators. String Operators
N
These operators can manipulate strings in a number of ways. Assume the following is true for the Slices and ranges will be
table: covered in greater depth
a = "Hello" with sequence data
o
e
in Returns True if the given character(s) exist in the "x" in a
ut
string. Returns False if they don't. False
not in Returns True if the given character(s) do not exist in "Hello" not in b
ib
the string. Returns False if they do. True
tr
Note: The in and not in operators are also called membership operators.
is
String Interpolation: The format() Function
D
String Interpolation: The One additional way to process strings uses placeholder characters ( {} ). These are placeholders for
format() Function variables or values that you define. The Python interpreter fills in the placeholders with their
or
corresponding values at runtime. This process is called string interpolation. String interpolation
can make formatting complex strings easier.
There are two main methods of string interpolation in Python. Both involve inserting a placeholder
e
within the string itself. For the first method, you'd type .format() at the end of the string literal
and then fill in the parentheses with whatever value or variable you want to inject into the string.
at
For example:
>>> count = 2
lic
Note: In these examples, the >>> symbols indicate the Python command being typed into the
interactive console. The output is indicated by a lack of preceding symbols.
Python uses format() to format the variable into a string, then passes this value into its placeholder
D
field (signified by curly braces). You can also use multiple placeholders to interpolate multiple
variables:
ot
>>> count = 2
>>> name = "Terry"
>>> people = "There are {} people named {}.".format(count, name)
N
>>> print(people)
There are 2 people named Terry.
If you don't put anything inside these placeholder fields, Python will replace variables from left to
o
right. Otherwise, you can manipulate the replacement values in several ways. For example:
D
e
>>> count = 2
>>> people = f"There are {count} people."
ut
>>> print(people)
There are 2 people.
ib
Notice how the variable count is referenced inside the placeholder, and the people string literal
begins with the letter f outside of the quotation marks.
The same can be done with multiple placeholders:
tr
>>> count = 2
is
>>> name = "Terry"
>>> people = f"There are {count} people named {name}."
>>> print(people)
D
There are 2 people named Terry.
The advantage of f-strings over format() is that f-strings are easier to read, since the variable
names are inline with the string literal.
or
Note: There are other ways of formatting strings in Python, but format() and f-strings are the
preferred ways for Python 3, with the latter being introduced in Python 3.6 (December 2016).
e
Numeral Systems
at
By default, programmers work with integers using the decimal numeral system, also called base 10. Numeral Systems
lic
A numeral system is simply a way of writing numbers using a set of digits, and base 10 means that
10 different digits are used (0 through 9). Base 10 is the most widely used numeral system, but it is
not the only one that is relevant to programmers. Python also supports binary, octal, and
up
You may have noticed that all of these operations result in strings. These strings show how the
integer is represented in the given numeral system. They also have leading characters that make it
easier to determine what numeral system they are in (e.g., 0x commonly prefixes a hexadecimal
value). You can use string formatting to remove these prefixes, if desired.
e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D
ACTIVITY 2-1
Processing Integers and Strings
Data File
e
/home/student/094027Data/Processing Simple Data Types/InventoryEntry/inventory_entry.py
ut
Scenario
Now that you've captured the backbone for your user-input process, you'll want to start formatting Activity: Processing
ib
that input. At some point, you'll allow the user to add multiple book titles in a single session, each Integers and Strings
one with a different quantity, and then give them the option of seeing the total quantity of all books
in the inventory. For now, you'll just ask the user for the number of book titles and assume each
tr
book title has the same quantity. Then, you'll calculate the total quantity based on what the user
inputs.
is
Launch PyCharm and open the InventoryEntry project.
D
1.
a) Launch PyCharm if you have not left it running from a previous session.
b) In the Welcome to PyCharm window, select Open.
b) Write the code shown to ask the user how many books they are entering. To avoid typing, you can
copy this code from the
L2.txt snippets file,
up
• Line 21 creates a variable named num_books_query and assigns it to the input that the user
N
3. Print the total quantity with string concatenation and interpolation. copy this code from the
L2.txt snippets file,
under the heading "Print
Total Quantity".
e
ut
• Line 24 creates a new response variable that contains a string literal concatenated with the
value in num_books_query, concatenated with another string literal.
ib
• The f at the beginning of the second string literal is formatting that string literal using the
{total_quant} placeholder value.
• Line 25 prints the response string, replacing the {total_quant} placeholder with its actual
tr
value, as calculated on line 23.
is
4. Why can you concatenate num_books_query, but must use interpolation for
total_quant?
D
A: The num_books_query variable is a string, and only strings can be concatenated. Since
total_quant is an integer, it must use interpolation so that it's formatted properly in the string.
5.
statement.
a)
or
Run the code to test your conversion operation, calculation, and print
f) Verify that your program converted the total book titles and quantity, calculated the total quantity,
and formatted your string properly.
up
D
ot
N
o
D
TOPIC B
Process Decimals, Floats, and Mixed Number
Types
Aside from integers, there are other number data types that you'll likely need to process in your
e
applications.
ut
Decimals
ib
Besides integers, another type of number that Python can work with is decimals. Decimals are any Decimals
non-whole numbers; that is, they contain a decimal point and a number following that decimal Make sure students
point. Decimals have a high degree of precision and can store numbers containing many digits. aren't confusing the
tr
Because of this, decimals are most suitable in contexts where accuracy is absolutely vital: financial, decimal type with the
accounting, and other fields that deal with monetary values, which are best represented with decimal numeral system.
is
decimals. An increase in precision means that decimals add processing overhead to a program.
The following is an example of creating a decimal in Python: Importing a module is
D
cost = decimal.Decimal("45.95") covered in the Certified
Associate in Python
In this case, cost holds the exact value of 45.95. Programming (PCAP™)
or
Note: Actually using decimals requires that you import the decimal module, which is beyond
the scope of this course.
course.
e
Floats
at
As a tradeoff between performance and precision, floating-point numbers or floats are used by Floats
programming languages like Python. Floats limit the precision of digits that trail the decimal point
lic
so less processing power is wasted in calculating numbers that don't really matter. For example, a
carpenter measuring a piece of lumber doesn't need to know how thick in inches the wood is to the
hundred thousandths decimal place (.00001). A float can help make this value less precise, but more
up
practical to use.
Floats can use what is similar to scientific notation to represent a number. The number 123.456
could be represented as 1.23456 x 102. The decimal point in this notation can "float" to a
D
different place, and its correct value can still be represented. For example, 1234.56 x 10-1 is the
same value as before, but the decimal point has floated to the right and the exponent has changed.
This is advantageous because it enables programs to process numbers that have varying scales. If
ot
you want to multiply a very large number by a very small number, a float will maintain the accuracy
of the result. For example, physicists may need to use astronomical values (e.g., the distance between
stars) in the same operation as atomic values (e.g., the distance between protons and electrons in an
N
atom).
Defining floats in Python is very similar to defining integers. Simply by assigning a variable to a Consider reminding
number with a decimal point, Python will define that variable as a float data type: students that floor
o
Also, like integers, you can perform arithmetic operations on floats. In fact, in Python 3, dividing (/) an integer, as opposed
any integers will result in a float, even if the remainder is zero: to true division (/),
>>> first_num = 6 which always returns a
>>> second_num = 2 float.
>>> first_num / second_num
3.0
Note: Floats and decimals are different data types, despite their similarities.
Caution: You should never use floats for monetary values in a production application, as these
e
values require the high precision of a decimal.
ut
Statements with Mixed Number Types
ib
Statements with Mixed Python enables you to perform arithmetic on different types of numbers in the same operation. For
Number Types example:
tr
The result of the >>> my_integer = 8
example is 12.0. >>> my_float = 4.0
is
>>> my_integer + my_float
See if you can guess the result of the operation before running it.
D
When it comes to mixing integers with floats, the result of the arithmetic operation will always be a
float. This helps preserve any fractional digits after the decimal point in a float. If you want to
operate on integers and floats, but keep the result an integer, you can use the int() conversion
or
function. Note that a simple conversion to an integer will always remove the decimal point and
values after that point. So, int(12.7) will become 12.
When it comes to deciding which number type to conform to in mixed operations, Python uses the
e
widest type. Floats are wider than integers, so in an operation with both, the integer must widen to
the float.
at
Note: Using the floor-division operator (//) on an expression with at least one float will return
a float. However, that float will always have a zero after the decimal point, e.g., 10 // 2.4
lic
returns 4.0.
up
decimal point may not be ideal. You'll want the float to look neater—for example, you might not
want a velocity value to display any more than two digits after the decimal point. So, you need a way
to control the precision of your floats when you place them in strings.
ot
>>> hours_elapsed = 5
>>> mph = miles / hours_elapsed
>>> print(f"The air-speed velocity is {mph:.2f} miles per hour.")
o
The :.2f reference within the braces is a placeholder that alters the mph float's default formatting. It
tells Python to truncate the float out to two decimal places. Using just {mph} would keep the float at
23.646, which is one more digit than what you want in this case.
Note: You can also use the format() function for float precision in the same basic way.
e
Note: For more information, see https://docs.python.org/2.7/library/
ut
string.html#format-specification-mini-language.
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D
ACTIVITY 2-2
Processing Mixed Number Types
e
PyCharm is running, the InventoryEntry project is open, and the inventory_entry.py script is
ut
open in the editor.
Scenario
ib
Activity: Processing Aside from getting the total quantity of books in the inventory, your users will also want to see
Mixed Number Types statistics like the average price of each book title. This means you'll need to work with both floats
and integers at the same time. You'll then exercise greater control over the precision of floats by
tr
formatting them in strings you'll print as output.
Consider having
is
students comment out
the first two input 1. Write code to calculate the total price of all book titles and the average price
D
statements so they can
go directly to the input per book title.
they're testing. a) Place your insertion point at the end of line 25 and press Enter twice to insert new lines.
To avoid typing, you can
copy this code from the
L2.txt snippets file,
under the heading
or
b) Write the code as shown to calculate total price and average price.
e
"Calculate Total Price
and Average Price".
at
lic
• Line 27 calculates the total_price by multiplying the total_ids (the total number of book
titles) by the price that the user inputs (book_price), which has been cast into a float. In the
up
finished version, each book will have a different price; for now, the price is the same for all
books.
• Line 28 calculates the average price (avg_price) by dividing total_price by total_ids.
• Line 29 prints the average price using f-string formatting.
D
e
ut
ib
tr
3. Why did avg_price turn into a float instead of an integer?
is
A: By default, the result of all regular division operations in Python 3 is always a float.
D
4. Assume you want to convert avg_price into a different currency by multiplying
it by 10. What would the result of this operation be and why?
5.
widens to a float.
6. Format your output string to change your float's precision to two decimal
places.
ot
a) On line 29, within the string-interpolation curly braces, after the last letter in avg_price, type :.2f
N
o
c) Verify that your print line formatted the float to two decimal places (12.95).
e
ut
ib
tr
7. Clean up the workspace.
is
a) Select Main Menu→Close Project.
b) Close the Welcome to PyCharm window.
D
If you plan to proceed
directly into the next
lesson, you may opt to
have students just leave
PyCharm running.
If students were using
the snippets file, you can
or
e
have them close it here.
at
lic
up
D
ot
N
o
D
Summary
In this lesson, you processed simple data types like strings and numbers. Performing operations on
these data types is essential to most programs.
Encourage students to
What kinds of values might you want to format for float precision in your apps? use the social
A: Answers will vary. Apps that process file size, file read/write speed, dimension measurements, and networking tools
e
distance measurements may benefit from float precision. provided on the CHOICE
Course screen to follow
ut
In what circumstances might you want to concatenate strings in your apps? up with their peers after
the course is completed
A: Answers will vary. Concatenation is useful for joining string variables together to form a larger string
for further discussion
variable. This can help cut down on verbose code, especially if those strings need to be constantly
ib
and resources to support
reused. Concatenation is also useful when printing output to the user, especially if the output doesn't continued learning.
require complex formatting.
tr
Note: Check your CHOICE Course screen for opportunities to interact with your classmates,
peers, and the larger CHOICE online community about the topics covered in this course or
is
other topics you are interested in. From the Course screen you can also access available
resources for a more continuous learning experience.
D
or
e
at
lic
up
D
ot
N
o
D
e
ut
Lesson Time: 1 hour, 30 minutes
ib
tr
is
Lesson Introduction
D
You've processed simple data types, but Python® also supports more complex data
structures. These data structures make almost any application, no matter how large and
or
complex, much more powerful and easy to write.
Lesson Objectives
e
at
TOPIC A
Process Ordered Data Structures
In Python, data structures are often divided into two categories: ordered and unordered. You'll
begin by processing ordered data structures, also called sequences.
e
Sequences
ut
Sequences In programming, a data structure is a collection of data values stored in an organized format. A
sequence variable is a type of data structure in which order matters. Because sequences are ordered,
ib
each element has its own index, or position, within the sequence. In Python, this index is numbered
and starts with 0, increasing by one for each successive element.
tr
There are three main sequence types in Python:
• Lists
is
• Ranges
• Tuples
D
Although they each involve an ordered collection of data, these sequence types store and process
data differently.
Mutability
Mutability or
In programming, objects (including data structures) can be said to be either mutable or immutable.
e
The values in mutable objects can be modified after that object has been defined. On the contrary,
at
the values in immutable objects cannot be modified after those objects have been defined.
Although the difference may seem unimportant in practice, it can actually have some bearing on
which data types you choose. Remember, a variable points to certain values in memory. When a
lic
mutable variable changes, it points to a different value in memory. Because you can't change the
value of an immutable variable that's already been defined, you must create another variable in
memory. Extrapolate this to programs that must constantly update many variables, and you'll see
up
that using immutable variables in this situation will cost significantly more processing overhead.
Likewise, there are situations where using immutable objects is a better idea. For example,
immutable objects can prevent conflicts in multi-threaded programs. If two or more threads run at
D
the same time, but have different values for the same object due to some change, then this can
corrupt the object. Even in single-threaded programs, having an immutable object is useful because
it makes it easier to ensure that there won't be unwanted changes to your object somewhere in your
ot
code.
Although all objects in Python are either mutable or immutable, this property is most often
associated with data structures.
N
• Dictionaries
D
• Sets
The following data structures are immutable:
• Ranges
• Tuples
Lists
A list in Python is a type of sequence that can hold different data types in one variable. Lists are Lists
mutable. Additionally, the values in a list do not need to be unique; they can repeat as many times as
necessary. These qualities makes lists ideal for storing records of varying types and values, while still
e
enabling you to update the lists when necessary.
ut
Note: Lists are similar to arrays in other programming languages.
ib
Let's say you want to work with a bunch of different year values in your program. You could define
each year as its own separate integer, like this:
tr
year1 = 1939
year2 = 1943
is
year3 = 1943
However, this can be very tedious and inefficient, especially with a large number of values. Lists are
D
a better way of storing such values.
Like other variables, lists in Python are defined by assigning them to a variable using an equals (=)
symbol. Python identifies a variable as a list when its value is enclosed in square brackets [] and
years:
years = [1939, 1943, 1943]
or
each element inside those brackets is separated by commas. The following code defines a list of
e
Notice that these are all integers. As stated above, you can mix any data type (even other lists) into a
single list. The following list includes strings and integers:
at
years_and_names list, index 0 is 1939. You can retrieve and process specific indices in a list by
appending square brackets to a variable and providing the index within those brackets. This is the
same as indexing a string. For example, the following code retrieves "John":
D
>>> years_and_names[3]
"John"
You may also use a slice to retrieve multiple indices:
ot
>>> years_and_names[0:3]
[1939, 1943, 1943]
N
A slice will give you all values between the indices you specify, the end position being exclusive. In
the previous example, the slice [0:3] will return indices 0, 1, and 2. Being able to retrieve indices in
a list is useful for when you need to process specific elements in that list.
o
Using indices, you can also update or overwrite elements in a list. The following code replaces the
value at index 3 ("John") with the string "Terry":
D
years_and_names[3] = "Terry"
Multidimensional Lists
Multidimensional Lists A discussion of NumPy
By default, lists have one dimension. In some languages, these are also called vectors to distinguish and other third-party
them from lists that have multiple dimensions. libraries is beyond the
scope of this course.
Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM
Lesson 3: Processing Data Structures | Topic A
64 | Certified Entry-Level Python Programmer (PCEP™)
Creating a multidimensional list is fairly intuitive, although it can be somewhat difficult to read. A
list with two dimensions is called a matrix, and is created by including lists inside of a larger list. For
example:
years_and_names = [[1939, "John"], [1943, "Eric"], [1943, "Michael"]]
Notice how there are outer brackets that define the main list, and three different inner lists within
that main list. Each inner list is separated by a comma, just like any other list element would be.
It might be easier to visualize this data as a table. After all, a table is essentially a two-dimensional
data structure.
e
1939 "John"
ut
1943 "Eric"
1943 "Michael"
There are three "rows" in this table and two "columns." Each inner list defines a row and the
ib
column values.
When you want to index or slice a multidimensional list, you need to consider its dimensionality.
tr
Observe what happens when you perform a simple index operation:
>>> years_and_names[0]
is
[1939, "John"]
The entire first inner list was returned because it occupies index 0 in the main list. If you want to
D
index or slice specific elements within an inner list, you need to add another set of brackets:
>>> years_and_names[0][1]
"John"
or
This returns the string that occupies index 1 inside the inner list that occupies index 0.
Matrices, cubes (three-dimensional lists), and higher-dimensional lists are most commonly used in
mathematical calculations like linear algebra. If you do end up needing to use multidimensional lists,
e
it's usually best to rely on a third-party Python library that provides this capability, like NumPy.
at
List Operations
lic
List Operations Like other data types, you can perform a number of operations on lists. The following table
provides examples of list operations using the lists ["A", "B", "C"] and ["D", "E", "F"].
up
["A", "B", "C"] + ["D", "E", ["A", "B", "C", "D", Concatenates lists.
"F"] "E", "F"]
D
["A", "B", "C"] * 3 ["A", "B", "C", "A", Repeats list values.
"B", "C", "A", "B",
ot
"C"]
doesn't.
"B" not in ["A", "B", "C"] False Returns True if value does
o
List Processing
List Processing (2 Other than finding indices and performing operations, you can manipulate lists in several other
Slides) ways. The following table assumes a list named my_list that is equal to [20, 10, 30, 10].
e
.remove() my_list.remove(10) [20, 30, 10] Removes first item
in the list that
ut
matches the value
you specify.
ib
.index() my_list.index(30) 2 Returns the first
index in a list that
tr
matches the value
you specify.
is
.count() my_list.count(10) 2 Returns the
number of times a
D
value you specify
appears in a list.
.sort() my_list.sort() [10, 10, 20, 30] Sorts items in a list
sorted() sorted(my_list)
or
[10, 30, 10, 20]
in increasing order,
updating the list.
Sorts items in a list
e
in increasing order,
creating a new list.
at
a list.
max() max(my_list) 30 Identifies the
o
highest value in a
list. Returns an
D
e
strings and
numbers.
ut
More on Sorting
ib
The differences between .sort() and sorted() may not be immediately apparent, so here is a
code block demonstrating how they return different results:
tr
>>> my_list
[20, 10, 30, 10]
is
>>> sorted(my_list)
[10, 10, 20, 30]
>>> my_list
D
[20, 10, 30, 10]
Using sorted(), the original my_list object did not change. A new list was created instead.
Compare this to using .sort():
>>> my_list
[20, 10, 30, 10]
>>> my_list.sort()
or
e
>>> my_list
[10, 10, 20, 30]
at
List Copying
List Copying (2 Slides) Observe the following block of code:
up
[1, 2, 3]
The second line assigns a new list to the original list. As expected, the new list has the same values as
the original. But look at what happens when you update list_2:
ot
>>> list_2.append(4)
>>> list_2
N
[1, 2, 3, 4]
>>> list_1
[1, 2, 3, 4]
o
Recall that when you assign variables to values, the variable is just a named reference to a value
stored somewhere in memory. When you assign a new variable to an existing variable, and that
existing variable is a mutable data type, the new variable just points to the existing values in memory.
It doesn't create a copy. In other words, list_1 and list_2 are linked.
You may not want this, however. Instead, let's say you want list_2 to be distinct from list_1.
There are a few ways you can do this, but the easiest is to just slice the entire original list, like so:
e
ut
Deep Copying
The prior example is called a shallow copy because, when working with nested lists, it only copies the
outer list. For example:
ib
>>> list_1 = [[1, 2], ["A", "B"]]
>>> list_2 = list_1[:]
tr
>>> list_2[0][1] = 3
>>> list_1
is
[[1, 3], ["A", "B"]]
Updating a value in the inner list of list_2 actually updated it in list_1 as well.
D
To create a distinct copy of both outer and inner elements of a list, you need to use a method called Importing a module is
a deep copy, also known as cloning. This involves using the deepcopy() function: covered in the Certified
>>> list_1 = [[1, 2], ["A", "B"]] Associate in Python
>>> list_2 = deepcopy(list_1)
>>> list_2[0][1] = 3
>>> list_1
or Programming (PCAP™)
course.
e
[[1, 2], ['A', 'B']]
at
Note: Actually using deepcopy() requires that you import the copy module, which is beyond
the scope of this course.
lic
Ranges
In Python, a range is an immutable sequence of integers, meaning its values cannot change. It is
up
Ranges
typically used as a way to loop or iterate through a process a number of times. This is much more Assure students that
efficient and provides you greater control than if you simply repeated the same code snippet over they will learn about
and over again. looping in the next
D
lesson.
The syntax of a range is range(start, stop, step). The start tells the range where in the list
If necessary, remind
to begin, and if left blank, will default to position 0. The stop tells the range where to end and must
students that indices
be specified. The step defaults to 1 and will process the very next value in the range of a list, unless
ot
start at 0.
you specify a different step.
Consider the following code:
N
the following integers: 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50. Now consider this code
snippet using the same my_range:
D
>>> my_range[3]
15
Like normal lists, you can find the index of a value in a range using square brackets. In this case,
index 3 will return 15.
Note: Printing an entire range won't format it like a list. For example, printing my_range will
return range(0, 50, 5). Nevertheless, the variable still holds all of the integers of the range.
Tuples
Tuples A tuple is very similar to a list, the main difference being that tuples are immutable. As stated
before, immutability has its benefits, and tuples may help you ensure that your data structure does
not change somewhere within your code. Tuples also process faster than lists, which can make a
difference in larger programs.
Tuple syntax uses parentheses () to enclose its values. For example:
my_tuple = (1939, 1943, 1943, "John", "Eric", "Michael")
e
As you can see, tuples, like lists, can hold different data types. This can include other tuples.
ut
As with other sequence types, you find an index in a tuple by using square brackets:
>>> my_tuple[0]
1939
ib
And using a slice:
>>> my_tuple[2:4]
tr
(1943, "John")
is
Tuple Operations
D
Tuple Operations The following table provides examples of tuple operations using the tuples ("A", "B", "C") and
The following operations ("D", "E", "F").
are essentially the same
as they are with lists. Expression
Concatenates tuples.
e
("A", "B", "C") * ("A", "B", "C", "A", "B", "C", Repeats tuple values.
at
does.
Tuple Processing
D
Tuple Processing Tuple processing is very similar to list processing. The main exceptions are that you cannot add,
update, or delete values from a tuple, as this is not possible with an immutable data type.
ot
The following table assumes a tuple named my_tuple that is equal to (20, 10, 30, 10).
specify.
D
e
tuple. Returns an error if the
tuple contains unsortable data,
ut
like another tuple or a mix of
strings and numbers.
ib
Note: You can convert lists to tuples using the tuple() function, and vice versa using
list(). This can be useful if you need to change the structure's mutability on the fly.
tr
is
Guidelines for Choosing Ordered Data Structures
Use the following guidelines to help you choose the appropriate ordered data structures in Python.
D
Guidelines for Choosing
Note: All Guidelines for this lesson are available as checklists from the Checklist tile on the Ordered Data Structures
CHOICE Course screen.
modified later.
• Choose ranges to create a simple sequence of numbers that shouldn't change.
• Choose tuples for collections of data that must follow a certain order and should not be
lic
modified later.
• Choose tuples if performance is a significant concern.
up
D
ot
N
o
D
ACTIVITY 3-1
Processing Ordered Data Structures
Data File
e
/home/student/094027Data/Processing Data Structures/InventoryEntry/inventory_entry.py
ut
Scenario
Activity: Processing You need to enable users to store multiple book titles rather than just one. You could store each
ib
Ordered Data Structures book title and its details as separate variables, but this would be highly inefficient and it would make
the code very difficult to maintain. You need each book's details to be in a certain order (i.e., ID
first, then name, then quantity, then price), and you need the results to be mutable so users can
tr
continually add to the structure. This calls for a list.
is
1. Launch PyCharm and open the InventoryEntry project.
D
a) Launch PyCharm if you have not left it running from a previous session.
b) In the Welcome to PyCharm window, select Open.
c) Beneath the 094027Data folder, expand Processing Data Structures, and select the InventoryEntry
project folder.
d) Select OK. or
e) Configure PyCharm to trust all projects in this folder.
f) In the Project pane, double-click inventory_entry.py to show the source code in the editor.
e
Lines of code associated with getting the total quantity and average price have been commented
at
out. The interpreter will ignore these lines now, but it will be easy to enable them again later by
removing the hash marks.
lic
List".
ot
• Line 21 creates a list (book_1) using square brackets ( [] ). Each of the items in the list
N
references an input variable defined earlier, with each item separated by a comma.
• Line 22 prints the list.
o
c) Verify that Python prints a list and that each item in the list is a separate string.
e
ut
ib
4. Use list indexing to print individual elements from the list.
tr
a) Rewrite the print statement on line 22 as shown.
is
D
•
•
or
The print statement now references each item in the list directly using indexing.
Indices in Python start at 0, so book_1[0] is referring to the first item in the list (the book ID).
e
• By indexing the list items, you are retrieving their values directly.
at
6. Repeat the input questions and start a new list for a new book title.
a) Highlight lines 4 through 22 and press Ctrl+C to copy the code on those lines.
D
b) Place your insertion point at the end of line 22 and press Enter twice to create new lines. Students may ask if
c) On line 24, press Ctrl+V to paste the code. there is a way to do this
more efficiently than just
repeating the code.
Assure them that they
will address this in the
upcoming lessons.
e
You are asking the same questions for a new book title, and so that book title's information will be
stored in a different list.
ut
7. Append the genre as a new list item.
ib
a) Place the insertion point at the end of line 42 and press Enter twice to add new lines.
b) Write the code as shown.
tr
is
D
or
e
• Line 44 adds a new question for user input, asking the user what genre the book(s) are in
(book_genre).
at
• Lines 45 and 46 use .append() to append the genre to each of the book lists.
• Lines 47 and 48 print each of the book lists as raw list data.
lic
c) When you're prompted for the book ID again, enter different information for the prompts that follow.
d) Verify that the second book's information was printed, just like the first.
D
ot
N
o
D
f) Verify that both book lists were returned, and that 'fiction' was added to the end of both lists.
e
ut
9. Why did the 'fiction' string get applied to both books, even though it was
ib
only asked once?
A: In the source code, on lines 45 and 46, the book_genre variable was appended to both book_1
tr
and book_2.
is
D
or
e
at
lic
up
D
ot
N
o
D
TOPIC B
Process Unordered Data Structures
In addition to sequences, Python also has a couple of unordered data-structure types. You'll process
dictionaries and sets in this topic.
e
Dictionaries
ut
Dictionaries A dictionary is an unordered, mutable data structure. This means that, unlike lists, each element in a
dictionary is not bound to a specific numbered index. What further separates dictionaries from other
ib
data types is that dictionaries have key–value pairs. The key acts as an index; calling that key returns
its associated value. This makes dictionaries ideal for when you need your program to look up
tr
information using other information it's associated with. For example, in a phone registry, you'd
map a person's name (the key) to their phone number (the value). As the name implies, you can also
think of a dictionary as containing a term matched with the definition of that term.
is
Note: In other languages, a dictionary may be called an associative array or a hash table.
D
Consider pointing out Dictionaries are defined by using curly braces ( {} ). Within the braces, a key is separated from its
that, in this case, each
person's first name is
unique to the dictionary
in which it is placed. But,
in a real-world scenario,
or
value by a colon ( : ), and any subsequent key–value pairs are separated by a comma. Observe the
following code, in which a dictionary is defined:
dict = {"John": 5551234, "Terry": 5554321, "Eric": 5551234}
e
In this dictionary, there are three keys and three associated values. Each key must be unique,
first name would not be
a good key to use
otherwise it cannot act as an index. However, the values for each key do not have to be unique
at
because first names are (John and Eric have the same number).
not globally unique. Because dictionaries are indexed by key, you can access each value in the dictionary. The syntax for
lic
Keep in mind that because values are not unique, you won't be able to do the reverse (look up a key
from a value).
Like in lists, you can put any data type you want in a dictionary value. You can even nest dictionaries
D
within a dictionary. However, the keys in a dictionary must be immutable. For example, a list cannot
be a key.
Note: A space is not required between key and value, but including spaces increases readability
ot
Dictionary Modification
o
Dictionary Modification You can add, update, and delete key–value pairs in a dictionary easily. Consider the previous
dictionary of names and phone numbers:
D
Note that this is essentially the same as adding a new entry, but Python detects that the key "Terry"
already exists, so it simply updates the dictionary. To delete John and his phone number from the
dictionary:
del dict["John"]
By simply calling the dictionary variable, you can see how it's changed. Remember that dictionaries
are unordered, so the result will likely not be in the order you defined the key–value pairs:
>>> dict
{'Eric': 5551234, 'Graham': 5556789, 'Terry': 5556789}
e
ut
Dictionary Processing
There are many more ways you can process dictionaries. Assume that the following table uses the Dictionary Processing
ib
updated dictionary of names and phone numbers.
tr
len() len(dict) 3 Returns the total number of key–
is
value pairs in the dictionary.
.items() dict.items() dict_items([("Eric", Returns each key–value pair in
D
5551234), ("Graham", the dictionary.
5556789), ("Terry",
5556789)])
.keys() dict.keys()
.values() dict.values()
dict_keys(["Eric",
"Graham", "Terry"])
dict_values([5551234,
orReturns the keys in a dictionary.
False if it is.
projects = tv | film
print(projects)
The output from this code would be {'Flying Circus': 1969, 'Live at Aspen': 1998,
o
Sets
Sets A set is an unordered, mutable data structure that cannot contain duplicate values. Unlike a
dictionary, it does not have key–value pairs; there is only one value per entry, similar to a list. Sets
can only contain immutable data types, like integers, floats, and strings. They cannot contain
mutable data types, like lists, dictionaries, and other sets. The reason for using a set over a list is that
processing large sets is considerably faster, which is useful when you need to continually update or
confirm values in the set.
For example, assume that you have a large database of files. Each file name in the database is
e
unique, and its order does not matter. You want to check whether or not a certain file still exists to
ut
make sure it hasn't been deleted. Looking up this particular file will take less time if all of the file
names are part of a set.
The syntax for defining a set uses curly braces, like a dictionary:
ib
my_set = {"Blue", "Yellow", "Arthur", "Robin", 24}
Since there is no key–value pair in a set, you'd only separate values by commas. This set contains
tr
string and integer data types and, as required, each entry is unique. If you attempt to define a set
with repeating values, only one of those values will be in the set when Python creates it.
is
You can also explicitly use set() when defining your variable. Within set(), you enclose the values
in square brackets, like you would in a list:
D
my_set = set(["Blue", "Yellow", "Arthur", "Robin", 24])
Set Processing
Set Processing
or
Set processing has much in common with list processing. However, the unique values in a set enable
you to do additional processing not possible in lists. For the following table, assume my_set is equal
e
to {"X", "Y", "Z"} and my_set2 is equal to {"X", "Y", "A"}.
at
specified value is in
the set, False if not.
Returns True if
up
e
2) unique values from
two sets into one set.
ut
Guidelines for Choosing Unordered Data Structures
ib
Use the following guidelines to help you choose the appropriate unordered data structures in
Python.
tr
Guidelines for Choosing
Choose Unordered Data Structures Unordered Data
is
Structures
When choosing unordered data structures:
D
• Choose dictionaries for collections of data that have a unique identifier with corresponding data
that describes one or more aspects of that identifier.
• Choose dictionaries when order does not matter, but later modification should be possible.
should be possible. or
• Choose sets for collections of unique data in which order does not matter, but later modification
ACTIVITY 3-2
Processing Unordered Data Structures
e
PyCharm is running, the InventoryEntry project is open, and the inventory_entry.py script is
ut
open in the editor.
Scenario
ib
Activity: Processing In addition to adding new book titles to the inventory, a user must be able to update existing entries
Unordered Data and delete entries. A list is fine for holding the book data, but having a separate list variable for each
Structures book is just not feasible. You need a data structure that not only can contain other data structures,
tr
but can also enable the user to easily look up and modify each instance of data (i.e., a book title)
based on some key piece of information. This is where dictionaries excel.
is
Luckily, the data you're working with already has a perfect key: the book ID. You'll use this as the
keys in the dictionary, whereas the dictionary values will be the rest of that book's data in the form
D
of a list. You'll then write some code to update, delete, and retrieve entries in the dictionary, just like
a user should be able to do in the finished program.
1. or
Rewrite some of the code to start creating a dictionary.
a) Highlight line 22 and press Delete.
e
You don't need to print the details here anymore.
b) On line 21, rename book_1 to book_1_details and remove book_id from the list.
at
lic
up
To avoid typing, you can c) On line 22, write the code as shown.
copy this code from the
D
Dictionary".
N
• The book_inv variable is a dictionary that will hold the book data, as indicated by the curly
o
braces ( {} ).
D
• The book_id is the first key, so it is placed to the left of the colon.
• The values for the key go after the colon. In this case, you are using the book_1_details list
as the values. You can nest data structures like this.
d) Highlight line 42 and press Delete.
e) On line 41, rename book_2 to book_2_details and remove book_id from the list.
e
To avoid typing, you can
ut
2. Write code to add a new key (book title) to the dictionary. copy this code from the
L3.txt snippets file,
a) Starting on line 42, write the code as shown.
under the heading "Add
ib
to and Print the
Dictionary".
tr
is
D
• By indexing a dictionary by a key, you can retrieve or update its values. Here, because the
or
second book's key (book_id) doesn't exist in the dictionary yet, it will be added to the dictionary.
• Along with the new key, book_2_details will be added as the values for that key, just like with
the first book.
e
• The print statement will output the entire dictionary.
b) Highlight lines 45 through 49 and press Delete.
at
In the product specifications, the first letter of the book ID indicates the genre, so this question isn't
necessary.
lic
c) When the questions repeat, enter any values you want for the second book title, as long as they're
different than the first book title.
d) Verify that the dictionary prints to the screen, that each book ID is a key, and that each key has the
D
e
ut
• Line 45 asks the user for the ID of the book title they want to delete.
• Line 46 uses del and indexes the specified key to delete that key and its values from the
dictionary.
ib
• Line 47 will print the updated dictionary.
b) Rerun the program.
tr
c) For the first book's ID, enter F123
d) Fill out the rest of both books' details as desired.
is
e) When you're asked for the book ID to delete, enter F123
f) Verify that the dictionary no longer contains the first book you entered.
D
or
e
at
lic
e
ut
ib
• Line 49 asks the user for the book ID whose details they want shown.
• Line 50 prints that same ID (show_id) back to the user.
• Line 51 prints the name of the book. It does this by indexing the book_inv dictionary using
tr
show_id as the key. Normally, this would retrieve the entire object associated with that key (in
this case, the details list for the book). Instead, it does a second index operation to retrieve just
is
item 0 from that list. In other words, you are performing nested indexing operations: one to
retrieve the list based on the key, and one to retrieve the first item from that list.
• If you're having trouble visualizing the indexing code due to the surrounding print formatting,
D
here it is by itself:
book_inv[show_id][0]
• Lines 52 and 53 do the same thing, only they are indexing the second (1) and third (2) items in
c)
d)
the list, respectively.
Rerun the program. or
As before, enter F123 as the first book ID, and fill out the rest of the details as desired.
e
e) Enter F124 as the second book ID, and fill out the rest of the details as desired.
f) When prompted to delete an ID, enter F123
at
PyCharm running.
ACTIVITY 3-3
Choosing an Appropriate Data Structure
Scenario
e
Activity Consider the following discussion questions to help review your understanding of Python's data
Use this activity as an structures.
ut
opportunity to evaluate
students' understanding
of the strengths, 1. You're creating a program to store various information about students. In
ib
weaknesses, and
applications of each data particular, you need to store their grades in each class. Once their grades are
structure. set, they should not be changed.
tr
Which data structure would you use to store the grades of each student, and
is
why?
A: Answers may vary, but a tuple is probably the best choice. Tuples are immutable, so they cannot
D
be changed elsewhere in the program. They can also hold a variety of data types, so even if the
grades are numbers, letters, or some mix of the two, it won't be a problem.
2.
or
You're creating a program that needs to store weather data for each city in
the country. Each city has a high temperature, humidity level, wind speed, etc.
Users will need to search for and update this data by city name.
e
Which data structure would you use to store each city's weather data, and
at
why?
A: Answers may vary, but a dictionary would be a good choice. The city name would be the keys,
lic
and the weather info for each city would be the values. That would enable a user to easily look up
a city to see its weather info. And, because dictionaries are mutable, that info can be easily
updated. The values in the key–value pairs could be stored in nested lists.
up
3. You're creating a program that reserves study rooms for students on a large
campus. There are 120 rooms, and your requirements say that each room
should be assigned a number from 1 to 120 so they can be identified. The
D
why?
A: Answers may vary, but the most efficient way to accomplish this is to use a range. Ranges easily
N
create sequences from a beginning integer to an ending integer, so you can just create room
numbers from 1 to 120. Also, ranges are immutable, so they won't be changed later.
o
D
e
A: Answers may vary, but in this situation, you'd be able to accomplish this fairly easily using two
ut
sets. Sets are unordered and must contain unique values, so each directory could have its own
set, where the file names for that directory are the values. And, you can use .intersection()
to find the duplicates across both sets.
ib
5. You're creating a program in which users can create tasks and view those
tasks in the order in which they were created. They should also be able to
tr
update those tasks and remove them when they're done.
is
Which data structure would you use to store each task, and why?
A: Answers may vary, but a list is a good candidate. Lists are ordered, so the tasks could be created
D
and retrieved in the desired order. They are also mutable, so the user can change or remove
tasks as needed.
or
e
at
lic
up
D
ot
N
o
D
Summary
In this lesson, you processed both ordered and unordered data types. Being able to manipulate these
data types will help you implement more complex and useful features into your applications.
Encourage students to
use the social Which sequence type do you think you'll use more often, lists or tuples? Why?
networking tools A: Answers will vary. Lists are much more common, as they're easy to manipulate. Still, some students
e
provided on the CHOICE might prefer to use tuples in certain circumstances, especially when they want to ensure that the
Course screen to follow sequence will stay the same no matter what.
ut
up with their peers after
the course is completed How might you use dictionaries in your own apps?
for further discussion
A: Answers will vary. Dictionaries are great for creating associations between things and aspects of those
ib
and resources to support
continued learning. things, particularly when each thing is unique. For example, students might use a dictionary to
associate each option a user configures in an interface with how they chose to configure that option.
tr
The option is the key, and the way they configure the option is the value.
Note: Check your CHOICE Course screen for opportunities to interact with your classmates,
is
peers, and the larger CHOICE online community about the topics covered in this course or
other topics you are interested in. From the Course screen you can also access available
D
resources for a more continuous learning experience.
or
e
at
lic
up
D
ot
N
o
D
e
ut
Lesson Time: 2 hours
ib
tr
is
Lesson Introduction
D
Other than storing data, programming languages like Python® execute logical processes in
order to determine what to do in a program. Conditional statements and loops are the
or
primary ways that you can control the logical flow of a program, and they are found in
nearly all Python-developed software. In this lesson, you'll take advantage of both to
produce a more complex application.
e
Lesson Objectives
at
TOPIC A
Write Conditional Statements
In this topic, you'll leverage Python's ability to create objects that decide what to do based on certain
conditions.
e
Conditional Statements
ut
Conditional Statements A conditional statement is an object that tells the program it must make a decision based on
various factors. If the program evaluates these factors as true, it executes the block of code
ib
contained in the conditional statement. When that block of code has run, execution continues with
the code following the conditional statement. If false, the program skips the block of conditional
tr
code and jumps directly to the code following the conditional statement.
Conditional statements are fundamental to most programs, as they help you control the flow of
is
executed code. For example, if a user enters some input, you might want to process that input
differently based on a number of factors. The user might press one navigation button in a web app
and not another. Rather than sending them to both web pages, you'd only send the user to
D
whichever they chose.
True
Conditional statement
lic
Conditional code
up
D
Subsequent code
ot
N
The if Statement
o
note the colon ( : )—this is required after the condition of an if statement and before the actual
statement to be executed. Now consider the syntax with real values:
a = 2
b = 3
c = 5
if a + b == c:
print("Successful!")
e
Once the program evaluates this expression and determines it is true, Successful! is printed to the
command line.
ut
Note: Conditions can use many different types of operators and are not just limited to simple
arithmetic.
ib
Now consider what would happen if the condition evaluates to false: If students ask why this
expression uses the
tr
if a + c == b: double equals sign (==)
print("Successful!") rather than single,
is
In fact, nothing happens. Python doesn't produce an error, as nothing about this code causes ensure them that they
problems in execution. Python simply skips over the indented statement because the condition for it will learn the difference
shortly.
executing wasn't met.
D
The if…else Statement
or
What if you want the false value of a conditional statement to execute some code, rather than just
moving on? For that, you can modify the typical if statement by making it an if...else
statement:
The if...else
Statement
e
if a + c == b:
at
print("Success!")
else:
print("Failure!")
lic
If Python does not evaluate the condition to true, it will execute everything in the else branch of
the statement. This is useful when there are multiple conditions you need to evaluate, but only one
requires a unique action, and the rest can simply be treated the same way.
up
What if there are multiple conditions and you want to treat each differently? In this case, you can The elif Statement
essentially combine if and else into the elif branch. For example:
if a == b:
ot
print("A is B")
elif a == c:
print("A is C")
N
elif b == c:
print("B is C")
else:
o
print("Failure!")
D
After it evaluates the first if, Python will go down each successive elif and determine its truth
value. Python will stop once it finds a true condition and executes its code. As before, you can end
the if and elif branches with else to capture every other condition that you didn't explicitly call
out.
Nested if Statements
Nested if Statements You can also nest if statements within each other to have Python evaluate multiple layers of
conditions. For example:
if a + b == c:
if b + c == a:
print("Success!")
else:
print("Failure!")
e
else:
ut
print("Failure!")
In this conditional statement, Python must evaluate a + b == c before it can even start evaluating
b + c == a. There are several possible outcomes or "paths" involved in this statement.
ib
Booleans
tr
Booleans A Boolean is a data type that holds either true or false values. In Python, these values are actually
is
the keywords True and False.
Conditional statements evaluate conditions as either True or False. You can verify this by
D
executing the condition by itself:
>>> a + b == c
True
>>> a + c == b
False
or
Objects in Python also have a default truth value. For the most part, if an initialized variable is non-
e
empty, it always evaluates to True. Empty strings, sequences, etc., always evaluate to False. This
means you can check if a variable is empty or not:
at
if my_str:
print("Variable is not empty.")
Notice how the condition is just my_str, with no other qualifications. This will prompt Python to
up
evaluate its default truth value, which, in this case, is True. In other words, the message will print.
Note: Behind the scenes, True and False are essentially just the integers 1 and 0, respectively.
D
Comparison Operators
ot
Comparison Operators Comparison operators test the relation between two values and return a Boolean as a result. These
are most commonly used in conditional statements. There are several different ways to compare
N
e
ut
Note: This is not an exhaustive list of comparison operators. For more information, navigate to
http://www.tutorialspoint.com/python/python_basic_operators.htm.
ib
Logical Operators
tr
Another common operator in conditional statements is the logical operator. Logical operators Logical Operators
connect multiple values together so they can be evaluated as True or False. There are several
is
different ways to connect multiple values in Python, which are described in the following table.
D
Operator Definition Example/Result
or
True.
or True
False
Bitwise Operators
lic
Bitwise operators work with binary numbers. They are most useful when manipulating individual Bitwise Operators
bit values for low-level data operations. There are several different ways to work with binary values, If necessary, remind
up
& Sets each bit to 1 if both bits are 1. Also called a 5 & 3
bitwise AND. 1
| 5 | 3
Also called a bitwise OR. 7
<< Shifts the left operand left by the number of bits 5 << 3
specified in the right operand. Also called a 40
bitwise left shift.
>> Shifts the left operand right by the number of bits 5 >> 3
specified in the right operand. Also called a 0
bitwise right shift.
Note: Like working with binary numbers, using bitwise operators is fairly specialized and,
therefore, less common than the other operators mentioned.
Binary Example
It can be difficult to understand the results of a bitwise operation without knowing how the
numbers are represented in binary. Consider you have two decimal numbers, 5 and 3. When cast to
binary, they are:
e
>>> bin(5)
"0b101"
ut
>>> bin(3)
"0b11"
Removing the 0b prefix, the integer 5 is 101 in binary, and the integer 3 is 11 in binary. When
ib
performing a bitwise operation, each binary digit (bit) from each number is compared. But, since the
second number is one digit narrower than the first, it must be padded with a zero at the beginning.
tr
So, the numbers in binary are:
101
is
011
Now, the digits in each "column" can be compared. Let's say you want to perform 5 & 3. The first
D
column has a 1 and a 0. These are not both 1, so they become a 0. The second column also has a
mix of digits, so it is likewise a 0. The third column has a 1 for both numbers, so it becomes a 1.
The result, in binary, is:
001
Which, when converted to decimal, is 1:
>>> int("0b001", 2)
or
e
1
at
Note: The 2 is telling the int() function to treat the input as a base-2 number (i.e., binary).
lic
Assignment Operators
up
Assignment Operators Assignment operators, as the name implies, assign values to variables. You're already familiar with
the main assignment operator, which is just the single equals sign ( = ). However, Python also gives
you the ability to perform an operation (usually arithmetic) and assign the result of that operation to
a variable, all in one compact line. They are also called shortcut operators because they reduce the
D
assignment operator.
+= x += 5 x = x + 5
-= x -= 5 x = x - 5
o
*= x *= 5 x = x * 5
D
/= x /= 5 x = x / 5
//= x //= 5 x = x // 5
%= x %= 5 x = x % 5
**= x **= 5 x = x ** 5
Note: Each of the bitwise operators also has an assignment operator, except for the bitwise
NOT.
Order of Operations
When you include all of the operators mentioned in this course, this is the order of operations: Order of Operations
e
**
ut
+x –x ~x
* / // %
ib
+ -
<< >>
tr
&
is
^
|
D
in not in == != > < >= <=
not
and
or
or
e
at
Note: Like with arithmetic, you can control the order of other operations by wrapping them in
lic
parentheses.
Use the following guidelines to help you write conditional statements in your Python programs.
Guidelines for Writing
D
Note: All Guidelines for this lesson are available as checklists from the Checklist tile on the Conditional Statements
CHOICE Course screen.
ot
• Place a colon ( : ) at the end of the condition in an if and elif statement, as well as right after
an else statement.
D
• On the line below the condition or else statement, indent the code you want the statement to
execute.
• Make use of comparison operators like == and < in conditional statements to test how values and
variables relate to one another.
• Make use of logical operators like or, and, and not to determine how values are connected
together in a condition.
• Keep the order of operations in mind when writing conditions for an if statement.
• For more complex processing, nest if statements within each other.
e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D
ACTIVITY 4-1
Writing Conditional Statements
Data File
e
/home/student/094027Data/Writing Conditional Statements and Loops/InventoryEntry/
ut
inventory_entry.py
Scenario
ib
Your program won't function very well unless it can make decisions based on a number of factors— Activity: Writing
especially user input. To account for these decisions, you'll need to write conditional if statements Conditional Statements
to anticipate the various ways your program can execute.
tr
You'll start by considering the six main tasks the user can select:
is
1. Add a new book title.
2. Update an existing book title.
3. Delete an existing book title.
D
4. Show info for all books in the inventory.
5. Summarize info for all books in the inventory.
6. Exit the program.
or
Then, you'll write the code so that only the task the user selected is executed.
e
1. Launch PyCharm and open the InventoryEntry project.
at
a) Launch PyCharm if you have not left it running from a previous session.
b) In the Welcome to PyCharm window, select Open.
lic
c) Beneath the 094027Data folder, expand Writing Conditional Statements and Loops, and select the
InventoryEntry project folder.
d) Select OK.
e) Configure PyCharm to trust all projects in this folder.
up
f) In the Project pane, double-click inventory_entry.py to show the source code in the editor.
The code has been refactored and cleaned up to prepare it for this activity. Refactored code has had
its structure changed without its behavior changing. Also, several of the print statements were
D
removed to keep the source code and the output from being too cluttered with unnecessary
messaging.
2.
a) Examine lines 4 through 7.
N
o
D
• Line 4 prints a welcome message. The \n code indicates a line break and will be used
throughout the code to make the output look neater.
• Line 7 defines the book_inv dictionary. The first book title is being hardcoded into the dictionary
for now so that each of the tasks will work. Later, when you learn how to keep a program
running, you'll remove this hardcoding.
e
ut
ib
tr
is
• Lines 9 and 19 print hyphens to frame the selection menu, drawing the user's eye.
D
• Lines 11 through 17 print the menu to the user. On line 17, sep="\n\t" is telling the print()
function to separate each print field by a new line and a tab character (\t). Line 11 also includes
a tab character at the beginning so that it is properly aligned.
or
• Line 21 asks the user for their choice. The .lower() at the end will convert the result to
lowercase. The user will be able to specify either the number of the task they want, or the main
word that identifies that task (e.g., "ADD"). Remember, programming languages like Python are
case sensitive, so converting the input to lowercase avoids having to test for all possible case
e
variations.
c) Examine the rest of the code.
at
• Most of this should look familiar. The biggest difference is that it's been organized under
comments that indicate which task the user has selected. This is where you'll write your first
conditional statements.
lic
• The code under # SUMMARIZE is still commented out. You'll handle this later.
• There's also an # EXIT comment that you'll need to write new code for.
up
3. Create a conditional statement that handles a user adding a book title to the
inventory.
a) From the bottom-right corner of the PyCharm window, select 6 spaces*.
D
ot
N
o
b) From the pop-up menu, select Disable Indents Detection for Project.
D
PyCharm automatically detected the six-space indents on lines 12 through 17 and used that as the
default indentation length. However, four spaces is typically preferred when indentation is required
(e.g., in if statements, which you're about to write).
c) If necessary, close the pop-up message saying that indents detection was disabled.
d) Place the insertion point on line 24.
e
ut
• Line 24 defines the two conditions that must be met for the code indented below it to execute. To avoid typing, you can
• The first condition states that task_choice must be equal in value to the string "1". The copy this code from the
L4.txt snippets file,
ib
second condition states that task_choice must be equal in value to the string "add".
under the heading
• The conditions are connected by the logical operator or. This means that either of the two
"Conditional Statement
conditions must be True for the code to execute. In other words, a user can enter 1 or they can
for ADD".
tr
enter add for this code to run.
• When you finish typing line 24 and then press Enter, PyCharm automatically indents the next line
is
under it.
• Line 25 defines a print statement that will execute if the overall condition above it is met.
f) Highlight lines 26 through 33.
D
or
e
at
lic
up
Now, all of the code to add a book to the inventory will only run if the condition is met.
4. Create another conditional statement that handles a user updating a book title
in the inventory.
a) Place the insertion point on line 36.
To avoid typing, you can b) Type the two lines as shown.
copy this code from the
L4.txt snippets file,
under the heading
"Conditional Statement
for UPDATE".
e
ut
ib
• The elif statement will evaluate anything that does not meet the conditions of the first if
tr
branch.
• The condition in the elif branch follows a similar pattern as before: if the user enters 2 or
is
update, then the code under this branch will run.
c) Highlight lines 38 through 45, then press Tab to indent them under this elif branch.
For now, this code is the same as what's under the first if branch, but you'll modify it in a later
D
activity.
To avoid typing, you can
copy this code from the 5. Create several more conditional statements based on the user's task
L4.txt snippets file,
under the headings
"Conditional Statement
for DELETE/SHOW/
selection.
or
a) Repeat the same process for # DELETE, # SHOW, # SUMMARIZE, and # EXIT.
The elif branches should be as follows, respectively:
e
SUMMARIZE/EXIT".
# DELETE
Check in with students
at
# SHOW
elif task_choice == "4" or task_choice == "show":
print("Selection: SHOW\n")
up
# SUMMARIZE
elif task_choice == "5" or task_choice == "summarize":
print("Selection: SUMMARIZE\n")
D
# EXIT
elif task_choice == "6" or task_choice == "exit":
ot
print("Selection: EXIT\n")
Caution: Don't forget to indent each block of code under its associated elif
N
branch, except for # EXIT, which doesn't yet have any code.
Each successive elif branch will evaluate any selection that did not meet any of the conditions that
o
a) Place your insertion point at the end of line 78 (the line that prints the exit selection).
e
b) Press Enter twice.
ut
c) On line 80, press Backspace to unindent the insertion point.
d) Write the code as shown. To avoid typing, you can
copy this code from the
ib
L4.txt snippets file,
under the headings
"Conditional Statement
tr
for Invalid Selection".
is
D
•
•
prior conditions were met. or
The else branch indicates the last condition to check for in a chain of if statements, if no other
If the user enters something that doesn't match any of the prior options, they will be instructed to
try again. This ensures your program is resilient against unexpected user input.
e
7. Test the various conditions in the program.
at
Note: As you use the program, you may need to scroll up in the Run pane or
make the pane taller to see the relevant output.
c) Enter 1 or add
d) Verify that the output indicates you are in the "ADD" task and are prompted to enter book details.
e) Enter the book details any way you want, as long as they're different than book F123 ("The Open
Boat").
f) Verify that the dictionary returns the hardcoded listing for "The Open Boat" book, as well as the info
for the book you just entered.
The program terminates at this point. As mentioned, you'll implement code to keep a program alive
in an upcoming activity.
g) Rerun the program.
h) At the selection prompt, enter update
e
i) For the book ID, enter F123
ut
j) Fill out the rest of the details however you like.
k) Verify that the hardcoded info for book ID F123 ("The Open Boat") was changed in the dictionary.
The book with ID F123 l) Keep rerunning the program and trying the rest of the selections, including invalid selections.
ib
was hardcoded into the
program so that students Caution: Because the program logic still has gaps in it, you may trigger an
could use it to test the error depending on what you input. If that happens, just rerun the program.
tr
update, delete, and
show tasks.
Write conditional statements to validate the book ID input.
is
8.
a) When you're done testing the program, return to the code editor.
b) Place the insertion point at the end of line 26 and press Enter.
D
To avoid typing, you can c) Starting on a new line 27, write the code as shown.
copy this code from the
L4.txt snippets file,
under the headings
"Nested Conditional
Statements".
or
e
at
lic
up
• These are two if statements nested inside of the larger if statement. In other words, they will
D
only evaluate their conditions if the user has selected option #1 (add).
• Line 27 checks if the length of the book ID the user entered is not equal to 4. If it's not, the code
under the conditional executes. If it is, the interpreter moves to the next statement that is not
ot
• The purpose of this code is to ensure the user's input is conforming to the book ID specifications,
and to ensure that the user isn't adding a book that already exists in the inventory.
D
Note: Consider typing out ADD in varying cases if you haven't already to test
the program's ability to handle differences in case.
b) For the book ID, enter 123
Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM
Lesson 4: Writing Conditional Statements and Loops | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 99
Note: At the moment, the program continues. You will write code later to force
the user to re-enter the book ID.
d) Rerun the program and select the "ADD" option.
e) For the book ID, enter F123
f) Verify that you are told the book ID is already in the inventory.
e
ut
g) Either manually stop the program or fill out the rest of the book details to end it naturally.
h) Close the Run pane.
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D
TOPIC B
Write Loops
Now that you've written conditional statements, you can move on to loops, another way to control
the flow of logic in a program.
e
Loops
ut
Loops Another useful way to control logic in a program's code is by implementing loops. A loop is any
statement that executes code repeatedly. The loop repeats until a certain exit condition is met. Code
ib
within the loop runs each time the loop repeats. When the necessary exit condition is met, the loop
is finished, and the flow of execution resumes with the code that follows outside the loop.
tr
Loop
is
D
Repetitive code within the
loop, typically operating on
"next" item each pass
through
Exit
condition
or
e
End loop not met
at
Exit
condition is
met
lic
In Python, there are two main kinds of loops: while and for loops.
D
The while Loop A while loop executes code repeatedly until some specified condition is False. For example,
consider a typical desktop program. You want the window of the app to stay active until the user
N
voluntarily selects the close button. So, you'd wrap the relevant code in a loop, with the condition
being that the user hasn't selected the close button. Once the program stops meeting this condition
(i.e., the user selects close), the program can terminate.
o
while condition:
statement
Notice that the syntax is very similar to an if statement. Also, like in an if statement, the condition
in a while loop can contain an expression using various operators. For example:
count = 1
while count <= 5:
print(count)
count += 1
Count starts at 1, and while it is less than or equal to 5, two things happen:
• The count is printed to the console.
• The count is incremented by one using an assignment operator.
So, the first time the loop executes, count starts as 1 and becomes 2. Then, the very same print and
variable-assignment code loops again, with count starting at 2 and becoming 3. This process repeats
until count is equal to 6, and then Python skips the code in the while loop (because count is no
e
longer less than or equal to 5). The output of this code is as follows:
ut
1
2
3
ib
4
5
tr
If the condition for the while loop to run is never met, Python will never execute the code inside of
the loop. Conversely, if the condition to exit the loop is never met, the code inside the while loop
is
will run an indefinite number of times.
D
A for loop iterates through an object a certain number of times, depending on what you specify. The for Loop
or
Unlike a while loop, a for loop does not depend upon a condition being evaluated to False for it
to stop or never begin in the first place. So, for loops are meant to always execute code a given
number of times. This makes them ideal for processing iterable objects like lists, ranges, and other
data structures.
e
The syntax for a for loop is:
at
for i in my_list:
print(i)
First, you define a simple list. Next, in the for loop, you assign i as the current item, also known as
the iterator. The letter i is often used arbitrarily as the iterator, but you can choose a more
D
descriptive identifier if you prefer. The in my_list tells Python to loop through the list you
created. Within the loop is the print statement that outputs the iterator value. Essentially, the for
loop assigns the first value in the list (1) to i, prints i, then loops and assigns 2 to i, prints i, and so
ot
2
3
Four
o
Five
When it comes to iterating through data structures, for loops are the preferred method in Python;
D
while loops are less common and are typically reserved for user input.
Note: Like if statements, both loop types can be nested for greater complexity.
e
print("Done counting.")
In a for loop, the else branch will execute once the loop is finished iterating:
ut
my_list = [1, 2, 3, "Four", "Five"]
for i in my_list:
ib
print(i)
else:
print("We've reached the end of the list.")
tr
Range Loops
is
Range Loops Since loops can be used with many different types of objects, it helps to see those examples in
D
action. For example, let's say you want to perform a task a specific number of times, not just the
number of items in a list. You can use a for loop with a range to do this:
for i in range(1, 4):
print(f"This is loop number {i}.")
or
The iterator value will be assigned to each successive number in the range, from 1 to 3. The output
is:
e
This is loop number 1.
at
Dictionary Loops
Dictionary Loops Another common application of a for loop is to enumerate keys and/or values in a dictionary. To
up
Remind students that iterate through the keys only, use the .keys() approach:
the iterator name is dict = {'Eric': 5551234, 'Graham': 5556789, 'Terry': 5556789}
arbitrary. for k in dict.keys():
D
print(k)
The output is:
Eric
ot
Graham
Terry
N
5551234
5556789
5556789
And, finally, to iterate through both keys and values, use two iterators separated by a comma and
then the .items() approach:
for k, v in dict.items():
print(k, v)
The output is:
Eric 5551234
Graham 5556789
Terry 5556789
Nested Loops
e
ut
You can also nest loops just like you can nest conditional statements. You can also nest loops inside Nested Loops
of conditional statements and vice versa. For example:
for k, v in dict.items():
ib
if "555" in str(v):
print(f"{k}'s number is probably fake.")
tr
The first line uses the same for loop statement as the prior example. The second line starts a
conditional statement inside this loop. If the string "555" appears anywhere within the current
is
loop's dictionary value, then execute the code under the conditional statement. This code prints the
key (the person's name) and says their phone number is probably fake. Then, the loop starts over
with a new key (person) and a new value (their phone number), and goes through the same
D
conditional statement. The process repeats until there are no more key–value pairs in the dictionary.
Note: The value iterator (v) had to be cast to a string in the if statement because the in
operator doesn't work with integers.
Loop Control
Within loops, there are statements that give you greater control over how the code is executed. The Loop Control
up
break
print(i)
N
In this example, Python iterates through each entry in my_list. If it comes to a value that is not an
integer, it breaks out of the loop. The resulting output is:
1
o
2
3
D
4
The continue statement will stop Python from executing the code in that particular iteration, while
allowing the rest of the iterations to proceed. For example:
for i in my_list:
if i % 1 != 0:
continue
print(i)
Instead of terminating the entire loop, Python will simply ignore the iteration in which 5.2 appears.
The output is therefore:
1
2
3
4
e
6
Lastly, the pass statement essentially tells Python to do nothing. It is typically used as a placeholder
ut
before writing actual statements.
for i in my_list:
ib
pass
tr
List Comprehension: Syntax
is
List Comprehension: A list comprehension is a technique for creating a list using a loop and a condition within a single
Syntax statement. The power of a list comprehension is that you can succinctly automate list creation
without having to write multiple lines of code.
D
The basic syntax of a list comprehension is as follows:
[statement for item in iterable if condition]
• statement is the operation you want to perform on each item from an iterable object.
e
• item is the same as it is in a for loop: a variable that represents the individual value of the
iterable object in the current loop.
at
All of this is wrapped in opening and closing brackets ( [] ) so that the end result is a list.
List Comprehension: Let's say you have a list of numbers and want to create a new list that only incorporates integers
Example from the initial list. And, you want to double all of those valid integers. You could do this in a multi-
D
line for loop, but here's how you can make that code more compact:
old_list = [1, 2, 3, 4, 5.2, 6]
new_list = [i * 2 for i in old_list if i % 1 == 0]
ot
2. for i in old_list is identifying what iterable object to grab the items from. In this case, the
old_list variable.
3. if i % 1 == 0 is testing each item to see if it has a remainder of 0 when divided by 1.
o
Like a normal loop, this process happens for each item in the iterable object. The result is a new list
D
populated by the items that match the condition and have had the multiplication applied to them.
The output of new_list is:
[2, 4, 6, 8, 12]
Note: Although list comprehensions can be a nice shortcut, overly complex list comprehensions
can actually be harder to read than traditional loops. Be judicious in how you use them.
e
• Use for loops to iterate through objects like lists, ranges, dictionaries, and other data structures.
ut
• Use for loops to define exactly how many times to iterate through these objects.
• Place a colon ( : ) at the end of the loop, and indent code to be executed in that loop.
• Nest loops and conditional statements within each other to achieve more complexity in
ib
processing data.
• Use an else branch in a while loop to tell Python what to do when the condition becomes
tr
False.
• Use an else branch in a for loop to tell Python what to do once the loop completes.
is
• Use the break statement if you need to terminate a loop based on some condition.
• Use a continue statement if you need to stop a particular iteration in a loop.
D
• Use the pass statement as a placeholder for code in a loop you plan to write later.
• Use list comprehensions to automate the creation of lists in compact, single-line expressions.
• Prefer traditional for loops if list comprehensions become too complex and hard to read.
or
e
at
lic
up
D
ot
N
o
D
ACTIVITY 4-2
Writing while Loops
Scenario
e
Activity: Writing while As your program stands now, if a user makes a selection and enters the necessary data for that
Loops selection, the program will just stop entirely. Also, if the user enters an incorrectly formatted book
ut
If students were unable ID, or a book ID that already exists, the program will simply carry on. Neither of these behaviors is
to complete the prior ideal—the former because users need to be able to perform multiple tasks as many times as
activity, they can catch necessary, and the latter because the program needs to gracefully react to user mistakes.
ib
up by opening
inventory_entry_tpc_a_d So, you'll construct while loops to keep your programming running until the user manually exits.
one.py from the project And, you'll construct while loops to stop certain input prompts if the user provides invalid input.
tr
folder.
is
1. Write a while loop to keep the whole program running.
a) Place the insertion point on line 8 and press Enter to start a new line.
D
b) On a new line 9, type while True:
or
e
at
lic
up
D
Writing while True is essentially telling Python to execute the following indented code as long as
ot
True is True. Since this is always the case, the code will run indefinitely until it encounters a break
statement.
N
c) Highlight all of the code under the while loop—from lines 10 through 86—and press Tab.
You want all of this code to run indefinitely, so indenting it places it under the control of the loop.
o
D
d) Verify that the rest of the code is positioned within the while loop.
e
ut
ib
tr
is
D
or
e
at
2. Write a while loop to keep the "ADD" task running until the book ID is valid.
lic
a) Place the insertion point at the end of line 26 and press Enter twice.
b) On a new line 28, type while True:
c) Indent lines 29 through 40 so that they appear under this new while loop.
up
D
ot
N
o
D
You want the data-entry questions for adding a new book title to repeat until the entered data is
satisfactory. You'll need to define what will trigger the loop to stop or restart.
e
ut
ib
If the book ID is not exactly 4 characters, the most immediate while loop will restart the code
underneath it. In this case, the loop will keep asking the user for the book ID until it gets what it's
tr
looking for. This is what the continue statement does.
c) Place the insertion point at the end of line 34 and press Enter.
is
d) On a new line 35, type break
D
or
e
at
• If the book ID already exists in the inventory, the interpreter will break out of the most immediate
lic
execute and must therefore restart the outer while loop—the one that keeps the program
running. In other words, the menu will appear to the user again.
• The reason why the program is using a break here and not just a continue that asks for
another book ID is because the user may be trying to update an existing book title, and therefore
D
is sent back to the menu where they have the option of selecting that task.
e) Place the insertion point at the end of line 42, then press Enter twice.
f) On a new line 44, type break
ot
N
o
D
This break statement does the same thing, but this time it'll send the user back to the menu after
they've filled in all the details.
e
ut
ib
tr
is
D
or
e
e) Select the "ADD" task again.
at
ACTIVITY 4-3
Writing for Loops
e
PyCharm is running, the InventoryEntry project is open, and the inventory_entry.py script is
ut
open in the editor.
Scenario
ib
Activity: Writing for Now you're ready to write two important features into your program: the ability to show all books in
Loops the inventory in one report, and the ability to statistically summarize the books in the inventory. The
for loop is an easy and efficient way to iterate through structures like lists and dictionaries, so you'll
tr
be using these loops to achieve both goals without having to write a lot of code.
Your first for loop will iterate through all entries in the inventory dictionary and pull out quantity
is
and sales-price values for each book title, performing various statistical calculations on them. Your
second for loop will iterate through the same dictionary, this time retrieving the details for each
D
book title to show in a comprehensive report.
1.
inventory. or
Create a loop to calculate total quantity and price values for books in the
a) Highlight lines 77 through 81 and press Enter to delete those lines of code and start a new line.
e
at
lic
up
This code asked the user how many book titles there were and then assumed that each book title's
D
quantities were the same when it calculated the total. Instead, you'll rewrite the code to automatically
calculate the total quantity of books in the inventory.
To avoid typing, you can
ot
"Totals Loop".
o
D
e
ut
ib
tr
is
• Line 78 gets the length of book_inv (i.e., how many keys are in the dictionary). This will be
D
used shortly in the average-price calculation.
• Lines 79 and 80 initialize variables for total_quant and total_price, setting them both to 0.
Because of the way these variables are being reassigned on lines 83 and 84, you need to assign
them some value before this.
or
• Line 82 begins the for loop. It uses value as the iterator, and iterates through
book_inv.values(). In other words, it is iterating through all of the values in the dictionary,
regardless of the keys they are paired with. Recall that the values in the dictionary are lists of
e
book name, quantity, and price.
• Line 83 uses a shortcut operator to add the current value of total_quant to value[1], then
at
updates total_quant with that result. Since value is the for loop's iterator, it represents the
current list in the dictionary. It is being indexed at position 1 so that only the quantity is retrieved
(and cast as an integer).
lic
• Line 84 undergoes a similar process, but this time updating the total sales price for the current
book title in the inventory.
• When the first iteration completes, the next iteration starts. The value iterator then represents
up
the second list in the dictionary, and the total_quant and total_price variables are
updated accordingly.
• The process repeats until the iterator reaches the last values list in the dictionary, at which point
the loop exits.
D
• The whole point of this for loop is to iterate through every quantity value and every sales price
in the inventory, adding those values up one by one.
c) Highlight line 86 and press Backspace four times to remove the indents and delete the line.
ot
Note: Make sure to delete the # and the space after it so the code is properly
N
indented.
If you recall, this line calculates the average price by dividing the total price of all book titles in the
o
e
ut
ib
tr
The avg_price assignment and the print statements are not inside of the loop as they should only
be executed once.
is
2. Create a loop to print each book title in the inventory.
D
a) Highlight lines 68 through 72 and press Enter to delete those lines of code and start a new line.
or
e
at
lic
This code asked the user to specify just one book whose details to show, and then inefficiently
printed each detail. You want to show all details from all books, so you'll rewrite this code.
up
"Report Loop".
ot
N
o
D
e
ut
ib
• Lines 69 and 70 will make the output a bit easier to read.
tr
• Line 72 starts a for loop. This time, the loop is iterating through book_inv.items(), which
returns an iterable data structure of keys and values in the dictionary.
is
• Because the iterable structure stores keys and values separately, there are two iterators: key
and value. Each iterator will track the same key–value pair in the dictionary, even though
they're tracking different parts of it.
D
• Line 73 uses both iterators to print the current key (book ID) and all of the values (book name,
quantity, and price).
• As before, once the first iteration is done, the next iteration starts, until there are no more key–
•
value pairs left in the dictionary.
or
Ultimately, this for loop will print each book title as if it were a row in a table.
If students were unable
e
3. Test the "SHOW" and "SUMMARIZE" tasks. to finish writing the code,
have them open
a) Run the program.
at
inventory_entry_tpc_b_d
b) Select the "ADD" task. one.py from the project
c) Add a book with the following details: folder.
lic
• ID: F124
• Name: Bartleby, the Scrivener
• Quantity: 95
up
• Price: 9.95
d) Select the "SHOW" task.
D
ot
N
o
D
e) Verify that two books are shown and that their details appear as well.
e
ut
ib
tr
is
D
The output will look neater in an upcoming activity. For now, your program has successfully reported
all books in the inventory.
f) Select the "SUMMARIZE" task. or
g) Verify that the summary statistics for the two book titles are as shown.
e
at
lic
up
D
ot
N
Summary
In this lesson, you implemented conditional statements and loops into your code. The former will
enable your program to respond to changes in user input or program state, and the latter will help
you process repetitive logic more efficiently and easily.
Encourage students to
What are some common conditions in your apps that you'd want to test for in a use the social
conditional statement?
e
networking tools
A: Answers will vary. Testing user input is one of the most prominent use cases for a conditional provided on the CHOICE
ut
statement. If the user makes a choice, the conditional statement will evaluate that choice and act Course screen to follow
up with their peers after
appropriately. Another use for conditional statements is controlling which execution paths the program
the course is completed
takes based on how information is processed.
ib
for further discussion
and resources to support
When are for loops more useful than while loops in your program? continued learning.
tr
A: Answers will vary, but for loops are great for iterating through the items in a structure, like when you
need to read items from a list. They're also useful for executing the same processes over and over a
is
definite number of times, whereas a while loop waits for some condition.
Note: Check your CHOICE Course screen for opportunities to interact with your classmates,
D
peers, and the larger CHOICE online community about the topics covered in this course or
other topics you are interested in. From the Course screen you can also access available
resources for a more continuous learning experience.
or
e
at
lic
up
D
ot
N
o
D
e
ut
Lesson Time: 2 hours, 30 minutes
ib
tr
is
Lesson Introduction
D
Object-oriented languages excel at giving programmers the tools they need to make coding
easier. Reusing code not only enables you to develop at a quicker pace, but it also makes
or
your source code more readable. In addition, code that is resilient against errors is beneficial
to both users and developers. In this lesson, you'll employ Python's built-in mechanisms for
achieving these goals.
e
Lesson Objectives
at
TOPIC A
Define and Call Functions
Python® enables you to organize subroutines for easy reuse all throughout your source code. In this
topic, you'll write Python code to both define and call functions.
e
Function Definition
ut
Function Definition As you've seen before, a function is a block of code that is meant to be reused. The syntax for
Students may ask if they defining a function is similar to other objects you've seen, such as conditional statements and loops.
ib
can reuse functions The first line of a function includes its name and ends in a colon, and the code within a function is
throughout different indented. However, functions always begin with the statement def and include open and closing
scripts and projects.
tr
parentheses. The following is an example of a simple function definition:
Importing modules and
def my_function():
functions is covered in
is
the Certified Associate in print("This is a function.")
Python Programming Notice that the first parentheses are empty. This is acceptable in Python, but most functions are
(PCAP™) course.
D
designed to hold variables within these parentheses. These variables are called parameters. The
function uses these parameters in its code like it would use any other variable. For example:
def questions(name, quest, favorite_color):
print(f"Your name is {name}.")
print(f"Your quest is {quest}.")
or
print(f"Your favorite color is {favorite_color}.")
The function's name is questions and it has three parameters: name, quest, and favorite_color.
e
The code within the function uses these parameters to process the print statements.
at
Function Calling
lic
Function Calling Now that you have a function defined, how do you use it? Using functions, or more accurately,
calling them, is the process of actually executing the code within a function. Calling a function is
where you actually provide the values of the parameters that the function uses (if it accepts any)—
up
these are called arguments. Up until this point, you've actually been calling several functions. For
example, when you supply a value in print(), you're passing that value as an argument to Python's
built-in print() function. Using the preceding questions() function, the following code calls the
D
Parameters vs. In practice, people tend to use the terms "parameter" and "argument" interchangeably to refer to the
Arguments variables used by a function. But, they do refer to different things. A parameter is a variable that is
defined at the function level, when the function itself is defined. An argument is a value that is
passed into the function when it is called, after the function has been defined.
Parameters
e
Calling questions("Lancelot", "to seek the Holy Grail", "blue")
ut
Arguments
ib
Figure 5-1: Parameters vs. arguments.
tr
Argument-Passing Approaches: Position
is
There are three main ways to pass arguments into a function when calling that function: positional, Argument-Passing
keyword, and a mixture of the two. Approaches: Position
D
Passing arguments by position means that the arguments match the order of the parameters. You
can see this in the prior example: the first parameter is name, so the first argument "Lancelot" is
accepted by the function as the name value. The second parameter is quest, so the second argument
or
"to seek the Holy Grail" is accepted by the quest parameter, and so on.
The advantage of this approach is that you don't need to specify which argument applies to which
parameter, so it saves you on some typing. However, to use positional arguments effectively, you
e
need to actually know the order of each parameter in the function definition. This is not always
feasible, especially if you're using functions from a third-party module that some other programmer
at
The expression name = "Lancelot" comprises an argument, as do the other two expressions. The keyword-argument
advantage of this approach is that you don't need to know the order of the parameters when calling passing. It's being done
the function. You can rearrange the arguments to any order you want. For example, the following here to avoid text
ot
questions("Lancelot",
"to seek the Holy Grail",
favorite_color = "blue")
The first two arguments are passed by position, whereas favorite_color is passed by keyword.
This is a good approach to use when the order of the first few parameters is fairly obvious or
follows an easy-to-remember pattern, but you also need to pass in an argument that is less common
and harder to remember.
However, you cannot follow a keyword argument with a positional argument. Positional arguments
e
must always come before any keyword arguments in a function call. For example, the following code
will return an error:
ut
questions("Lancelot",
quest = "to seek the Holy Grail",
ib
"blue")
Python knows that "Lancelot" is referring to the first parameter, name. It also knows to assign
"to seek the Holy Grail" to the quest parameter since it's being specified. However, when
tr
Python gets to "blue", it doesn't know what position this is meant to refer to. Is it the second
position, since it's the second positional argument? Or is it the third position, since it's the third total
is
argument? Because of this ambiguity, Python cannot interpret this function call.
D
Default Parameter Values
Default Parameter Consider what happens when you call the questions() function but don't provide arguments for
Values
The error message and
the new function
definition have been
every parameter:
or
>>> questions("Lancelot", favorite_color = "blue")
...
e
questions() missing 1 required positional argument: "quest"
truncated for brevity.
When you define a function and you don't assign a default value to a parameter, you are required to
at
pass an argument for that parameter during the function call. This can become an issue because, for
some functions, certain parameters are optional. The calling code should not be forced to use such
lic
parameters.
To avoid this, you must assign default values to the parameters when defining the function. This is
the same as defining an object like a variable or an argument:
up
def questions(name,
quest = "to seek the Holy Grail",
favorite_color = ""):
D
...
Now you can call questions() without having to supply a quest argument:
questions("Lancelot", favorite_color = "blue")
ot
Note that, just as a positional argument cannot follow a keyword argument, a parameter without a
default cannot follow a parameter with a default. This is why assigning a default to favorite_color
N
is necessary (in this case, an empty string). You don't have to assign specific values for defaults;
empty strings are acceptable—though not necessarily the best approach.
o
The return Statement When you define a function, you can also return a value used within that function. Returning values
in functions is useful when you want to assign variables to function calls. You can use the return
statement to return a value. Consider the following function:
def age(year_of_birth, current_year):
return current_year - year_of_birth
This function takes a person's year of birth and the current year as arguments. The return function
returns that person's age by subtracting their year of birth from the current year. Now, consider the
function call:
>>> john_age = age(1939, 2023)
>>> print(f"John is approximately {john_age} years old.")
John is approximately 84 years old.
Because it returned a specific value, you are able to assign that value to a variable when calling the
age() function. This gives you a lot more power to process the results of your function's code.
e
The None Type
ut
When a Python function that does not explicitly return a value is called, it will return None after The None Type
ib
executing its code. None is a data type that indicates an object has no value assigned to it. This is
useful when you want your code to check if an object has a value or does not. It's more precise than
just checking if an object is empty, like an empty list ( [] ), because you may want to handle empty
tr
objects differently.
It's also common to assign None as the default value in a function parameter, e.g.:
is
def questions(name,
quest = "to seek the Holy Grail",
D
favorite_color = None):
...
Recursion or
Recursion, in the context of programming, is when a function calls itself from within its own code. Recursion
e
It is commonly used in scenarios where a problem can be solved by breaking it down into smaller
subproblems. Consider the task of solving a factorial of a number. A factorial of a number n is the
at
product of all integers from 1 to n. For example, the factorial of the number 4 (also formatted as 4!)
is:
lic
>>> 1 * 2 * 3 * 4
24
Think about how you might determine the equation itself. It can also be represented as 4 * 3 * 2
up
* 1 since you are essentially counting down from the initial number. You take the first number and
subtract 1 from it to get the next number, then you multiply the two numbers. You then repeat the
process: subtract 1 from the current number to get the next number, then multiply. In other words,
this problem can be broken down into multiple subproblems that directly depend on the solution to
D
Recursion Example
ot
def factorial(n):
# Base case.
if n == 0:
o
return 1
# Recursive case.
D
else:
return n * factorial(n - 1)
The if branch defines the base case. The base case is the input that produces a result that doesn't
recur. This is important for all recursive functions to have; without a base case, a recursive function
will recur indefinitely. In this function, the base case returns 1 if the current number is 0, meaning
the function is done counting down and there are no more numbers to add to the equation.
The else branch defines the recursive case. This is the code that solves a subproblem based on the
solution to the prior subproblem. It is multiplying the current number by the result of calling the
same function with n - 1 as the argument.
Here's the result of calling the function using 4 as n:
>>> factorial(4)
24
When called, the following steps happen:
1. The factorial() function is called with an argument of 4.
e
2. Since 4 is not equal to 0, the recursive branch is executed.
ut
3. The recursive branch calculates and returns 4 * factorial(3).
4. This calls factorial(3).
ib
5. Since 3 is not equal to 0, the recursive branch is executed.
6. The recursive branch calculates and returns 3 * factorial(2).
7. This calls factorial(2) and the process repeats.
tr
8. When factorial(0) is finally called, it returns 1 and the recursion ends.
9. The recursion "unwinds," supplying each return value in order through each function call, until it
is
eventually calculates 4 * 3 * 2 * 1, which is 24.
D
Scope: Local Variables
Scope: Local Variables When you create an object such as a variable, it is not necessarily available to be used throughout the
or
entire program. The programming concept of scope refers to where objects like variables are
"visible" within a program, and where they are not. For example, a variable used inside of one
function may not be visible to other functions.
e
1 # No variable created here.
2
at
3
4 def get_title(name, title):
5 # Variable created inside the function.
lic
In Python, the scope of an object depends on where it was created. Suppose a variable is created
within a function as shown in line 6 of the figure. When Python encounters that line of code, it
creates the variable in the context where it was encountered. So, the variable full_title is created
ot
inside of the get_title() function. The variable is said to be local in scope to that function, and it
will only be visible within that function.
The function is called on line 9, passing in values for the two arguments. Line 6 creates the variable,
N
assigning it a string composed of the title and name that were passed into the function, with a space
in between. The print statement on line 7 successfully prints out the resulting string "Sir Eddie".
However, after the function is called, line 11 of this example attempts to print out the value of
o
full_title. This causes Python to encounter an error because full_title doesn't exist within
the scope of line 11.
D
by that name, not the global variable with the same name. Outside the function, line 11 prints
full_title, but due to scope, it accesses the variable that was created on line 2, which still contains
the string "global created".
e
6 full_title = title + " " + name
7 print(full_title) "Sir Eddie"
ut
8 "global created"
9 get_title("Eddie", "Sir")
ib
10
11 print(full_title) No Error
tr
Figure 5-3: Local variable not visible in global scope.
is
Because of scope, some programmers moving into Python from another programming language
may experience some frustration trying to use global variables within functions. However, Python
operates sensibly, since using global variables as a way to pass data into and out of a function is
D
generally considered a poor programming practice. This is because global variables run the risk of
being modified anywhere within the code, potentially introducing errors or unwanted behavior in
your program. For larger, more complex programs, it is much more difficult to spot when and
where this can happen.
or
So, it is generally advised to use parameters to provide a function with input, and to return output by
providing a function return value, as shown in the following figure.
e
1 # Global variable created here.
at
Using well-defined points of input and output in a function will help you avoid unwanted side
ot
In instances where you have global variables and you want your functions to be able to update those
global variables, you can use the global keyword. For example:
o
x = 5
D
def my_func():
global x
x += 1
print(x)
Every time you call my_func(), it will add 1 to the global variable x.
Variable Shadowing
Variable shadowing, also called name hiding, is the practice of defining a variable in one scope that
has the same name as a variable in another scope. The prior two figures illustrate this—full_title
is both local to the get_title() function and global to the program. There is some debate as to
whether shadowing is a bad practice or an acceptable one. Certain integrated development
environments (IDE) like PyCharm may warn you about using shadowed variables, though this
doesn't mean you need to change them.
e
Function Call Stack
ut
Function Call Stack (2 The call stack is the sequence of functions that are called by the interpreter. In many cases, one
Slides) statement in Python will call multiple other functions—not simultaneously, but in an order. For
example:
ib
def one(x):
return 1 + two(x)
tr
def two(x):
return three(x) - 3
is
def three(x):
return x + 5
D
The execution of this code can be broken out in the following steps:
1. You call one(10) somewhere else in the code, and Python adds that function to the stack.
2. Python enters the one() function, but doesn't return anything yet because it calls two().
or
3. Python calls two(10) and adds it to the top of the stack.
4. Python enters the two() function, but doesn't return anything yet because it calls three().
5. Python calls three(10) and adds it to the top of the stack.
e
6. Python enters and executes the code in three(), which is 10 + 5 or 15.
7. Python "pops" three() off the stack and returns 15 to its calling function—two().
at
8. Python executes the code in two() using the returned value (15); i.e., it executes 15 - 3, which
is 12.
lic
9. Python "pops" two() off the stack and returns 12 to its calling function—one().
10. Python executes the code in one() using the returned value (12); i.e., it executes 1 + 12, which
is 13.
up
11. Python "pops" one() off the stack, leaving the stack empty and finishing execution.
12. The final value returned to the initial one(10) call is 13.
D
1 2 3 4 5 6
ot
three()
First function called, Second function called, Third function called, Third function Second function First function executed,
added to stack added to stack added to stack executed, popped off executed, popped off popped off stack; stack
D
Error handling is It should be fairly obvious that you need to understand what function a piece of code calls, and
discussed in more detail what function(s) that function calls, in order to read and write code effectively. But the call stack is
in the next topic. also important to understand when it comes to error handling. Python will usually provide you with
an error message that indicates where the error occurred for each function in the stack, from the
Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM
Lesson 5: Using Functions and Handling Exceptions | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 125
bottom all the way to the top. This is called a stack trace. With a stack trace, it's easier for you to
determine where the fault actually lies, and where to apply a fix.
e
CHOICE Course screen.
ut
Define Functions
When defining functions:
ib
• Place any parameters that the function needs to work with in parentheses.
• Assign default values to parameters that you want to remain optional when the function is called.
tr
• Don't try to use parameters without a default value after parameters with default values—they
won't work.
is
• Use return to pass values out of the function when it is called, especially when you need to
assign the call to a variable.
• Use recursive functions to solve problems that can be broken down into smaller subproblems.
D
• Create a base case in recursive functions to avoid indefinite recursion.
• Make sure the variables used in a function are within the proper scope. Don't use variables local
to a function outside of that function.
• Avoid using global variables in functions when possible.
or
• Consider how your function calls other functions, forming the call stack.
e
Call Functions
at
• Provide the necessary arguments that the function will work with in the parentheses.
• Be mindful of which data types your arguments are, so that they do not cause errors when
processed in the function.
up
• Determine which argument-passing approach is most appropriate for your usage of the function:
positional, keyword, or mixed.
• Don't try to use positional arguments after keyword arguments in a function call—they won't
work.
D
ACTIVITY 5-1
Defining and Calling Functions
Data File
e
/home/student/094027Data/Using Functions and Handling Exceptions/InventoryEntry/
ut
inventory_entry.py
Scenario
ib
Activity: Defining and The InventoryEntry program currently lacks structure. Every line is essentially in the same global
Calling Functions scope, which will make it difficult to reuse important sections of code. The code could also be much
easier to read and manage should you or another team member need to expand upon it in the
tr
future. So, to add some reusability to your code, you'll wrap some of the most important processes
in functions. These functions will help you logically group code blocks together so that you can call
is
upon them when necessary.
D
1. Launch PyCharm and open the InventoryEntry project.
a) Launch PyCharm if you have not left it running from a previous session.
or
b) In the Welcome to PyCharm window, select Open.
c) Beneath the 094027Data folder, expand Using Functions and Handling Exceptions, and select the
InventoryEntry project folder.
d) Select OK.
e
e) Configure PyCharm to trust all projects in this folder.
at
f) In the Project pane, double-click inventory_entry.py to show the source code in the editor.
To minimize time spent typing in class, the code has been filled out some more since you last saw it.
You'll review these changes shortly.
lic
The source code has been divided into three main sections to make it easier for a programmer to
orient themselves. These sections are marked using comments and are:
• HELPER FUNCTIONS: Contains functions that are meant to support the main logic of the
D
• MENU SELECTION: Contains code in the global scope that implements the selection menu.
Much of this you've already written, and some of it currently contains logic that should be moved
into inventory-task functions.
N
The first book title is no longer being hardcoded into the dictionary. The dictionary will grow as the
user enters book titles. However, the variable book_inv still needs to be initialized before it can be
used, so it's just being assigned an empty dictionary.
A condition has been added that checks to see if the entered book name is greater than 30
e
characters. If it is, the inner while loop repeats and asks the user for their input again.
d) Examine lines 111 through 121.
ut
ib
tr
is
D
or
The conditional logic in the "UPDATE" section is essentially the same as it is in the "ADD" section.
The book ID must actually be in the inventory in order to update it. The same length restrictions for
the ID and the name also apply.
e
e) Examine lines 136 through 138.
at
lic
To delete a book, its ID must already be in the inventory, so this is another example of checking for
up
that.
f) Briefly scan the rest of the code.
It's pretty much the same as you left it.
D
e
ut
• This line defines a custom function called add_book().
• Between the parentheses are the function's parameters. There are parameters for each of the
four book fields. Later, when you call this function, you'll pass values into these parameters
ib
based on the user's input.
d) Press Enter.
tr
The next line is indented for you. Like code inside conditions and loops, code inside functions must
be indented.
is
e) On line 36, press Ctrl+V to paste the code you cut.
D
or
e
at
The logic for adding a new book title is now part of this function. However, it needs to be rewritten to
lic
• The code to create the details list and to index the dictionary are now using the function's
o
parameters. In other words, the code inside the function will be able to use whatever values are
being passed into it.
• The book_details variable is locally scoped, meaning it is only being defined in terms of this
function's context. If you hover over the variable, PyCharm points out that it is being shadowed.
This means there is a book_details variable being used outside of this scope (i.e., outside of
this function). This is not necessarily a problem, but it's something to be cognizant of as you
write code.
g) Place the insertion point at the end of line 35 and press Enter twice to create new lines.
e
ut
ib
• Unlike book_details, this variable is being declared specifically as a global variable.
• Recall that just above the selection-menu code book_inv is initialized as an empty dictionary.
You want to be able to continually update this dictionary across multiple functions. If
tr
add_book() updates the dictionary to add a new entry, then the functions to update, delete,
etc., should be working with that same dictionary. The global keyword ensures the functions
is
are all updating that same globally scoped variable, rather than just one that is local to each
function. There are other ways to handle this without using global variables, but it's sufficient for
a relatively simple program like this.
D
4. Review the helper functions.
a) Examine lines 8 through 16.
or
e
at
lic
up
• This function, when called, will prompt the user to confirm whether or not they want to continue.
• The function has one parameter: message. You can pass in a custom message as an argument.
• Everything's wrapped in a while loop so that the user will keep being prompted until they
D
the code inside the while loop will finish, then repeat for a new iteration. In other words, the
user must answer properly.
• Line 13 checks if the user answered "yes". If so, the function will return the string "yes".
N
• Line 15 checks if the user didn't answer "yes". If they didn't, then the function will return "no".
• When the function is called, it can be assigned to a variable. That variable will contain either
"yes" or "no", assuming the user answers properly. This is the purpose of the return
o
statement in functions.
D
This is a simple function that prints the column headers neatly. There are several points where you'll
e
need to output a book title, so it helps to make this a function that you can call repeatedly.
c) Examine lines 25 through 27.
ut
ib
tr
• This function prints a book title as a row. You'd typically call this after print_cols().
• The function takes the familiar arguments.
is
• The print statement on line 27 prints each book field using string formatting to neatly pad and
align those fields under the columns.
D
• Once again, you can call this function multiple times when needed.
• Line 38 calls the print_cols() function. The function has no parameters, so no arguments
are being passed.
• Line 39 calls the print_rows() function, passing in the book fields as the parameters.
N
• Line 40 calls the input_yesno() function, passing in a custom message as the sole argument.
The function call is also being assigned to the variable response, which means it will take on
the function's return value.
o
○ Positional
○ Keyword
○ Mixed
7. Adjust the add_book() function's logic to account for the user's confirmation
response.
Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM
Lesson 5: Using Functions and Handling Exceptions | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 131
a) Place the insertion point on line 41, then press Enter to add a new line.
b) Type if response == "yes":
c) Highlight lines 43 and 44, then press Tab to indent them under the if branch.
d) Place the insertion point at the end of line 44, then press Enter to start a new line.
e) Write the code as shown. To avoid typing, you can
copy this code from the
L5.txt snippets file,
under the heading
"Handle Y/N Return
e
Values".
ut
ib
tr
is
D
•This conditional statement checks response for whatever value was returned by the
input_yesno() function.
• If the user entered "yes", meaning they've confirmed their addition, then the program will run the
True. or
code to add their entry to the book inventory. The return value of the add_book() function is
• If the user entered "no" to the confirmation, the program prints a warning message and returns
False.
e
• You'll use these return values soon, when you call the add_book() function.
at
f) Highlight line 50 with the print(book_inv) statement and press Delete twice.
a) Place the insertion point at the end of line 111 and press Enter to start a new line.
The add_book() function is ready to be called from the global scope.
To avoid typing, you can
up
Return Values".
ot
N
o
D
e
ut
ib
•Line 112 calls add_book() and assigns it to the add_result variable.
•The function is called with the book fields as arguments. These arguments are using the globally
tr
scoped variables that are defined on the lines above, when the program asks the user the
various questions about the book title they're adding.
is
• Lines 114 through 117 handle whatever the return value from add_book() is. Remember, if the
user enters "yes" for confirmation, True is returned. So, line 114 checks for this (True is implied
by default so you don't need to explicitly state it).
D
• If the user confirms their addition, the current while loop breaks, meaning the program will stop
asking the user the questions for adding a book.
• If the user does not confirm their addition, the current while loop restarts and asks the user the
book-related questions again.
or
c) Highlight the stray break statement on line 119 and press Delete.
This is no longer needed since you're controlling the loop above.
e
9. Test the logic of the "ADD" task.
at
h) Enter n
D
i) Verify that you are prompted to enter the book info again.
j) Enter a valid book ID, name, quantity, and price.
k) This time, enter y when prompted to confirm.
e
ut
ib
10.Stop the program and close the source code.
tr
a) From the Run console, close the inventory_entry tab.
is
b) In the Process 'inventory_entry' Is Running dialog box, select Terminate.
c) From the code editor, close inventory_entry.py.
D
or
e
at
lic
up
D
ot
N
o
D
ACTIVITY 5-2
Reviewing Updated Code and Testing the
Program
e
Data File
ut
/home/student/094027Data/Using Functions and Handling Exceptions/InventoryEntry/
inventory_entry_staged.py
ib
Before You Begin
To save time during PyCharm is running and the InventoryEntry project is open, but no Python scripts are open.
tr
class, students will open
up a staged file that has Scenario
the rest of the function
is
You've made good progress on the InventoryEntry program. A colleague has taken over the work
code written for them. of writing the remaining inventory-task functions and cleaning up the selection-menu code. You'll
This code doesn't
briefly review their work, then test out the program.
D
illustrate any new
concepts, so they will
just briefly review the
changes, then test the 1. Examine the code in the remaining inventory-task functions.
program.
Activity: Reviewing
Updated Code and
Testing the Program
the editor. or
a) In PyCharm, in the Project pane, double-click inventory_entry_staged.py to show the source code in
Most of the code for the remaining inventory-task functions has been filled in for you, and the menu-
e
selection code has been cleaned up accordingly.
If students are curious, b) Examine the update_book() function on lines 53 through 70.
at
PyCharm adds notation • This code is fairly similar to the code you wrote for the add_book() function.
to the top of each
• Just like add_book(), update_book() relies on the global book_inv to perform its task.
function that indicates
lic
how many times the Again, this ensures that the same dictionary is being updated throughout, regardless of function.
function is called in the All of the inventory-task functions use this global variable.
rest of the code. This • The biggest difference is that this function calls print_rows() twice. The first time, on line 58,
uses the local id but global book_inv values for the name, quantity, and price. The purpose is
up
• Line 79 shows the user the book detail for the book they're about to delete.
• As with the other functions, delete_book() asks for confirmation.
d) Examine the show_books() function on lines 89 through 99.
N
• The print_rows() helper function is being called for each key–value pair in order to output all
book titles in the inventory.
D
e
• Line 216 breaks the while loop regardless of whether the user says "yes" or "no" to the
confirmation. The idea is that a user might change their mind at the last minute and say "no";
ut
therefore, the program shouldn't keep prompting them.
c) Examine lines 218 through 226.
Both of these conditional statements call their respective inventory-task functions and nothing else.
ib
d) Examine lines 228 through 238.
• Before the program exits, it asks the user for confirmation. The input_yesno() function is
tr
called with a unique custom message as the argument.
• For lines 234 through 238, if the user confirms they want to exit, the outer while loop breaks,
is
which terminates the program since there's nothing left to execute. If the user changes their
mind, the loop restarts.
D
3. Test the program.
a) Run the program.
or
b) Select any task you want and enter the inputs however you want.
c) Test out the other tasks, or try different inputs for the same task.
d) Keep testing out the program until instructed to move on.
e) When you're done, select the "EXIT" task to quit the program, then close the Run console.
Encourage students to
play around with the
program and try different
inputs, but ensure you
e
don't lose too much
class time. There's still
at
4. Discuss your findings with the class. one topic and activity
left.
Did everything work as expected? Did you encounter any errors? If so, what In some cases, students
lic
return a
5. What other functionality or improvements might you want to add if you had ZeroDivisionError.
Assure them they will
time? handle exceptions in the
D
A: Answers will vary, as there are many ways this program could be improved. For example, it could next activity.
be coded in such a way that, after adding one book, it asks the user if they want to add another
book, rather than just send them back to the selection menu. Some students may point out that
ot
losing all changes after restarting the program is obviously not ideal, and that the inventory data
should be stored in a file or database somewhere.
N
o
D
TOPIC B
Perform Basic Exception Handling
Exceptions are commonplace in the programming process, and they can often break an application
in unforeseen ways. Thankfully, Python has built-in functionality for addressing exceptions, and in
this topic, you'll leverage this functionality.
e
ut
Exceptions
Exceptions It may not be possible or expedient to detect every potential problem situation in advance, so
ib
sometimes a program may encounter problems that get in the way of the normal flow of execution.
When something prevents the normal flow of execution from completing, an exception is said to
tr
have occurred. Python understands and is able to interpret the code, but is unable to execute it for
whatever reason. These types of errors are common in programs that access external resources. If,
for example, your code contains a statement that reads a file in a storage location that doesn't exist
is
or the program doesn't have adequate rights to access, an exception will be thrown when that
statement is run.
D
Exceptions may or may not result in the program crashing. They may just make a certain part of a
program non-functional while allowing the rest of the program to run just fine. Some exceptions are
unavoidable and don't even require major action on the programmer's part.
a = 3
b = 0
or
For a basic example of an exception, check out this simple arithmetic operation:
e
c = a / b
at
This code is syntactically sound, and most IDEs may not even pick up on the problem before
execution. However, attempting to run the program (from the console) will result in the following
error:
lic
This is an exception because Python understood the arithmetic, but the arithmetic itself (dividing by
zero) is mathematically undefinable. Python has no choice but to produce an exception. In this case,
Python will likely stop executing any code that follows this operation. However, any code that
D
exceptions. This can help you debug your code, but keep in mind that these line numbers do not
always indicate where you need to actually apply a fix.
N
of an exception higher up in the hierarchy. At the very top of the hierarchy is BaseException, from
which all other exceptions derive. Below this are various other exceptions, and so on for several
levels.
Becoming familiar with the exception hierarchy can help you determine how to handle exceptions.
The following figure demonstrates this hierarchy using some, but not all, of the built-in exceptions.
BaseException
e
ArithmeticError LookupError TypeError ValueError
ut
ib
IndexError KeyError
tr
Note: For an exhaustive list of exceptions, navigate to https://docs.python.org/3/library/
is
exceptions.html.
D
Built-In Exceptions
Aside from the hierarchy, exceptions are also classified in terms of their utility. Base or abstract Built-In Exceptions
The following table describes the built-in exceptions shown in the hierarchy figure.
e
Base Exception Definition
at
Exception Most other exceptions derive from this exception, not counting
those that are the result of exiting the program.
ArithmeticError The base exception for all other exceptions that pertain to arithmetic
up
KeyboardInterrupt The user presses the interrupt key, usually Ctrl+C or Delete.
SystemExit The sys.exit() function is executed, signaling to the interpreter
that it should stop execution.
N
e
Basic exception-handling code is structured with one try branch and one except branch after it.
ut
Within each of these branches is applicable code. The code that you actually want to test for errors,
or the code that you think might cause issues, goes inside the try branch. Within the except
branch is the code that Python executes if indeed there is an error. The following example
ib
demonstrates exception handling:
Ask students if they can try:
tell what might cause the
tr
print(f"Item in index {index}: {my_list[index]}.")
error. except:
is
print("An unspecified error has occurred.")
Depending on the value of index, Python might print to the console "An unspecified error has
occurred." So, in the try branch, you tried to index a list, and in the except branch, you output a
D
warning in case that didn't work. The code in the except branch wouldn't execute if the code in the
try branch didn't have an error.
or
Code in the except branch can be a simple warning, as shown in the prior example, or it can be
more complex code that attempts to keep the programming running as normal. How you handle
exceptions will depend heavily on the exception itself, as well as the nature of the code you're trying.
e
Specific Exception Handling
at
Specific Exception The prior example "caught" all possible exceptions because nothing was specified in the except
Handling statement. However, in most cases, you'll want Python to respond differently based on what type of
lic
exception it encounters. At the except branch, you can actually reference the type, and you can
even include multiple except branches. Like an elif branch in a conditional statement, Python will
go through each branch until it finds the value that matches the exception it found.
up
For example, let's say you want to handle any exception that isn't caused by a system-exit code. This
is what Exception is for. So, you can add that to the except branch like so:
try:
D
This time, you can be more sure that the error has to do with the code in the try block instead of
something else, like the user pressing the interrupt key. But, the code could be improved by using a
more specific exception—one that derives from Exception but is lower in the hierarchy.
N
The following code looks for an IndexError and prints the warning message if it encounters one:
try:
o
Exception Ordering
The prior code block doesn't necessarily handle potential exceptions properly. This is because it Exception Ordering
assumes a specific type of error that the faulty code won't necessarily encounter. There will be times
when you think you can anticipate the likely error a piece of code might encounter, but still need to
leave the door open for other possibilities. This is where using multiple except branches comes into
play.
Remember, except branches are like elif branches in that they will be checked in order.
Therefore, you want to design them so that the more-specific exception types—the ones lowest on
e
the hierarchy—are at the top, and the broader exception types—the ones highest on the hierarchy—
ut
are at the bottom. The broader types will essentially act as a "net" in catching any exceptions that
happened to slip by the earlier types.
For example, if you're still not sure of the exact exception likely to be encountered, you can do the
ib
following:
try:
tr
print(f"Item in index {index}: {my_list[index]}.")
except IndexError:
is
print("The list index is out of range.")
except Exception:
print("Unspecified error in print statement.")
D
If index is a string, such as "5", Python will print "Unspecified error in print statement" to the
console, because whatever the specific error might be, it's based on Exception (and it's not
IndexError).
or
Note: If index were "5", then the actual error in this case is TypeError, because the code is
trying to use a string as an index, whereas only integers can be used as indices.
e
at
statement. The raise statement can force Python to encounter an exception, which you can then
handle. The syntax for the raise statement refers to the specific exception you want to raise, and
then takes an optional exception argument within parentheses:
up
However, very rarely will you need to raise one of Python's built-in exceptions. Instead, you'll most exceptions is covered in
likely raise exceptions that are specific to your code as a way to help other programmers who will be the Certified Associate in
reusing your code. That way they can more easily debug code that is based on your code. This Python Programming
N
For example:
def divide(numer, denom):
try:
result = numer / denom
except ZeroDivisionError:
print("Can't divide by zero.")
raise # Re-raise the exception.
return result
e
def call(num1, num2):
ut
# Some business logic:
# ...
try:
ib
result = divide(num1, num2)
print(f"The result is: {result}")
except ZeroDivisionError:
tr
print("Error during division.")
And here's an instance of executing the code:
is
>>> call(10, 0)
Can't divide by zero.
D
Error during division.
The ZeroDivisionError exception is first raised in the divide() function, since it is called last
or
and executed first. The raise statement in the except branch tells the interpreter to re-raise the
exception in the function that called divide(), pushing it beyond that function's boundaries. The
call() function is able to receive the exception and handle it in its own way.
The advantage of handling exceptions in multiple places in the call stack is that it enables you to
e
handle exceptions in different ways depending on where the interpreter is currently executing code.
at
For instance, you might want the functions at the top of the stack to only handle exceptions in ways
that are specific to that function's purpose (like changing the input to make it valid), whereas the
calling functions can perform general exception-handling tasks (like sending a warning to the user).
lic
Exception Propagation: You may also want to delegate responsibility for handling an exception to a calling function, rather
Delegating than handle it in multiple places. The advantage of this approach is that it makes the code more
D
Responsibility to Another modular; you can more effectively separate exception handling from typical program logic. This can
Function make code easier to read and maintain.
To delegate exception-handling responsibility, you just need to include a raise statement in the
ot
except branches of the top-level function, and nothing else. That way, the exception will propagate
back to the calling function without the top-level function taking any other action. In the prior
example, this means removing the print statement in the divide() function:
N
e
Guidelines for Handling Exceptions
ut
Use the following guidelines to help you handle exceptions in Python.
Guidelines for Handling
ib
Handle Exceptions Exceptions
When handling exceptions:
tr
• Familiarize yourself with Python's built-in exceptions, as well as the exception hierarchy.
• Wrap any code you want to test for errors with a try...except statement.
is
• Place the code to be tested in the try branch.
• Place the code to execute if there is an exception in the except branch.
D
• Specify exception types in your except branches to pinpoint the root cause of the problem.
• Use multiple except branches to catch multiple exception types.
• Order except branches from specific to general in terms of the exception hierarchy.
or
• Use the raise statement to force Python to encounter an exception.
• Use the raise statement within an except branch to propagate the exception to calling
functions in the call stack.
e
• Propagate exceptions to multiple places in the call stack when you want to handle the
exceptions differently in different contexts.
at
• Delegate responsibility for handling exceptions to calling functions when you want to
separate exception-handling code from typical program logic.
lic
up
D
ot
N
o
D
ACTIVITY 5-3
Performing Basic Exception Handling
e
PyCharm is running, the InventoryEntry project is open, and the inventory_entry_staged.py
ut
script is open in the editor.
Scenario
ib
Activity: Performing You've written code to perform various data operations, including calculating statistics about the
Basic Exception books in the inventory. However, these calculations are prone to various runtime problems, like
Handling trying to divide by zero or performing arithmetic on non-numbers.
tr
There are various ways to deal with these problems, one of which involves creating exception
handlers that can gracefully react to invalid or undesired inputs.
is
D
1. Trigger an exception in the program.
a) Run the program.
b) Select the "ADD" task.
c)
d)
e)
Enter a book ID and name.
or
When prompted to enter the quantity, enter one hundred
When prompted to enter the price, enter twelve dollars
e
f) Confirm the addition.
g) Select the "SUMMARIZE" task.
at
• When Python encounters an exception, it outputs the call stack that led to the exception being
ot
encountered—also called a traceback. The traceback indicates the line numbers for each
function where the exception was encountered.
• Python also outputs the type of exception it encountered, and in some cases, offers an
N
2. Tracebacks list the most recent function call at the top. The bottom of the
o
e
ut
In the same summarize_book() function, line 115 triggers the error.
ib
4. Why do you think Python was trying to divide by zero?
tr
A: The total_ids variable refers to the number of book titles in the inventory. If no books have
been added yet, then that number remains at 0—the value it was first initialized with.
is
5. Add code to handle the ValueError exception.
D
a) Place the insertion point at the end of line 36, then press Enter twice to add new lines.
b) Starting on a new line 38, write the code as shown. To avoid typing, you can
copy this code from the
• There are many ways you could handle this problem; this is just one example.
• In this case, the add_book() function will try to convert quant to an integer and price to a
float.
ot
• If both statements execute without an exception, the interpreter will continue. However, if either
one encounters a ValueError exception, the code in the except branch will run.
• If the error does trigger, the program will tell the user their input is invalid.
N
• As the code is currently written, the interpreter will still attempt to execute the statements starting
on line 45, even if it encounters a ValueError. You need to rewrite the code to stop this.
c) Place the insertion point on line 44 and press Tab to ensure it is indented once.
o
d) Type else:
D
e) Highlight lines 45 through 56 and press Tab to indent them within the else branch.
e
ut
ib
tr
is
D
Now, the rest of the code will only execute if the except branch isn't executed. Just as you can add
else branches to conditionals and loops, you can also add them to exception handlers.
f) Place the insertion point at the end of line 61, then press Enter twice to add new lines.
•
•
•
Indent line 69 and type else:
or
g) Repeat the prior substeps for the update_book() function:
Add the same try...catch branches as before to lines 63 through 68.
e
ut
ib
tr
is
D
or
e
at
Since both adding and updating books involves entering quantity and price values, the exception-
handling code should apply to both.
lic
c) Highlight line 129 and press Tab to indent it under the try branch.
d) Place the insertion point at the end of line 129, then press Enter to start a new line.
To avoid typing, you can
D
"Handle
ZeroDivisionError".
N
o
D
e
ut
ib
• This time, the avg_price calculation is being tried for errors.
• On lines 130 and 131, if a ZeroDivisionError is triggered because of that calculation, then
the program will tell the user that it can't summarize the books if there are none.
tr
• Lines 132 through 134 catch any other exceptions that fall under the Exception type. This is
most exceptions. In case Python encounters some unanticipated problem other than
is
ZeroDivisionError, this except branch will run its code.
• In this case, lines 132 through 134 are acting as a "safety net" to broadly catch any other
problems that might arise. Writing multiple except branches enables you to assert more
D
granular control over exception-handling logic.
f) Place the insertion point on line 135 and ensure it is indented once.
g) Type else: and then indent the rest of the code within this function.
7.
or
As before, you only want this code to execute if there are no exceptions.
When writing multiple except branches, why should you always order the
e
exception types from specific to general according to the exception hierarchy?
at
A: A general exception type that has a more specific exception type under it will always catch that
specific exception if it has not already been caught. The branch with the specific exception will
never execute, making it pointless.
lic
8. Verify that the exceptions are being handled properly in the running program.
a) Rerun the program.
up
e) Verify that you are prompted to re-enter the book ID after being told the quantity/price are invalid.
In both cases, the exception-handling code is doing its job.
ot
Summary
In this lesson, you made your code more amenable to reuse through functions. Structuring your
code around functions will make your code easier to manage and easier to incorporate elsewhere.
You also dealt with the exceptions that are inevitable in any programming project. With the proper
handling techniques, you'll be able to minimize program failures and improve your debugging
process.
e
Encourage students to
What types of custom functions might you define in your apps? use the social
ut
A: Answers will vary depending on the app, but any chunk of programming logic that the app is likely to networking tools
execute multiple times will benefit from being put into a custom function. For example, an app that provided on the CHOICE
draws a graph based on some dataset will likely need to draw that graph every time the data Course screen to follow
ib
up with their peers after
changes. The graph-drawing code could be put into a custom function called draw_graph() that the
the course is completed
developer calls whenever the data changes and they need to see the latest graph. That way, the
for further discussion
tr
developer won't need to write the graph-drawing code over and over. and resources to support
continued learning.
What kinds of exceptions might your apps encounter?
is
A: Answers will vary depending on the app. Exceptions like IndexError and TypeError are fairly
common when working with data structures. Most exceptions will at least derive from Exception.
D
Note: Check your CHOICE Course screen for opportunities to interact with your classmates,
peers, and the larger CHOICE online community about the topics covered in this course or
or
other topics you are interested in. From the Course screen you can also access available
resources for a more continuous learning experience.
e
at
lic
up
D
ot
N
o
D
Course Follow-Up
Congratulations! You have completed the Certified Entry-Level Python Programmer (PCEP™) course.
You have successfully applied the fundamental elements of the Python® programming language to
create a simple application. Python is a versatile language and understanding the basics will help you
eventually develop more complex apps for desktop, mobile, and web platforms.
What's Next?
e
The next course in this series is Certified Associate in Python Programming (PCAP™). For programmers,
cybersecurity is a major concern, so you might also consider taking CertNexus Certified Cyber Secure
ut
Coder® (Exam CSC-210).
You are encouraged to explore Python further by actively participating in any of the social media
ib
forums set up by your instructor or training administrator through the Social Media tile on the
CHOICE Course screen. You may also wish to explore the official Python documentation website
at https://docs.python.org/3/ for more information about the language.
tr
is
D
or
e
at
lic
up
D
ot
N
o
D
e
to PCEP™ – Certified
ut
Entry-Level Python
ib
Programmer (Exam
tr
is
PCEP-30-02)
D
or
Obtaining the Certified Entry-Level Python Programmer certification requires candidates to
pass the PCEP™ – Certified Entry-Level Python Programmer Exam PCEP-30-02.
To assist you in your preparation for the exam, Logical Operations has provided a reference
document that indicates where the exam objectives are covered in the Logical Operations
e
Certified Entry-Level Python Programmer (PCEP™) courseware.
at
The exam-mapping document is available from the Course page on CHOICE. Log on to
your CHOICE account, select the tile for this course, select the Files tile, and download
and unzip the course files. The mapping reference will be in a subfolder named Mappings.
lic
e
ut
ib
Mastery Builders are provided for certain lessons as additional learning resources for this
tr
course. Mastery Builders are developed for selected lessons within a course in cases when
they seem most instructionally useful as well as technically feasible. In general, Mastery
is
Builders are supplemental, optional unguided practice and may or may not be performed as
part of the classroom activities. Your instructor will consider setup requirements, classroom
D
timing, and instructional needs to determine which Mastery Builders are appropriate for you
to perform, and at what point during the class. If you do not perform the Mastery Builders
in class, your instructor can tell you if you can perform them independently as self-study,
or
and if there are any special setup requirements.
e
at
lic
up
D
ot
N
o
D
e
Scenario
ut
The Editing department at Fuller & Ackerman (F&A) has decided to use a program to
perform initial analyses of manuscripts submitted by authors. Eventually, a wide range
ib
of analyses will be performed, but some software requirements have been identified for
a prototype application that you will develop in Python.
tr
Word List
100,000+
is
English
words Common Words
Input File
aardvark the
D
… be
Manuscript zymurgy are
is
…
+ 50
-
Read all
words
The quick
brown fox
If a
manuscript
word
the: 23
or
quick: 13
brown: 15
fox: 11
After
manuscript
words are
counted,
the: 23
brown: 15
quick: 13
fox: 11
Strip
the: 23
brown: 15
quick: 13
fox: 11
e
jumped appears in common
from the keep 50
over the word list, jumped: 9 … words …
manuscript most
lazy dog… count it over: 8
frequent
at
lazy: 7
…
lic
code.
Note: There is not necessarily a "correct" way to write every line of code, as there
o
are often several ways to write code to do the same thing. You can write the code
however you feel most comfortable, as long as it accomplishes the tasks set out
D
for you. If you are stuck and need help, you can "borrow" code from the
InventoryEntry scripts, and/or consult the official Python documentation.
e
3. On the first line, write a comment with the following text:
ut
This program counts the number of times each unique word appears in a text file.
ib
4. Write code to prompt the user to enter text for analysis.
Assign the prompt to the variable user_text.
tr
5. Write code to ask the user whether or not they want to strip common words
is
from the results (yes or no).
Assign the prompt to the variable user_common_words.
D
6. Write code to print the user's text and their decision to strip words on separate
lines.
7.
8.
Run the program and provide any input you want.
e
Activity Time: 15 minutes
ut
Data File
/home/student/094027Data/Processing Simple Data Types/WordCount/
ib
word_count.py
tr
Scenario
You've written the beginnings of the WordCount program, including some basic input
is
and output statements. Now you want to test out your program's ability to calculate
word frequencies based on user input, as well as print those frequencies to the user in a
friendly way. For now, you'll estimate the frequency for a word based on the number
D
of times it appears in one chapter. Later, you'll actually write code to automatically
count every word.
or
Note: There is not necessarily a "correct" way to write every line of code, as there
are often several ways to write code to do the same thing. You can write the code
however you feel most comfortable, as long as it accomplishes the tasks set out
for you. If you are stuck and need help, you can "borrow" code from the
e
InventoryEntry scripts, and/or consult the official Python documentation.
at
2.
3. Write code to prompt the user to enter the number of times that the
word "boat" appears in the first chapter.
D
formatting as necessary:
D
6. Run the program and provide any whole number when prompted to
enter the number of times "boat" appears in the first chapter.
Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM
Mastery Builders
Certified Entry-Level Python Programmer (PCEP™) | 157
Note: You can input whatever you want for the prior two prompts.
7. Verify that the estimated count for "boat" was printed in the proper format.
e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D
e
Activity Time: 20 minutes
ut
Data File
/home/student/094027Data/Processing Data Structures/WordCount/word_count.py
ib
Scenario
tr
You've worked with integers and strings in the WordCount program; now it's time to
add data structures like lists and dictionaries. These will enable the program to work
is
with collections of data, like the manuscript words that the program should eventually
process.
D
Note: There is not necessarily a "correct" way to write every line of code, as there
are often several ways to write code to do the same thing. You can write the code
however you feel most comfortable, as long as it accomplishes the tasks set out
or
for you. If you are stuck and need help, you can "borrow" code from the
InventoryEntry scripts, and/or consult the official Python documentation.
e
1. Open the /home/student/094027Data/Processing Data Structures/
at
The code that estimated the number of words has been removed. There are also new
input statements for three different words, each one assigned to its own read_input
variable.
D
You can do this by adding .strip(".,?!\"\';:()") to the end of the list item.
D
7. Write code to create a dictionary word_count where the keys are the
words from the list, and the value for each key is 1.
9. Run the program, and enter the following for each of the three words:
• Test!
• test
• teSt
10.Verify that you are given a dictionary with each word as the key and 1 as the
value (frequency).
e
11.Verify that the punctuation from the first word was removed.
ut
12.Close the project and PyCharm.
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D
e
Activity Time: 60 minutes
ut
Data File
/home/student/094027Data/Writing Conditional Statements and Loops/
ib
WordCount/word_count.py
tr
Scenario
Now it's time to make WordCount more programmatic by ensuring it:
is
• Asks the user if they want to strip common words from the results until the user
answers satisfactorily.
D
• Removes punctuation from all words.
• Creates a dictionary to hold each word and its frequency.
• Outputs the frequency of each word depending on whether or not the user chose
to strip common words.
or
You'll achieve these goals by incorporating both loops and conditional statements.
e
Note: There is not necessarily a "correct" way to write every line of code, as there
are often several ways to write code to do the same thing. You can write the code
at
however you feel most comfortable, as long as it accomplishes the tasks set out
for you. If you are stuck and need help, you can "borrow" code from the
InventoryEntry scripts, and/or consult the official Python documentation.
lic
• The values for the common words, manuscript input, and word list are all hardcoded
into the program for this prototype.
• The common words are put in a set (COMMON_WORDS) since they're unique in that
N
data structure.
• The words in the manuscript are put into a list (read_input), as are the words in the
word list (read_wordlist).
o
• The user is still being asked for the text, although this won't do anything until the
manuscript files are available.
• The user is still being asked if they want to strip common words from the result, which
you'll deal with soon.
5. Write code to create a while loop so that the user is continually asked if they
want to strip common words (user_common_words) until they provide a
value answer ("y" or "n").
e
• The third line under the comment also makes each word lowercase.
ut
• The count variable is being incremented to keep track of the list indices.
ib
of words and frequencies. Make sure the loop:
• Makes the word lowercase.
tr
• If the word is in read_wordlist, then:
• If the word is not in word_count (the dictionary defined under the # Create dictionary
is
of words and frequencies comment), assigns the dictionary key of that word to a value of
1.
• If the word is in word_count, then assigns the dictionary key of that word to a value that is one
D
greater than its current value.
Note: This will require nesting if statements inside the main if statement,
•
which is itself nested inside the for loop.
or
If the word is not in read_wordlist, then continues to the next iteration of the for loop.
e
8. Write code to loop through each word in items (the sorted list of the
word_count dictionary) to truncate the output if the user chooses to
at
• If the user chooses not to suppress common words, or if the user chooses to suppress common
words but the current word is not in COMMON_WORDS, then:
• Assigns the word along with its frequency to result in the following format: <word>:
up
<frequency> times
• Prints result to the screen.
Note: For each list item, the items list holds a tuple of each word and its
D
frequency. You need to index the first item in the tuple to get the word, and
the second item in the tuple to get the frequency.
ot
• If the user chooses to suppress common words and the current word appears in COMMON_WORDS,
then does nothing.
N
9. Run the program and verify that the prompt asking if the user wants to
suppress common words will keep appearing until you enter either y or n.
o
10.Enter y at the question prompt and verify that you receive the following
results:
D
test: 4 times
this: 3 times
11.Rerun the program, enter n at the question prompt, and verify that you receive
the following results:
a: 1 times
is: 3 times
test: 4 times
this: 3 times
e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D
e
Data File
ut
/home/student/094027Data/Using Functions and Handling Exceptions/WordCount/
word_count.py
ib
Scenario
You'll add some structure to the WordCount program so that important sections of code can be
tr
easily reused. Adding code to functions will also make the code easier to read, especially when the
program grows much larger.
is
Note: There is not necessarily a "correct" way to write every line of code, as there are often
several ways to write code to do the same thing. You can write the code however you feel most
D
comfortable, as long as it accomplishes the tasks set out for you. If you are stuck and need help,
you can "borrow" code from the InventoryEntry scripts, and/or consult the official Python
documentation.
3. Take all of the code from line 10 to 37 and place it inside of a new
words_dict() function that you define.
up
This places all of the code that compares the input to the word list under the function. Now this code is
no longer in scope of the whole program, but in scope of the words_dict() function.
4. Inside the words_dict() function, at the end, write code to return the
D
5. Take all of the code below word_dict() that prints and suppresses the
N
e
ut
10.Run the program and verify that it outputs the word frequencies as
expected.
ib
11.Close the project and PyCharm.
tr
is
D
or
e
at
lic
up
D
ot
N
o
D
e
ut
ib
ACTIVITY 1-5: Preventing Errors
tr
is
7. Why does the program print the wrong value? How can you fix this
statement to get the program to print the right value?
D
A: The print statement prints book_id, which is the first input. You can change the statement
to say print(book_name) to get the program to print the second input.
A: The num_books_query variable is a string, and only strings can be concatenated. Since
total_quant is an integer, it must use interpolation so that it's formatted properly in the
string.
D
A: The result would be 120.0. In an operation with a mix of integers and floats, the result
always widens to a float.
9. Why did the 'fiction' string get applied to both books, even
though it was only asked once?
A: In the source code, on lines 45 and 46, the book_genre variable was appended to
both book_1 and book_2.
e
ut
ACTIVITY 3-3: Choosing an Appropriate Data
Structure
ib
tr
1. Which data structure would you use to store the grades of each
student, and why?
is
A: Answers may vary, but a tuple is probably the best choice. Tuples are immutable, so
they cannot be changed elsewhere in the program. They can also hold a variety of data
D
types, so even if the grades are numbers, letters, or some mix of the two, it won't be a
problem.
Which data structure would you use to store each city's weather
2.
data, and why?
or
A: Answers may vary, but a dictionary would be a good choice. The city name would be
the keys, and the weather info for each city would be the values. That would enable a
e
user to easily look up a city to see its weather info. And, because dictionaries are
mutable, that info can be easily updated. The values in the key–value pairs could be
at
3.
room, and why?
A: Answers may vary, but the most efficient way to accomplish this is to use a range.
up
Ranges easily create sequences from a beginning integer to an ending integer, so you
can just create room numbers from 1 to 120. Also, ranges are immutable, so they won't
be changed later.
D
4. Which data structure would you use to store each directory's file
names, and why?
ot
A: Answers may vary, but in this situation, you'd be able to accomplish this fairly easily
using two sets. Sets are unordered and must contain unique values, so each directory
could have its own set, where the file names for that directory are the values. And, you
can use .intersection() to find the duplicates across both sets.
N
5. Which data structure would you use to store each task, and why?
o
A: Answers may vary, but a list is a good candidate. Lists are ordered, so the tasks could
be created and retrieved in the desired order. They are also mutable, so the user can
D
e
ut
ACTIVITY 5-2: Reviewing Updated Code and Testing the
ib
Program
tr
4. Did everything work as expected? Did you encounter any errors? If so, what
did you do to trigger those errors?
is
A: Answers may vary. Most of the functions should work, but there are a few cases where students will
experience a program crash.
D
5. What other functionality or improvements might you want to add if you had
time?
or
A: Answers will vary, as there are many ways this program could be improved. For example, it could be
coded in such a way that, after adding one book, it asks the user if they want to add another book,
rather than just send them back to the selection menu. Some students may point out that losing all
e
changes after restarting the program is obviously not ideal, and that the inventory data should be stored
in a file or database somewhere.
at
lic
added yet, then that number remains at 0—the value it was first initialized with.
7. When writing multiple except branches, why should you always order the
N
specific exception if it has not already been caught. The branch with the specific exception will never
execute, making it pointless.
D
e
ut
ib
argument calling
A value passed into a function that the The process of invoking a function, usually
tr
function uses when called. by providing arguments for the function to
use (if it accepts any).
is
arithmetic operator
An operator that performs basic cloning
D
mathematics on numbers, including See deep copy.
addition, subtraction, multiplication, and
division. command shell
assignment operator
An operator that performs variable
or Software that enables a user to directly
interact with a computer's operating
system by executing commands.
e
assignment using a shortcut.
comparison operator
at
binary values.
concatenation
Boolean The process of combining strings end to
ot
constant
call stack An identifier with a value that does not
The sequence of functions called by the change.
interpreter.
e
specific task.
The property that defines how a variable is
ut
classified and stored in memory. global variable
A variable that is useable everywhere
debugger within a program's source code.
ib
A software tool that helps a programmer
to detect and test errors in a program's hexadecimal
tr
source code. A numeral system with a base of 16.
is
deep copy IDE
The act of copying the outer and inner (integrated development environment)
D
elements of an object like a list. Software that assists programmers in
writing code.
dictionary
identifier
error
or
An unordered, mutable data structure that
has key–value pairs. The name attached to an object, like a
variable, class, function, etc.
e
An incorrect or unintended result after the IDLE
at
A type of error that indicates the position of that value in the object.
interpreter is able to understand the code
integer
ot
exception handling
The process of anticipating and responding interactive mode
to program exceptions. A Python feature in which the interpreter
o
keyword operand
A word that cannot be used as an object The values that an operator evaluates.
e
identifier because it has a fixed meaning.
operator
ut
lexis Objects that can evaluate expressions.
The set of all terms recognized by a
programming language. operator precedence
ib
See order of operations.
list
order of operations
tr
A mutable sequence that can hold different
types of values. The order in which operators in an expression
is
are executed.
list comprehension
parameter
D
A technique for creating a list using a loop and
a condition within a single statement. A value defined with a function that the
function uses when called.
local variable
A variable that is bound to a specific object,
such as a function, and cannot necessarily be
used outside of that object.
PEP
or
(Python Enhancement Proposal) A public
document that describes a design element of
e
Python or proposes a new feature.
logic error
at
An operator that connects multiple values A set of files used to develop a program in
together so they can be evaluated. Python, typically stored within a directory that
contains Python source code, configuration
loop files that specify how the code should be
D
A statement that executes code repeatedly. processed to create the finished program, and
other supporting files.
matrix
ot
nesting
The act of placing a programming construct
within another programming construct.
semantics tuple
The meaning of terms written in a An immutable sequence that can hold different
programming language. types of values.
e
sequence type casting
ut
An ordered collection of elements. The process of converting data from one type
to another type.
set
ib
An unordered, mutable data structure with unary operator
individual entries that cannot be repeated. An operator that performs an operation on a
tr
single operand.
shallow copy
is
The act of copying the outer elements of a variable
mutable object like a list. A value that is stored in memory and is
D
associated with an identifier.
shortcut operator
See assignment operator. variable shadowing
slicing
or
The process of retrieving a group of values in
an object like a string or list by the desired start
The practice of defining a variable in one scope
that has the same name as a variable in another
scope.
e
and end positions of those values in the object. vector
at
A one-dimensional list.
source code
Code written by a programmer in a high-level virtual machine
lic
programming language such as Python, which In CPython, the software environment that
is then processed by an interpreter or compiler executes bytecode.
for execution on the computer.
up
string
A sequence of characters stored in memory.
D
string interpolation
The process of replacing variable placeholders
ot
string literal
A value that is enclosed in single or double
quotation marks.
o
syntax
D
e
ut
ib
tr
A decimals 53
dictionaries 74, 75
is
arithmetic operators 18
floats 53
in Python 46
B
D
integers 46
bytecode 4 numbers 46
sequences 62
C
command shell 5
or sets 76
strings 47
debugger 5
e
comments 26 dictionaries
compilers modification 74
at
concatenation 47
conditional statements
E
assignment or shortcut operators 90
errors
up
bitwise operators 89
booleans 88 logic error 37
comparison operators 88 syntax error 37
elif statement 87 types of 37
D
logical operators 89
nested if statement 88 exception handling
order of operations 91 delegate to calling function 140
N
D built-in 137
data structures hierarchy 136
mutable vs. immutable 62 overview 136
sequences 62 raise statement 139
data types
F L
floor division 19 lexis 17
functions list comprehension 104
arguments 118 lists
calling 118 copying 66
call stack 124 deep copying 67
deepcopy () 67 indexing and slicing 63
defined 27, 118 in Python 63
e
float() 54 multidimensional 63
ut
format() 48 operations 64
help 15 processing 64
input() 28 shallow copy 67
ib
int() 47, 54 loops
None type 121 control statements 103
tr
parameters 118, 120 dictionary 102
parameters vs. arguments 118 else branch 102
is
passing arguments 119 for loop 101
print() 27, 28 list comprehension 104
D
recursion 121 nested 103
return statement 120 overview 100
str() 47 range 102
H
help utility 15
or M
while loop 100
e
modulo 19
at
I
identifier 17 N
lic
IDEs numbers
configuration 6 decimals 53
IDLE 4 floats 53
up
popular 5 integers 46
IDLE 4 mixed number types 54
indexing 47 subtypes 46
D
IDEs hexadecimal 49
interactive mode 15 octal 49
interpreters
N
CPython 4 O
examples of 4
operands 18
o
interactive mode 15
overview 3 operator precedence 19
D
P type casting 47
PEP 17
PEP 8 17 V
project folders 6 variables
Python assignment 17
app types 2 global variables 122
file extensions 26 local variables 122
history 2
e
variable shadowing 124
implementations 4 virtual machine 4
ut
overview 2
scripts and files 26
syntax 16
ib
Python Enhancement Proposal, See PEP
tr
R
is
ranges
in Python 67
reserved words 18
D
See also keywords
S
scope
defined 122
or
e
global variables 122
local variables 122
at
sequences
lists 63, 64, 66
ranges 67
up
tuples 68
types 62
sets
D
overview 76
processing 76
slicing 47
ot
string interpolation
float precision 54
format() 48
N
f-strings 49
string literals 20
o
string operators 47
strings 47
D
T
tuples
in Python 68
operations 68
processing 68
Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM
Index
e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D