[go: up one dir, main page]

0% found this document useful (0 votes)
111 views184 pages

PCEP Student Book

The document outlines the Certified Entry-Level Python Programmer (PCEP™) course, which introduces learners to Python programming fundamentals. It includes lessons on setting up the development environment, processing data types, writing conditional statements, and handling exceptions, aimed at preparing students for the PCEP certification. The course is designed for individuals with basic computing skills and provides resources for further learning and assessment through the CHOICE platform.

Uploaded by

ritaavalentine
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views184 pages

PCEP Student Book

The document outlines the Certified Entry-Level Python Programmer (PCEP™) course, which introduces learners to Python programming fundamentals. It includes lessons on setting up the development environment, processing data types, writing conditional statements, and handling exceptions, aimed at preparing students for the PCEP certification. The course is designed for individuals with basic computing skills and provides resources for further learning and assessment through the CHOICE platform.

Uploaded by

ritaavalentine
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 184

e

ut
ib
Certified Entry-

tr
Level Python

is
D
Programmer
(PCEP™) or
e
at
lic
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Certified Entry-Level Python
Programmer (PCEP™)

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Certified Entry-Level
Python Programmer

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

Topic C: Create a Python Application............................................ 26


Topic D: Prevent Errors.................................................................37
lic
up

Lesson 2: Processing Simple Data Types....................... 45


Topic A: Process Integers and Strings........................................... 46
D

Topic B: Process Decimals, Floats, and Mixed Number Types........ 53


ot

Lesson 3: Processing Data Structures............................61


N

Topic A: Process Ordered Data Structures.....................................62


Topic B: Process Unordered Data Structures................................. 74
o
D

Lesson 4: Writing Conditional Statements and Loops.... 85


Topic A: Write Conditional Statements.......................................... 86
Topic B: Write Loops...................................................................100

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


| Certified Entry-Level Python Programmer (PCEP™) |

Lesson 5: Using Functions and Handling Exceptions........... 117


Topic A: Define and Call Functions....................................................... 118
Topic B: Perform Basic Exception Handling........................................... 136

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


About This Course

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

• Using Microsoft® Windows® 11


• Using Microsoft® Windows® 11: Transition from Windows® 10
• Using Microsoft® Windows® 10 (Second Edition)
N

Course Objectives
o

In this course, you will develop simple command-line programs in Python. You will:
D

• Set up Python and develop a simple application.


• Perform operations on simple data types, including strings and numbers.
• Perform operations on data structures, including lists, ranges, tuples, dictionaries, and
sets.
• Write conditional statements and loops.
• Define and use functions, and perform basic exception handling.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


| Certified Entry-Level Python Programmer (PCEP™) |

The CHOICE Home Screen


Logon and access information for your CHOICE environment will be provided with your class
experience. The CHOICE platform is your entry point to the CHOICE learning experience, of
which this course manual is only one part.
On the CHOICE Home screen, you can access the CHOICE Course screens for your specific
courses. Visit the CHOICE Course screen both during and after class to make use of the world of
support and instructional resources that make up the CHOICE experience.
Each CHOICE Course screen will give you access to the following resources:

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

How To Use This Book


up

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

reference and reflection to facilitate understanding and practice.


Data files for various activities as well as other supporting files for the course are available by
N

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

you're back on the job and need to refresh your understanding.


At the back of the book, you will find a glossary of the definitions of the terms and concepts used
throughout the course. You will also find an index to assist in locating information within the
instructional components of the book. In many electronic versions of the book, you can click links
on key words in the content to move to the associated glossary definition, and on page references in
the index to move to that term in the content. To return to the previous location in the document
after clicking a link, use the appropriate functionality in your PDF viewing software.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


| About This Course |
| Certified Entry-Level Python Programmer (PCEP™) |

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


| About This Course |
e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


1 Setting Up Python and
Developing a Simple

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

In this lesson, you will:


• Set up a Python development environment.
• Write Python statements.
up

• Create a Python application.


• Prevent errors.
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


2 | Certified Entry-Level Python Programmer (PCEP™)

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

• Spotify®, a popular music-streaming service.


• Dropbox®, a cloud-based file-hosting service.
• PyCharm®, a programming tool (used in this course).
up

• Django®, an open-source web framework.


• Blender™, a 3D-art and animation app.
D

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

will be explained later in


the course.
Python 2 was the first major update to the Python programming language, released in October 2000.
Python 2 improved upon the original Python by adding features like garbage collection, augmented
Inform students that this
o

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 3

Interpreters and Compilers


In computer programming, an interpreter is software that executes written code so that it runs on Interpreters and
the operating system. A compiler translates code written in one programming language into a Compilers
different programming language. Point out that students
will use a Python
Compilers and interpreters have a similar purpose. They perform some operation on source code
interpreter in this course.
so that it can eventually be used to execute programming instructions. Source code is code written
by a programmer in a high-level programming language like Python. A high-level language means
that the code is abstracted from the instructions that are directly executed by a processor. A low-

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

into executable it as program runs


• Faster once compiled • Easier to use
D

• Reveals errors when • Portable


program is compiled

Figure 1-1: A Venn diagram comparing compilers to interpreters.


Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM
Lesson 1: Setting Up Python and Developing a Simple Application | Topic A
4 | Certified Entry-Level Python Programmer (PCEP™)

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

Bytecode Virtual machine


lic

(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

Figure 1-2: How CPython works.

You might want to point


out that the Linux VM A Note on Virtual Machines
ot

students will use in this


course is an example of
The term "virtual machine" (VM) can be confusing in this context, because VM is usually used to
a system VM, as it describe a virtual duplicate of a complete computer system. These types of VMs are implemented
N

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:

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 5

• 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

Other Python IDEs


There are several IDEs for Python that are more powerful than IDLE. The following are some of Other Python IDEs
lic

the most popular examples. The activities in this


• PyCharm—A cross-platform IDE delivered in a free Community Edition and commercial course assume that
students will be using
Professional Edition. Includes an intelligent code editor with features such as debugging, testing,
up

PyCharm. You may


profiling, deployments, remote development, database tools, and a Python console. choose a different IDE if
• Jupyter Notebook—A cross-platform, open-source web application that enables you to create you wish, but be aware
and share documents that contain live code, equations, visualizations, and narrative text. This that some of the steps
may not key exactly as
D

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

and working with Jupyter notebooks.


• Komodo IDE—An advanced cross-platform, open-source editor developed by ActiveState®. It
provides a rich feature set including tracked changes, multiple selections, bookmarking, code
o

folding, smart language detection and code intelligence, debugging, split views, variable
highlighting, code snippets, macros, and user scripts.
D

• Wing IDE—A comprehensive cross-platform, proprietary Python IDE, including customizable


code editor, code intelligence, debugging, unit testing, and project management.
• PyDev—A cross-platform, free third-party plugin for Eclipse. Similar to PTVS, it adds Python
development capabilities to a feature-rich, general-purpose IDE (Eclipse).
• Spyder—A cross-platform, open-source development environment designed primarily for
scientific programming. It provides advanced features for editing and debugging Python code,
and exploration of datasets, and is designed to be customized and extended.
Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM
Lesson 1: Setting Up Python and Developing a Simple Application | Topic A
6 | Certified Entry-Level Python Programmer (PCEP™)

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 7

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

Before You Begin

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.

Present selection menu

no
or The InventoryEntry
Program Flow Chart
Make sure students
e
Prompt user

don't obsess over the


Book info yes yes
yes for book ID, valid, ID Show user User
ADD? name, doesn't entry/entries confirms? Book added/updated
exist?

details of this flow chat;


quantity, price
no
at
no

it's just meant to give


them a glimpse at the
Prompt user yes
yes Book info
UPDATE?
for book ID, valid, ID
name, exists?
quantity, price
no Return to overall flow of the
lic

no

program's logic.
selection
no no
menu

You may find it helpful to


yes yes yes
Prompt user Book ID Show user User
DELETE?
exists? confirms?
Book deleted
for book ID book title

no have students refer back


to the flow chart and
up

requirements as they try


End of loop

yes More no
Get next book Output book
Loop

SHOW? books All books shown


in inventory info
out the finished program
left?

yes

in this activity, so they


no

understand what the


D

End of loop

yes More no Calculate


program is actually
Get next book Add to total
Loop

SUM? books average price


Book stats shown
in inventory quantity/price left?

no yes
doing behind the
scenes.
ot

Figure 1-4: Flow chart of the InventoryEntry program.

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic A
8 | Certified Entry-Level Python Programmer (PCEP™)

• 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

a) Start the Oracle VM VirtualBox application.


b) In the Oracle VM VirtualBox Manager, from the list on the left, select PCEP and select
Machine→Start→Normal Start.
lic

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.

2. Examine the project files.


Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM
Lesson 1: Setting Up Python and Developing a Simple Application | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 9

a) At the command shell, type cd 094027Data and press Enter.

Caution: Linux commands are case sensitive.

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

Note: The backslashes indicate the start of a space.

d) Press Enter to change to that directory.


D

e) Type ls -l and press Enter.


There are three subdirectories: Errors, Finished, and Solutions.
f) Type cd Finished and press Enter.
ot

g) Type ls -l and press Enter.


N
o
D

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.

3. Run a completed Python script.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic A
10 | Certified Entry-Level Python Programmer (PCEP™)

a) Type python3 inventory_entry.py and press Enter.

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

You are then prompted to enter the price of the book.


f) Type 12.95 and press Enter.
You are then shown the book details you just entered and asked to confirm.
lic

This is a good g) Type y and press Enter.


opportunity to point
students back to the first
up

row of the program flow


chart.
D
ot
N
o

This was meant to just


give students a taste of
D

the finished program.


Time permitting, you You are given a message that the book was added and then sent back to the selection menu.
may want to show them
h) At the task-selection prompt, type 4 and press Enter.
more. However, they'll
get a chance to play You are shown the details of the book you just entered.
around in the finished
program at the end of 4. Exit the program and the command shell.
the course.
Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM
Lesson 1: Setting Up Python and Developing a Simple Application | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 11

a) At the prompt, type 6 and press Enter.


You are asked to confirm that you want to exit.
b) Type y and press Enter.
You are returned to the Linux command shell.
c) Type exit and press Enter.
d) In the dialog box, select Yes.
The Linux command shell closes.

e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic A
12 | Certified Entry-Level Python Programmer (PCEP™)

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 13

e) Select the New Directory button.

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

3. Create a Python file.


a) Verify that InventoryEntry is listed in the Project pane on the left side of the PyCharm window.
up
D
ot
N
o

b) Right-click InventoryEntry and select New→Python File.


c) In the New Python file dialog box, in the Name text box, type inventory_entry and press Enter.
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic A
14 | Certified Entry-Level Python Programmer (PCEP™)

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 15

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

Figure 1-5: Python running in interactive mode.

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,

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic B
16 | Certified Entry-Level Python Programmer (PCEP™)

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

Figure 1-6: The interactive help utility.


up

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

indentation in the following code:


if True:
print("True")
else:
print("False")

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 17

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.

Lexis and Semantics


Other linguistic terms can also apply to a programming language like Python. Python's lexis, or
lexical structure, defines all of the tokens of the language that can be interpreted. A token is the
atomic element of the language and can be everything from digits, to symbols, to whitespace, and so
on. Python translates written code into tokens during interpretation.

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

Python knows to consider count an integer type of variable.


lic

Note: When a variable is created and assigned a value, it is said to be initialized.


up

PEP 8 and Naming Conventions


The Python Software Foundation maintains a list of various Python Enhancement Proposals or PEP 8 and Naming
PEPs. A PEP is a public document that either describes some element of Python's design, or Conventions
D

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

improve readability by separating words with an underscore.


• Correct: my_variable = 1
• Incorrect: MyVariable = 1
It's good practice to give your variables meaningful names in order to avoid ambiguity. You also
cannot begin variable names with a number. Python will produce a syntax error.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic B
18 | Certified Entry-Level Python Programmer (PCEP™)

Note: For the full text of PEP 8, navigate to https://www.python.org/dev/peps/


pep-0008/.

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

assert from raise


break global return
up

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

the operator, while 2 and 4 are the operands.


Inform students that they
Operators can be grouped in several different ways. One such group is arithmetic operators.
will learn about more
operator types later, as Operator Definition Example
well as the difference
between integers and
+ Adds operands together. 2 + 4 will return 6.
floats.
Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM
Lesson 1: Setting Up Python and Developing a Simple Application | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 19

Operator Definition Example


- Subtracts the operand to the right 4 - 2 will return 2.
from the operand to the left.
* Multiplies operands together. 2 * 4 will return 8.
/ Divides the left operand by the right 10 / 4 will return 2.5.
operand and returns a float.
Divides the left operand by the right 10 // 4 will return 2.

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

around with expressions.


can be evaluated one of two ways: This may help them to
better understand the
• Evaluated left to right, the answer is 48.
lic

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

Note: A comprehensive summary of operator precedence is provided at https://


docs.python.org/3/reference/expressions.html#operator-summary.

Unary vs. Binary Operators


The operations shown thus far have used operators in a binary mode. In other words, each Unary vs. Binary
operator connects two operands together. This is the most common way to use operators. However, Operators
Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM
Lesson 1: Setting Up Python and Developing a Simple Application | Topic B
20 | Certified Entry-Level Python Programmer (PCEP™)

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.

Quotes and String Literals

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

example, a = "Won't" is acceptable because it is enclosed by consistent double quotation marks.


You can also use triple quotes of either variety (''' or """) to enclose multiple lines of a string
literal. For example:
lic

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

a = "This is a "string literal.""


This will cause a syntax error because Python thinks the string literal has ended at the second
N

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

a = "This is a \"string literal.\""


D

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 21

Escape Code Adds A

\\ 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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic B
22 | Certified Entry-Level Python Programmer (PCEP™)

ACTIVITY 1-3
Writing Python Statements

Before You Begin

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

Interactive shell Special Variables list


D

• 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.

2. Configure the layout of the Python console.


N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 23

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.

3. Define variables and assign values to them.


a) At the command prompt, type a = 5 and press Enter.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic B
24 | Certified Entry-Level Python Programmer (PCEP™)

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

The current values of a and b are shown.


up

4. Perform arithmetic operations on your variables.


a) At the command prompt, enter a + b
b) Verify that Python returns a value of 15 at the console.
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 25

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic B
26 | Certified Entry-Level Python Programmer (PCEP™)

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.

Script Properties Script Contents


or
e
at
lic
up
D

Figure 1-7: The file properties of a Python script alongside the contents of that script.
ot

Additional File Extensions


N

Python-related files may also come in the following extensions:


• .pyc (compiled source code)
• .pyo (optimized compiled source code)
o

• .pyd (dynamic module)


D

• .pyw (GUI-based source code)

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic C
Certified Entry-Level Python Programmer (PCEP™) | 27

(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


D

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic C
28 | Certified Entry-Level Python Programmer (PCEP™)

Figure 1-8: The print() function in 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

print(a, b, sep=", ", end="!")


The result is: Hello, world!
up

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


ot

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

name = input("What is your name?\n")


This code prints the question What is your name? and then opens up a command prompt for the
user to type in. Whatever the user enters is passed into the variable name. By default, name will be a
o

string. The following is what it looks like running from a script, with the user's name printed back to
D

them.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic C
Certified Entry-Level Python Programmer (PCEP™) | 29

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic C
30 | Certified Entry-Level Python Programmer (PCEP™)

ACTIVITY 1-4
Creating a Python Application

Before You Begin

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

2. Write code to take a user's input, then print it back to them.


a) Press Ctrl+End to move to the end of the code, then press Enter until the insertion point is on line 4.
Students will likely notice b) Starting on line 4, add the following code.
D

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

students to ignore such


IDE features. If you or
your students want to
o

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

use it effectively. The


important thing is for
their code to look like it 3. Add a print statement with a comment to explain the statement's purpose.
does in the screenshots. a) Ensure your insertion point is at the end of line 4.
b) Press Enter twice to advance to line 6.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic C
Certified Entry-Level Python Programmer (PCEP™) | 31

c) Type the two lines shown.

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic C
32 | Certified Entry-Level Python Programmer (PCEP™)

d) Type 1234 and then press Enter.

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.

5. Create and run multiple, consecutive input statements.

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic C
Certified Entry-Level Python Programmer (PCEP™) | 33

b) In the Run pane, select the Rerun 'inventory_entry' button.

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

c) At the third prompt, enter 100


d) At the fourth prompt, enter 12.95
e) Verify that the program finishes with an exit code of 0.
up

f) In the Run pane, close the inventory_entry tab.

Close tab
D
ot
N
o
D

g) Close the inventory_entry.py editor tab.


The editor for that file is closed, but the InventoryEntry project remains open.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic C
34 | Certified Entry-Level Python Programmer (PCEP™)

7. Examine the directory that contains the Python source-code file.


a) In the Project pane, right-click inventory_entry.py and select Open In→PCManFM-Qt File Manager.
This command launches the file browser included in this Linux distribution to the project folder that
you created.
The point of these b) From the file browser's menu, select View, then check the Show Hidden check box.
remaining steps is to c) Examine the contents of the project folder.
demonstrate that Python
code can exist outside of
PyCharm or any IDE

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

created a folder named .idea, which contains the project settings.

Note: Normally, you would not need to directly edit the files in the .idea folder,
which are maintained automatically by the IDE.
lic

d) In the file browser, right-click inventory_entry.py and select Properties.


up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic C
Certified Entry-Level Python Programmer (PCEP™) | 35

e) Examine the File Properties dialog box.

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

a) From the file-browser menu, select Tools→Open Terminal.


This runs the default terminal in this Linux distribution from the current directory location.
lic

b) Examine the current directory in the terminal.


up
D
ot

c) Enter the ls -a command.


The inventory_entry.py file is shown in the list, as is the hidden .idea folder. If you were working
N

outside of an editor like PyCharm, you might view the Python project files from the terminal, like this.

9. Run the program directly from the terminal.


o

a) Enter the python3 inventory_entry.py command.


D

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic C
36 | Certified Entry-Level Python Programmer (PCEP™)

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic C
Certified Entry-Level Python Programmer (PCEP™) | 37

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

need to change the code or else it will return an error.


up
D
ot

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?")

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic D
38 | Certified Entry-Level Python Programmer (PCEP™)

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.

Guidelines for Preventing Errors

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.

Prevent Logic Errors


e
To prevent errors in logic:
• Use comments to adequately explain what every block of code should do.
at

• Try to envision how a block of code could affect the whole program if it fails to execute as
intended.
lic

• Watch for loops that never initiate or terminate.


• Thoroughly test larger, more complex programs before releasing them to a wider audience.
• During testing, attempt to "break" your code; that is, test how the code handles unconventional
up

or uncommon input.
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic D
Certified Entry-Level Python Programmer (PCEP™) | 39

ACTIVITY 1-5
Preventing Errors

Data File

e
/home/student/094027Data/Setting Up Python and Developing a Simple Application/Errors/

ut
inventory_entry.py

Before You Begin

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) Verify that a syntax error is reported.


ot
N
o
D

c) In the Run pane, close the inventory_entry tab.

3. Debug the program.


a) Verify that PyCharm has detected several syntax errors in the code, denoted by red underlining.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic D
40 | Certified Entry-Level Python Programmer (PCEP™)

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

Two possible errors have been identified in line 9.


D

4. Correct the missing closing quote.


a) Place your insertion point at the end of line 9, before the last closing parenthesis.
b) Type a double-quote character.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic D
Certified Entry-Level Python Programmer (PCEP™) | 41

c) Verify that line 9 is no longer marked as an error.

Double quote added

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

b) Fix the error by removing the letters l and n from println.


c) On line 15, point at the underlined word bookquant.
up
D
ot
N

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

name isn't exact, Python won't be able to execute it.


D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic D
42 | Certified Entry-Level Python Programmer (PCEP™)

d) Add the underscore to fix the print statement on line 15.

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

have fixed this error 8. What kind of error is this? Why?


before proceeding.
A: This is a logic error. Python is able to interpret and execute the code correctly, but the code
doesn't do what the programmer intended.
up

9. Correct the error.


a) In inventory_entry.py source code, correct the logic error.
D

b) Rerun the program and test that it works as intended.


ot
N
o
D

10.Clean up the workspace.


a) Select Main Menu→Close Project.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic D
Certified Entry-Level Python Programmer (PCEP™) | 43

b) Close the Welcome to PyCharm window.


If you plan to proceed
directly into the next
lesson, you may opt to
have students just leave
PyCharm running.

e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application | Topic D
44 | Certified Entry-Level Python Programmer (PCEP™)

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 1: Setting Up Python and Developing a Simple Application |
2 Processing Simple Data
Types

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

In this lesson, you will:


• Process integers and strings.
lic

• Process decimals, floats, and mixed number types.


up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


46 | Certified Entry-Level Python Programmer (PCEP™)

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 2: Processing Simple Data Types | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 47

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

print("The number is " + str(num)) # Succeeds.


The first print statement fails because a string type cannot be added to a number type.
up

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

The number is 635502


ot

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

types in the next lesson.


b = "World"
D

Operator Description Example and Result

+ Combines the left operand string with the right a + b


operand string. This process is called concatenation. "HelloWorld"
* Concatenates a copy of the string itself the number of b * 3
times defined by the other operand. "WorldWorldWorld"

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 2: Processing Simple Data Types | Topic A
48 | Certified Entry-Level Python Programmer (PCEP™)

Operator Description Example and Result


[] Returns the character at the given position. The a[0]
position is called the index and the technique is called "H"
indexing. Indices start at 0.
[:] Returns the group of characters that span the given b[0:3]
indices. The group of characters is called a slice and "Wor"
the technique is called slicing. Note that the end
index is exclusive; i.e., it is not included in the result.

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

>>> people = "There are {} people.".format(count)


>>> print(people)
There are 2 people.
up

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

people = "There are {1} people named {0}.".format(count, name)


Which outputs: There are Terry people named 2. The number you supply in the replacement
field corresponds to the order of the variables in format(), starting with 0.
Note: String interpolation is an alternative to concatenation and is especially useful since you'd
otherwise need to convert any integer variables into strings before you can concatenate them.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 2: Processing Simple Data Types | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 49

String Interpolation: f-strings


An alternative method of interpolation involves using f-strings. Like using the format() function, String Interpolation: f-
you add {} placeholders in the string literal wherever you want to include variables. The difference strings
is, you place the name of the variable in those placeholder brackets. You then just need to type the
letter f before the string literal, which signals to Python that it should interpolate the provided
values.
Here's an example of using an f-string:

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

hexadecimal numeral systems.


Python has functions for converting integers into these three numeral systems, as shown in the
following table.
D

Numeral System Description Example and Result

Binary • Base 2 bin(30)


ot

• Digits: 0 and 1 "0b10100"

Octal • Base 8 oct(30)


N

• Digits: 0 through 7 "0o36"

Hexadecimal • Base 16 hex(30)


o

• Digits: 0 through 9 and A "0x1e"


through F
D

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 2: Processing Simple Data Types | Topic A
50 | Certified Entry-Level Python Programmer (PCEP™)

Applications of Binary, Octal, and Hexadecimal


There are several reasons why you might need to work with alternative numeral systems, most of
which have to do with specialized applications. For example, some programmers need to access data
and memory at a low level, where it is more commonly represented in a format like hexadecimal.
Compiled executables and other encoded files (like images and other media) are often called binaries
or binary data because they represent data as bits instead of as human-readable text. To modify these
files programmatically, the programmer may need to work with the data as represented using a non-
decimal system.

e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 2: Processing Simple Data Types | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 51

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.

InventoryEntry project folder.


d) Select OK.
e) Configure PyCharm to trust all projects in this folder.
or
c) Beneath the 094027Data folder, expand Processing Simple Data Types, and select the
e
f) In the Project pane, double-click inventory_entry.py to show the source code in the editor.
at

2. Calculate total book titles and quantity.


a) Place the insertion point on line 20 and press Enter to prepare a new line.
lic

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

under the heading


"Calculate Total Book
Titles and Quantity".
D
ot

• Line 21 creates a variable named num_books_query and assigns it to the input that the user
N

enters in response to the prompt.


• Line 22 converts the user's string input to an integer so math operations can be performed on it.
• Line 23 multiplies the number of books the user input by the quantity they entered earlier, with
o

book_quant being converted to an integer in the process.


To avoid typing, you can
D

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".

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 2: Processing Simple Data Types | Topic A
52 | Certified Entry-Level Python Programmer (PCEP™)

a) Write the code as shown to print the 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

Right-click the source-code pane and select Run 'inventory_entry'.


e
b) In the Run pane, enter any value at the first prompt and second prompt.
c) When you're prompted to enter the quantity, enter 100
at

d) Enter any value for the price prompt.


e) When prompted for the number of books, enter 5
lic

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

g) From the Run pane, close inventory_entry.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 2: Processing Simple Data Types | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 53

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

my_float = 123.456 division (//) involving


integers always returns
D

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 2: Processing Simple Data Types | Topic B
54 | Certified Entry-Level Python Programmer (PCEP™)

Numbers can also be converted to a float type by using float():


>>> my_integer = 5
>>> float(my_integer)
5.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

String Formats for Float Precision


String Formats for Float When you perform arithmetic on floats or mixed numbers, you'll often get a result with many digits
Precision after the decimal point. When it comes to outputting this in a string, too many numbers after the
D

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

The way to do this should be familiar, as it involves string interpolation:


>>> miles = 118.23
N

>>> hours_elapsed = 5
>>> mph = miles / hours_elapsed
>>> print(f"The air-speed velocity is {mph:.2f} miles per hour.")
o

The air-speed velocity is 23.65 miles per hour.


D

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 2: Processing Simple Data Types | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 55

Additional Formatting Options


There are many other ways to format strings besides achieving float precision. For example, you can
pad parts of a string with a certain number of spaces, as well as align that part of the string left or
right within the given space.
>>> print(f"MPH: {mph:>20}")
MPH: 23.65
The > operator indicates that the field will be right aligned, and 20 is the minimum number of
characters it should occupy (padded with spaces to fill out the remainder).

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 2: Processing Simple Data Types | Topic B
56 | Certified Entry-Level Python Programmer (PCEP™)

ACTIVITY 2-2
Processing Mixed Number Types

Before You Begin

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

2. Run the program and provide input.


a) Run the program and input any values for the first two questions.
ot

b) For the book quantity, enter 100


c) For the book price, enter 12
N

d) For the total book titles, enter 5


o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 2: Processing Simple Data Types | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 57

e) Verify that you receive the following output:

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.

Run your program with a more precise input value.


or
A: The result would be 120.0. In an operation with a mix of integers and floats, the result always
e
a) Rerun the inventory_entry program.
at

b) For the quantity, enter 100


c) For the book price, enter 12.951
d) For the total book titles, enter 5
lic

e) Verify that the output for the average price is $12.950999999999999.


Obviously, this level of precision does not make sense for a monetary value.
up

Note: In a production environment, you should use a decimal type instead of a


float type to hold prices and other monetary values. Floats are being used in
this program for convenience.
D

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

b) Rerun the program, and use 12.951 as the price again.


D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 2: Processing Simple Data Types | Topic B
58 | Certified Entry-Level Python Programmer (PCEP™)

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 2: Processing Simple Data Types | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 59

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 2: Processing Simple Data Types |
e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


3 Processing Data
Structures

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

In this lesson, you will:


• Process ordered data structures.
lic

• Process unordered data structures.


up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


62 | Certified Entry-Level Python Programmer (PCEP™)

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

The following data structures are mutable:


• Lists
o

• Dictionaries
D

• Sets
The following data structures are immutable:
• Ranges
• Tuples

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 63

Note: Strings are also immutable.

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 = [1939, 1943, 1943, "John", "Eric", "Michael"]


lic

List Indexing and Slicing


Lists have indices. Each element in a list, from left to right, is indexed, starting at 0. In the preceding List Indexing and Slicing
up

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

Expression Result Description

["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"]

"A" in ["A", "B", "C"] True Returns True if value exists


in the list; False if it
N

doesn't.
"B" not in ["A", "B", "C"] False Returns True if value does
o

not exist in the list; False if


it does.
D

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].

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 65

Approach Example Result Description

.append() my_list.append(5) [20, 10, 30, 10, 5] Adds values you


specify to the end
of a list.
.insert() my_list.insert(0, 5) [5, 20, 10, 30, 10] At an index of a list
you specify, inserts
a value you specify.

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

.reverse() my_list.reverse() [10, 30, 10, 20] Reverses the order


of values in a list.
lic

.clear() my_list.clear() [] Removes all items


from a list.
up

del del my_list[2] [20, 10, 10] Deletes an item


from a list at the
specified index.
Values to the right
D

of the deleted item


are shifted to the
left.
ot

len() len(my_list) 4 Retrieves the


number of items in
N

a list.
max() max(my_list) 30 Identifies the
o

highest value in a
list. Returns an
D

error if the list


contains unsortable
data, like another
list or a mix of
strings and
numbers.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic A
66 | Certified Entry-Level Python Programmer (PCEP™)

Approach Example Result Description

min() min(my_list) 10 Identifies the


lowest value in a
list. Returns an
error if the list
contains unsortable
data, like another
list or a mix of

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

In this case, the original my_list object changed.


lic

List Copying
List Copying (2 Slides) Observe the following block of code:
up

>>> list_1 = [1, 2, 3]


>>> list_2 = list_1
>>> list_2
D

[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

Both list_2 and list_1 were updated. Why is this?


D

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:

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 67

>>> list_1 = [1, 2, 3]


>>> list_2 = list_1[:]
>>> list_2.append(4)
>>> list_2
[1, 2, 3, 4]
>>> list_1
[1, 2, 3]
As you can see, list_1 was not updated; only list_2 was. This is called a shallow copy. It points
to a different set of values in memory, meaning the two lists are not linked.

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

my_range = range(0, 50, 5)


This creates a range that starts at 0, increments by 5, and ends at 50. Therefore, the range contains
o

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic A
68 | Certified Entry-Level Python Programmer (PCEP™)

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

("A", "B", "C") +


("D", "E", "F")
Result
or
("A","B","C","D","E","F")
Description

Concatenates tuples.
e
("A", "B", "C") * ("A", "B", "C", "A", "B", "C", Repeats tuple values.
at

3 "A", "B", "C")

"A" in ("A", "B", True Returns True if value exists in


lic

"C") the tuple; False if it doesn't.


"B" not in ("A", False Returns True if value does not
"B", "C") exist in the tuple; False if it
up

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).

Approach Example Result Description


N

.index() my_tuple.index(30) 2 Returns the first index in a tuple


that matches the value you
o

specify.
D

.count() my_tuple.count(10) 2 Returns the number of times a


value you specify appears in a
tuple.
len() len(my_tuple) 4 Retrieves the number of items
in a tuple.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 69

Approach Example Result Description

max() max(my_tuple) 30 Identifies the highest value in a


tuple. Returns an error if the
tuple contains unsortable data,
like another tuple or a mix of
strings and numbers.
min() min(my_tuple) 10 Identifies the lowest value in a

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.

Choose Ordered Data Structures


When choosing ordered data structures:
or
e
• Choose lists for collections of data that must follow a certain order and are allowed to be
at

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic A
70 | Certified Entry-Level Python Programmer (PCEP™)

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

2. Write code to add the book details to a list.


a) Place the insertion point at the end of line 19 and press Enter twice to insert new lines.
To avoid typing, you can b) Write the code as shown.
up

copy this code from the


L3.txt snippets file,
under the heading
"Create and Print Book 1
D

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

3. Run the program and test some input.


a) Run the program.
D

b) Enter whatever values you want at each prompt.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 71

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

5. Run the program and verify the changes in output.


a) Run the program.
lic

b) Enter whatever values you want at each prompt.


c) Verify that the printed information is neater and no longer appears as a single list.
up
D
ot
N
o

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic A
72 | Certified Entry-Level Python Programmer (PCEP™)

d) On lines 41 and 42, change all instances of book_1 to book_2

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

8. Test the new list-processing code.


a) Rerun the program.
b) Enter the first book's information as desired.
up

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

e) At the prompt asking for the genre, enter fiction

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic A
Certified Entry-Level Python Programmer (PCEP™) | 73

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic A
74 | Certified Entry-Level Python Programmer (PCEP™)

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

accessing a key's value is similar to accessing indices in a list:


>>> dict["Terry"]
5554321
up

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

and is the preferred practice according to Python's style guide.


N

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

dict = {"John": 5551234, "Terry": 5554321, "Eric": 5551234}


To add Graham and his phone number to the dictionary, you'd type the following:
dict["Graham"] = 5556789
To change Terry's phone number to 5556789, you'd type:
dict["Terry"] = 5556789

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 75

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.

Approach Example Result Description

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.

Returns the values in a


e
5556789, 5556789]) dictionary.
at

in "John" in False Returns True if specified value is


dict a key in the dictionary, False if
not.
lic

not in "Michael" True Returns True if specified value is


not in dict not a key in the dictionary,
up

False if it is.

.clear() dict.clear() {} Removes all entries from a


dictionary.
D

Merge and Update


The merge operator ( | ) enables you to easily combine dictionaries.
ot

tv = {'Flying Circus': 1969, 'Live at Aspen': 1998}


film = {'Holy Grail': 1975, 'Life of Brian': 1979}
N

projects = tv | film
print(projects)
The output from this code would be {'Flying Circus': 1969, 'Live at Aspen': 1998,
o

'Holy Grail': 1975, 'Life of Brian': 1979}


D

The update operator ( |= ) updates the original dictionary.


projects = {'Flying Circus': 1969, 'Live at Aspen': 1998}
projects |= {'Holy Grail': 1975, 'Life of Brian': 1979}
print(projects)
The output from this code is the same as before.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic B
76 | Certified Entry-Level Python Programmer (PCEP™)

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

Approach Example Result Description

in "X" in my_set True Returns True if


lic

specified value is in
the set, False if not.
Returns True if
up

not in "A" not in my_set2 False


specified value is not
in the set, False if it
is.
D

.add() my_set.add(1) {"X", "Y", "Z", 1} Adds the specified


value to the set.
ot

.remove() my_set.remove("X") {"Y", "Z"} Removes the specified


value from the set.
N

.clear() my_set.clear() set() Removes all values


from the set.
.difference() my_set.difference(m {"Z"} Compares one set
o

y_set2) with another and


returns the value(s)
D

that are in the first set,


but not also in the
second set.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 77

Approach Example Result Description

.intersection() my_set.intersectio {"X", "Y"} Compares one set


n(my_set2) with another and
returns the value(s)
that appear in both
sets.
.union() my_set.union(my_set {"X", "Y", "Z", "A"} Combines all of the

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

• Choose sets to compare unique collections of data to each other.


e
at
lic
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic B
78 | Certified Entry-Level Python Programmer (PCEP™)

ACTIVITY 3-2
Processing Unordered Data Structures

Before You Begin

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

L3.txt snippets file,


under the heading
"Create the Inventory
ot

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 79

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

3. Test the new book-inventory dictionary.


a) Rerun the program.
b) Enter any values you want for the first book title.
up

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

list of book details as its values.


ot
N
o
D

To avoid typing, you can


4. Delete a book title from the dictionary. copy this code from the
L3.txt snippets file,
under the heading
"Delete a Key from the
Dictionary".

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic B
80 | Certified Entry-Level Python Programmer (PCEP™)

a) Starting on line 45, write the code as shown.

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

5. Retrieve specific items from the inventory dictionary.


a) Place the insertion point at the end of line 47, then press Enter twice to insert new lines.
up

To avoid typing, you can


copy this code from the
L3.txt snippets file,
D

under the heading


"Retrieve Book Details
from the Dictionary".
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 81

b) Starting on line 49, write the code as shown.

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

g) When prompted for the ID of the book to show, enter F124


h) Verify that each of the book's details are shown on separate lines.
lic
up
D
ot
N

6. Close the project and PyCharm.


If you plan to proceed
directly into the next
o

lesson, you may opt to


have students just leave
D

PyCharm running.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic B
82 | Certified Entry-Level Python Programmer (PCEP™)

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

room numbers don't need to change at any point.


Which data structure would you use to assign numbers to each room, and
ot

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 83

4. You're creating a program to check two different directories on a user's


computer and determine which file names are in Directory A and also
Directory B. That way, the program can identify and remove duplicate file
names across the directories. The order of the file names doesn't matter, and
each file name is unique within its directory.
Which data structure would you use to store each directory's file names, and
why?

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures | Topic B
84 | Certified Entry-Level Python Programmer (PCEP™)

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 3: Processing Data Structures |
4 Writing Conditional
Statements and Loops

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

In this lesson, you will:


lic

• Write conditional statements.


• Write loops.
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


86 | Certified Entry-Level Python Programmer (PCEP™)

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.

or Example: Did the user select


"Yes" in response to a prompt
from the program?
e
Condition
False
at

True
Conditional statement
lic

Conditional code
up
D

Subsequent code
ot
N

Figure 4-1: The basic flow of a conditional statement.

The if Statement
o

The if Statement Python uses the if statement as its conditional statement.


D

The syntax for if statements is as follows:


if condition:
statement
If the condition is met, execute the statement below. That is the essential process of an if
statement. Note that any code to be executed as part of the if statement must be indented. Also

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™) | 87

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

The elif Statement


D

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic A
88 | Certified Entry-Level Python Programmer (PCEP™)

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

my_str = "Hello, world!"


lic

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

values in Python, some of which are described in the following table.


Consider pointing out
that the = operator is not Operator Definition Example and Result
o

the same as the ==


operator. The single == Checks if both operands have an equal value. 2 == 4
D

equals sign assigns a False


value to a variable,
whereas the double
!= Checks if operands do not have an equal value. 2 != 4
equals sign is used for True
comparing values. > Checks if left operand is greater in value than 2 > 4
right operand. False

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™) | 89

Operator Definition Example and Result


< Checks if left operand is less in value than right 2 < 4
operand. True

>= Checks if left operand is greater in value or equal 2 >= 2


in value to right operand. True

<= Checks if left operand is less in value or equal in 4 <= 2


value to right operand. False

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

and Checks if both operands evaluate to True. 2 > 3 and 4 > 3

or
True.
or True
False

Checks if at least one of the operands evaluates to 2 > 3 or 4 > 3


e
not Negates an operand. not(3) == 4
True
at

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

which are described in the following table. students of the binary


numeral system
Operator Definition Example/Result mentioned earlier.
D

& Sets each bit to 1 if both bits are 1. Also called a 5 & 3
bitwise AND. 1

Sets each bit to 1 if at least one of the bits is 1.


ot

| 5 | 3
Also called a bitwise OR. 7

^ Sets each bit to 1 if only one of the bits is 1. Also 5 ^ 3


N

called a bitwise XOR (exclusive OR). 6

~ Flips all bits, turning 0 into 1 and vice versa. Also ~5


o

called a bitwise NOT. -6


D

<< 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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic A
90 | Certified Entry-Level Python Programmer (PCEP™)

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

amount of code you need type to do both tasks.


The following table gives the long way of doing the assignment, as well as the shortcut way with an
ot

assignment operator.

Operator Example (Shortcut) Equivalent


N

+= 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

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™) | 91

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.

Guidelines for Writing Conditional Statements


up

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

Write Conditional Statements


When writing conditional statements:
N

• Use an if statement to test for a simple condition.


• Add an else statement at the end of a conditional to account for all other conditions.
• Use successive elif statements to test multiple conditions and execute different code for each.
o

• 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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic A
92 | Certified Entry-Level Python Programmer (PCEP™)

• 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

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™) | 93

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.

Examine the refactored code.


ot

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic A
94 | Certified Entry-Level Python Programmer (PCEP™)

b) Examine lines 9 through 21.

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.

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™) | 95

e) Type the two lines as shown.

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

g) Press Tab to indent these lines under the if statement.


D
ot
N
o
D

Now, all of the code to add a book to the inventory will only run if the condition is met.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic A
96 | Certified Entry-Level Python Programmer (PCEP™)

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

elif task_choice == "3" or task_choice == "delete":


to make sure they are
able to make these print("Selection: DELETE\n")
changes.
lic

# 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

came before it.


D

6. Include a final condition in case the user makes an invalid selection.

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™) | 97

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

a) Run the program.


b) Verify that you are presented with a selection menu and are prompted to enter a task.
lic
up
D
ot
N
o
D

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic A
98 | Certified Entry-Level Python Programmer (PCEP™)

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

indented under that conditional.


• Line 29 checks if the book ID the user entered is in the book_inv dictionary. If it is, the code
under the conditional executes. If it's not, the interpreter moves to the next statement that is not
N

indented under that conditional.


• Line 29 uses a regular if statement instead of an elif because each condition is independent.
Both of them will be evaluated, even if the first is True.
o

• 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

9. Test the nested conditional logic.


a) Rerun the program and select the "ADD" option.

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

c) Verify that you are told the book ID must be 4 characters.

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.

Note: Again, you'll write code later to handle this better.

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic A
100 | Certified Entry-Level Python Programmer (PCEP™)

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

Resume at code following


the loop
up

Figure 4-2: The basic flow of a loop.

In Python, there are two main kinds of loops: while and for loops.
D

The while Loop


ot

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

The syntax for a while loop is:


D

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:

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 101

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.

The for Loop

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 item in iterable:


statement
As you can see, the basic structure (indentation, colon, etc.) is familiar. For a practical example,
lic

observe the following:


my_list = [1, 2, 3, "Four", "Five"]
up

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

on until it gets to the end of the list. Here is the output:


1
N

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic B
102 | Certified Entry-Level Python Programmer (PCEP™)

The else Branch in Loops


The else branch can also be used in loops. In a while loop, an else branch will execute once the
condition becomes False:
count = 1
while count <= 5:
print(count)
count += 1
else:

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

This is loop number 2.


This is loop number 3.
lic

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

To iterate through the values only, use the .values() method:


for v in dict.values():
print(v)
o

The output is:


D

5551234
5556789
5556789
And, finally, to iterate through both keys and values, use two iterators separated by a comma and
then the .items() approach:

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 103

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.

Ultimately, the output is as follows:


Eric's number is probably fake.
or
e
Graham's number is probably fake.
at

Terry's number is probably fake.


There are many more ways to use loops; these were just some examples.
lic

Loop Control
Within loops, there are statements that give you greater control over how the code is executed. The Loop Control
up

control statements in Python are break, continue, and pass.


The break statement terminates the current loop and executes the very next statement. This is
useful if you need to end a loop's execution due to some change in condition. For example:
D

my_list = [1, 2, 3, 4, 5.2, 6]


for i in my_list:
if i % 1 != 0:
ot

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:

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic B
104 | Certified Entry-Level Python Programmer (PCEP™)

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]

what each component does: or


All of these components you've seen before, just in different formats. Here's more explanation for

• 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

• iterable is any iterable object, like a list or range.


• condition is any evaluable expression, like what you'd use in an if statement.
lic

All of this is wrapped in opening and closing brackets ( [] ) so that the end result is a list.

List Comprehension: Example


up

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

Here's what this code is doing:


1. i * 2 is doubling each item.
N

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 105

Guidelines for Writing Loops


Use the following guidelines to help you write loops in your Python programs.
Guidelines for Writing
Write Loops Loops
When writing loops:
• Use while loops to execute code based on a condition that is either True or False.
• Use while loops primarily for processing user input.

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic B
106 | Certified Entry-Level Python Programmer (PCEP™)

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 107

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic B
108 | Certified Entry-Level Python Programmer (PCEP™)

3. Add control statements where the loops need to do something different.


a) Position the insertion point at the end of line 31 and press Enter.
b) On a new line 32, type continue

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

while loop and move on.


• This is what the break statement does.
• In this case, because there is no more code in the if branch, the interpreter has nothing left to
up

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 109

4. Test the while loops.


a) Run the program.
b) Select the "ADD" task.
c) For the book ID, enter F123
d) Verify that the program tells you the book ID already exists and sends you back to the selection
menu.

e
ut
ib
tr
is
D
or
e
e) Select the "ADD" task again.
at

f) For the book ID, enter F12


g) Verify that the program tells you the book ID must be 4 characters, but that you are prompted to
enter the book ID again.
lic
up
D
ot
N

h) This time, for the book ID, enter F124


i) Verify that you are allowed to continue entering book details.
o

j) Continue entering the details as desired.


k) When you're done, verify that the program printed the inventory dictionary and then sent you back to
D

the selection menu.

5. Stop the program.


a) From the Run console, close the inventory_entry tab.
b) In the Process 'inventory_entry' Is Running dialog box, select Terminate.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic B
110 | Certified Entry-Level Python Programmer (PCEP™)

ACTIVITY 4-3
Writing for Loops

Before You Begin

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

copy this code from the


L4.txt snippets file,
under the heading
N

"Totals Loop".
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 111

b) Starting on a new line 78, write the code as shown.

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

d) On line 86, delete the # mark to uncomment the line.

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

inventory by the total number of book titles.


e) Highlight line 87 and press Delete.
D

To avoid typing, you can


copy this code from the
L4.txt snippets file,
under the heading "Print
Summary Stats".

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic B
112 | Certified Entry-Level Python Programmer (PCEP™)

f) Starting on a new line 87, write the code as shown.

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

To avoid typing, you can


copy this code from the
L4.txt snippets file,
under the heading
D

"Report Loop".
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 113

b) Starting on a new line 69, write the code as shown.

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops | Topic B
114 | Certified Entry-Level Python Programmer (PCEP™)

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

Time permitting, have


students continue to add
o

new book titles to the


inventory so they can
D

see how the "SHOW"


and "SUMMARIZE"
outputs change. h) When you're done, stop the running program.
If you plan to proceed
directly into the next 4. Close the project and PyCharm.
lesson, you may opt to
have students just leave
PyCharm running.
Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM
Lesson 4: Writing Conditional Statements and Loops | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 115

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 4: Writing Conditional Statements and Loops |
e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


5 Using Functions and
Handling Exceptions

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

In this lesson, you will:


lic

• Define and call functions.


• Perform basic exception handling.
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


118 | Certified Entry-Level Python Programmer (PCEP™)

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

function and supplies three arguments:


questions("Lancelot", "to seek the Holy Grail", "blue")
This will print to the console:
ot

Your name is Lancelot.


Your quest is to seek the Holy Grail.
N

Your favorite color is blue.


The preceding example uses all strings, but you can pass any data type as an argument.
o

Parameters vs. Arguments


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.

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™) | 119

Parameters

def questions(name, quest, favorite_color):


print(f"Your name is {name}.")
Defining print(f"Your quest is {quest}.")
print(f"Your favorite color is {favorite_color}.")

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

has defined, or if there are a lot of parameters to deal with.


lic

Argument-Passing Approaches: Keyword


Passing arguments by keyword means specifying which argument is assigned to which parameter. Argument-Passing
You do this by naming the parameter and assigning it to the desired value or variable. For example: Approaches: Keyword
up

questions(name = "Lancelot", Ensure students


quest = "to seek the Holy Grail", understand that making
this function call multi-
favorite_color = "blue")
line is not related to
D

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

call is the same: wrapping. You may also


want to explain that
questions(favorite_color = "blue", breaking up arguments
N

name = "Lancelot", by line is acceptable in


quest = "to seek the Holy Grail") Python, as long as the
line ends in a comma or
Of course, the downside is that the code is more verbose. You also need to know the exact names
o

the closing parenthesis.


of the parameters.
D

Argument-Passing Approaches: Mixed


Lastly, you can perform mixed-argument passing by using a combination of positions and keywords. Argument-Passing
For example: Approaches: Mixed

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic A
120 | Certified Entry-Level Python Programmer (PCEP™)

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


D

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

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™) | 121

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

the prior subproblem as in a sequence. This is a good case for recursion.

Recursion Example
ot

Here's how this would look in a function: Recursion Example


N

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic A
122 | Certified Entry-Level Python Programmer (PCEP™)

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

6 full_title = title + " " + name


7 print(full_title)
8
9 get_title("Eddie", "Sir") "Sir Eddie"
10
up

11 print(full_title) NameError: name "full_title" is not defined

Figure 5-2: Scope of variable created within a function.


D

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

Scope: Global Variables


Scope: Global Variables This following figure is nearly identical to the prior one, except that a global variable named
full_title is created on line 2 (as highlighted in the figure). In this case, the print statement inside
the function still sees the local variable named full_title. The function "sees" the local variable

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™) | 123

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".

1 # Global variable created here.


2 full_title = "global created"
3
4 def get_title(name, title):
5 # Variable created inside the function.

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

2 full_title = "global created"


3
4 def get_title(name, title):
lic

5 # Variable created inside the function.


6 full_title = title + " " + name
7 print(full_title)
8 return full_title
9 No Error
up

10 full_title = get_title("Eddie", "Sir")


11 "Sir Eddie" (from local variable)
12 print(full_title) "Sir Eddie" (from global variable)
D

Figure 5-4: Using a function return value.

Using well-defined points of input and output in a function will help you avoid unwanted side
ot

effects in your programs.

The global Keyword


N

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic A
124 | Certified Entry-Level Python Programmer (PCEP™)

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()

two() two() two()


N

one() one() one() one() one()


o

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

stack stack empty

Figure 5-5: Visualizing the call stack.

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.

Guidelines for Defining and Calling Functions


Use the following guidelines to help you work with functions in Python.
Guidelines for Defining
Note: All Guidelines for this lesson are available as checklists from the Checklist tile on the and Calling Functions

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

When calling functions:


• Write the name of the function followed by open and closed parentheses.
lic

• 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

• Be aware of which values, if any, are returned from the function.


ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic A
126 | Certified Entry-Level Python Programmer (PCEP™)

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

2. Review the current state of the program.


a) Examine lines 4 through 6, 29 through 31, and 54 through 56.
up

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

program. You'll review these in more detail later.


• INVENTORY-TASK FUNCTIONS: Contains functions that will implement the main logic of the
program, i.e., each of the five data-entry tasks. You'll begin writing these functions in this activity.
ot

• 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

b) Examine line 61.


o
D

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.

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™) | 127

c) Examine lines 91 through 94.

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

3. Start defining a function for adding book titles to the inventory.


a) Highlight lines 99 through 101 and press Ctrl+X to cut them.
ot
N
o
D

You'll move this logic to a new function.


b) Place the insertion point on line 35.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic A
128 | Certified Entry-Level Python Programmer (PCEP™)

c) Type the code as shown.

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

use the function's parameters.


f) Remove book_ from the variables on lines 36 and 37 as shown.
up
D
ot
N

• The code to create the details list and to index the dictionary are now using the function's
o

parameters (id, name, quant, and price).


• When you call the function and pass in arguments, the function will bind those arguments to the
D

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.

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™) | 129

h) On a new line 36, type global book_inv

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

answer either "yes" or "no".


• Line 11 prompts the user with the custom message.
• Line 12 determines whether the user input is valid, i.e., is it some variation of "yes" or "no". If not,
ot

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic A
130 | Certified Entry-Level Python Programmer (PCEP™)

b) Examine lines 19 through 22.

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.

5. Call the appropriate helper functions.

To avoid typing, you can


copy this code from the
L5.txt snippets file,
b) Write the code as shown. or
a) Place the insertion point at the end of line 36 and press Enter twice to add new lines.
e
under the heading "Call
Helper Functions".
at
lic
up
D
ot

• 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

6. Lines 39 and 40 use what kind of argument-passing approach?


D

○ 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.

8. Call the add_book() function from the selection-menu code.


lic

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

copy this code from the


L5.txt snippets file,
under the heading
"Handle Add-Book
D

Return Values".
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic A
132 | Certified Entry-Level Python Programmer (PCEP™)

b) On a new line 112, write the code as shown.

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

a) Run the program.


b) Select the "ADD" task.
lic

c) For the book ID, enter F123


d) For the book name, enter more than 30 characters.
e) Verify that you are cautioned to enter 30 characters or fewer, then prompted to restart the book-
addition process.
up

f) Enter a valid book ID, name, quantity, and price.


g) Verify that you are shown the book info for the book you're about to add, and that you're prompted to
confirm the addition.
D
ot
N
o

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.

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™) | 133

l) Verify that the book was successfully added to the inventory.

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic A
134 | Certified Entry-Level Python Programmer (PCEP™)

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

doesn't affect line


numbering. to show the current details for the book the user is trying to update.
• Line 60 prints all local variables like normal to show the user what they just entered. The user
can compare both outputs to see what will change.
D

c) Examine the delete_book() function on lines 73 to 86.


• The only parameter needed for this function is id, since the user will specify what book they
want deleted by its ID.
ot

• 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

• No parameters are necessary for this function.


• Lines 96 and 97 use the for loop you wrote earlier to loop through each key–value pair in the
dictionary.
o

• 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) Examine the summarize_books() function on lines 102 through 121.


• No parameters are necessary for this function.
• The code is virtually the same as it was since you last touched it.
• Note that only add_book() and update_book() actually return values. As you'll see, this is
because those tasks don't need to handle their looping logic differently depending on the user's
response to the confirmation prompt.

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™) | 135

2. Examine the new menu-selection code.


a) Examine lines 176 through 201.
The code for the "UPDATE" selection is very similar to that of the "ADD" selection.
b) Examine lines 203 through 216.
• The while loop that starts on line 207 checks to make sure the book ID the user input actually
exists in the inventory.
• Line 213 calls the delete_book() function, but since that function doesn't return anything, it
doesn't assign it to a variable.

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

did you do to trigger those errors? may trigger exceptions.


For example, selecting
A: Answers may vary. Most of the functions should work, but there are a few cases where students "SUMMARIZE" before
will experience a program crash. any books are added will
up

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic A
136 | Certified Entry-Level Python Programmer (PCEP™)

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

Traceback (most recent call last):


File "<stdin">, line 1, in <module>
ZeroDivisionError: division by zero
up

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

executes before this operation may still work.


Note: Python will usually point to one or more line numbers where it encountered any
ot

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

The Exception Hierarchy


When Python encounters an exception, it usually categorizes it in one of many ways. And, these
o

The Exception Hierarchy


exception categories follow a hierarchy. This means that one exception may inherit the functionality
D

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 137

BaseException

KeyboardInterrupt Exception SystemExit

e
ArithmeticError LookupError TypeError ValueError

ut
ib
IndexError KeyError

Figure 5-6: The exception hierarchy.

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

exceptions and are meant to be used directly. or


exceptions are typically not used directly, whereas concrete exceptions are derived from base

The following table describes the built-in exceptions shown in the hierarchy figure.
e
Base Exception Definition
at

BaseException The base exception for all other built-in exceptions.


lic

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

errors, including ZeroDivisionError.


LookupError The base exception for all other exceptions that pertain to data-
mapping or sequence errors, such as IndexError.
D

Concrete Exception Occurs When


ot

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

TypeError The program attempts to perform an operation on a data type that


isn't compatible with this operation.
o

ValueError The program attempts to perform an operation on an appropriate


D

data type with an inappropriate value.


IndexError The program attempts to find an index (e.g., in a list) that doesn't
exist.
KeyError The program requests a key that is not in a dictionary.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic B
138 | Certified Entry-Level Python Programmer (PCEP™)

The try…except Statement


The try…except In programming languages like Python, there are built-in tools that enable you to defend against the
Statement unwanted effects of an exception. This process is called exception handling, as the programmer
writes code to anticipate an exception and resolve it. In Python, you can handle exceptions by
implementing the try...except statement.
Note: This statement is known in many other languages as try...catch and does essentially
the same thing.

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

print(f"Item in index {index}: {my_list[index]}.")


except Exception:
print("There's an error in the print statement.")
ot

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

print(f"Item in index {index}: {my_list[index]}.")


except IndexError:
D

print("The list index is out of range.")


Now, the code in the except branch will only execute if there is an IndexError.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 139

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

The raise Statement


Instead of letting Python produce an exception on its own, you can do so yourself with the raise The raise Statement
lic

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

>>> raise ArithmeticError("Can't calculate numbers!")


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
D

ArithmeticError: Can't calculate numbers!


This code raises an ArithmeticError exception and passes in the string as an argument.
You can raise an exception anywhere in your code, including inside try and except branches. Creating custom
ot

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

involves creating custom exceptions. (PCAP™) course.

Note: Creating custom exceptions is beyond the scope of this course.


o
D

Exception Propagation: Handling Exceptions in Multiple Places


In many cases, you'll want to write exception-handling code in functions to handle exceptions that Exception Propagation:
may occur when those functions are called. In some cases, you might want the exception to Handling Exceptions in
propagate through the call stack so that the calling function can also handle the exception. You can Multiple Places
do this using the raise statement.
Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM
Lesson 5: Using Functions and Handling Exceptions | Topic B
140 | Certified Entry-Level Python Programmer (PCEP™)

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: Delegating Responsibility to Another


Function
up

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

def divide(numer, denom):


try:
o

result = numer / denom


except ZeroDivisionError:
D

raise # Re-raise the exception.


return result

def call(num1, num2):


# Some business logic:
# ...
try:

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 141

result = divide(num1, num2)


print(f"The result is: {result}")
except ZeroDivisionError:
print("Error during division.")
And, when executed:
>>> call(10, 0)
Error during division.

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic B
142 | Certified Entry-Level Python Programmer (PCEP™)

ACTIVITY 5-3
Performing Basic Exception Handling

Before You Begin

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

h) Verify that the program terminates and a ValueError exception is triggered.


lic
up
D

• 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

explanation as to why it encountered that exception.

2. Tracebacks list the most recent function call at the top. The bottom of the
o

traceback is the code that originated the exception.


D

Which of the two lines do you think is at fault, and why?


A: Line 112 is at fault because it is the source of the error (not a valid integer). Line 226 calls
summarize_book(), which eventually executes line 112.

3. Trigger another exception in the program.


a) Rerun the program.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 143

b) Select the "SUMMARIZE" task without adding a book first.


c) Verify that, this time, you receive a ZeroDivisionError.

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

or L5.txt snippets file,


under the heading
"Handle ValueError for
ADD".
e
at
lic
up
D

• 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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic B
144 | Certified Entry-Level Python Programmer (PCEP™)

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.

Highlight lines 70 through 84 and press Tab to indent.


e
at
lic
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 145

h) Verify the function's code appears as shown.

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

6. Add code to handle the ZeroDivisionError exception.


a) Place the insertion point on line 128 and ensure it is indented once.
b) Type try:
up

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

copy this code from the


L5.txt snippets file,
under the heading
ot

"Handle
ZeroDivisionError".
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic B
146 | Certified Entry-Level Python Programmer (PCEP™)

e) Press Backspace to unindent by one, then write the code as shown.

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

b) Select the "SUMMARIZE" task without adding a book first.


c) Verify that the program keeps running and that you receive a message about there being no books
in the inventory.
d) Add a new book, entering an invalid value for the book quantity, book price, or both.
D

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

9. Terminate the program, close the project, and close PyCharm.


N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions | Topic B
Certified Entry-Level Python Programmer (PCEP™) | 147

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Lesson 5: Using Functions and Handling Exceptions |
e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Certified Entry-Level Python Programmer (PCEP™) | 149

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Course Follow up
e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


A Mapping Course Content

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

Best of luck in your exam preparation!


up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Mastery Builders

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


154 | Certified Entry-Level Python Programmer (PCEP™)

Mastery Builder 1-1


Creating the WordCount Program

Activity Time: 15 minutes

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

As shown in the image, the program will generally do the following:


1. Read all words from a manuscript that the user provides.
2. If a manuscript word appears in a separate list of words, count how many times
up

that word appears in the manuscript.


3. Retain the 50 most frequent words.
4. Ask the user if they want to strip common words like articles, conjunctions,
D

pronouns, etc., from the results.


5. Display the count of each word to the user.
You don't yet have any manuscripts on hand and the word list is not yet complete. So,
ot

samples of each will be hardcoded into the program.


For now, you'll create the WordCount project and start writing basic input and output
N

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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Mastery Builders
Certified Entry-Level Python Programmer (PCEP™) | 155

1. Start a new project in PyCharm called WordCount and save it to /home/


student/094027Data/Setting Up Python and Developing a Simple Application.
• Ensure you are creating a new directory called WordCount inside of this directory.
• Ensure you are using the previously configured Python 3.10 system interpreter.
• Do not allow PyCharm to create a main.py welcome script.

2. Create a new Python file in the project called word_count.py.

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.

Verify that your input is printed back to you.


or
e
at

9. Close the project and PyCharm.


lic
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Mastery Builders
156 | Certified Entry-Level Python Programmer (PCEP™)

Mastery Builder 2-1


Processing Integers and Strings in the
WordCount Program

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

1. Open the /home/student/094027Data/Processing Simple Data


lic

Types/WordCount project in PyCharm.

Open the word_count.py file for editing.


up

2.

3. Write code to prompt the user to enter the number of times that the
word "boat" appears in the first chapter.
D

Assign the prompt to the variable boat_num.


ot

4. Assign total_boat_num to boat_num times 10.


Note: Remember, user_input() results in a string, so you'll need to
N

convert boat_num to an integer first.

5. Write code to print the following, using concatenation and/or string


o

formatting as necessary:
D

Estimated count of word "boat": <total_boat_num> times.

Note: <total_boat_num> should be replaced with the actual variable.

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.

8. Close the project and PyCharm.

e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Mastery Builders
158 | Certified Entry-Level Python Programmer (PCEP™)

Mastery Builder 3-1


Adding Data Structures to the WordCount
Program

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

WordCount project in PyCharm.


lic

2. Open the word_count.py file for editing.

3. Review the code from lines 3 through 8.


up

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

4. Write code to add read_input_1 and read_input_2 to a list


named read_input.
ot

5. Write code to append read_input_3 to read_input.


N

6. Write code to remove punctuation from the first read_input list


item.
o

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.

8. Write code to print the dictionary.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Mastery Builders
Certified Entry-Level Python Programmer (PCEP™) | 159

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Mastery Builders
160 | Certified Entry-Level Python Programmer (PCEP™)

Mastery Builder 4-1


Adding Conditional Statements and
Loops to the WordCount Program

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

1. Open the /home/student/094027Data/Writing Conditional


up

Statements and Loops/WordCount project in PyCharm.

2. Open the word_count.py file for editing.


D

3. Review the code from lines 3 through 12.


ot

• 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

4. Review the code from lines 14 through 16.


D

• 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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Mastery Builders
Certified Entry-Level Python Programmer (PCEP™) | 161

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").

6. Review the code underneath the # Remove punctuation comment.


• A for loop has been created for you.
• This code loops through the read_input list and strips out the punctuation from each word in the
list, if there is any.

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.

7. Write code to loop through each word in read_input, creating a dictionary

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

suppress common words. Make sure the loop:


• Only indexes the first 50 words in the items list.
lic

• 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:

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Mastery Builders
162 | Certified Entry-Level Python Programmer (PCEP™)

a: 1 times
is: 3 times
test: 4 times
this: 3 times

12.Close the project and PyCharm.

e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Mastery Builders
Certified Entry-Level Python Programmer (PCEP™) | 163

Mastery Builder 5-1


Adding Functions to the WordCount Program

Activity Time: 30 minutes

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.

1. Open the /home/student/094027Data/Using Functions and Handling


or
e
Exceptions/WordCount project in PyCharm.
at

2. Open the word_count.py file for editing.


lic

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

word_count dictionary from the function.


When the function completes, it will now pass the result (the contents of the word_count dictionary)
back to the statement that called the words_dict() function.
ot

5. Take all of the code below word_dict() that prints and suppresses the
N

output, and place it inside of a new print_top_words() function. Make


sure the function:
o

• Has a single parameter called choice.


• Returns results_list at the end.
D

6. Change the conditional statement in this function so that it checks choice


instead of user_common_words.

7. At the top of this function, call words_dict() and assign it to word_count.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Mastery Builders
164 | Certified Entry-Level Python Programmer (PCEP™)

8. Move the code under the # Prompt user. comment to the


bottom of the code, into the global scope. This includes:
• The line that asks the user to enter text to analyze.
• The line that initializes user_common_words.
• The while loop that asks the user if they want to strip common words.

9. Below this, still in the global scope, call print_top_words() and


pass in the user's choice as an argument.

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Mastery Builders
Solutions

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.

8. What kind of error is this? Why?


or
A: This is a logic error. Python is able to interpret and execute the code correctly, but the code
doesn't do what the programmer intended.
e
at

ACTIVITY 2-1: Processing Integers and Strings


lic

4. Why can you concatenate num_books_query, but must use interpolation


for total_quant?
up

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

ACTIVITY 2-2: Processing Mixed Number Types


ot
N

3. Why did avg_price turn into a float instead of an integer?


A: By default, the result of all regular division operations in Python 3 is always a float.
o

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?
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.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


166 | Certified Entry-Level Python Programmer (PCEP™)

ACTIVITY 3-1: Processing Ordered Data Structures

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

stored in nested lists.

Which data structure would you use to assign numbers to each


lic

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

change or remove tasks as needed.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Solutions
Certified Entry-Level Python Programmer (PCEP™) | 167

ACTIVITY 5-1: Defining and Calling Functions

6. Lines 39 and 40 use what kind of argument-passing approach?


◉ Positional
○ Keyword
○ Mixed

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

ACTIVITY 5-3: Performing Basic Exception Handling


up

2. Which of the two lines do you think is at fault, and why?


A: Line 112 is at fault because it is the source of the error (not a valid integer). Line 226 calls
summarize_book(), which eventually executes line 112.
D

4. Why do you think Python was trying to divide by zero?


A: The total_ids variable refers to the number of book titles in the inventory. If no books have been
ot

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

exception types from specific to general according to the exception hierarchy?


A: A general exception type that has a more specific exception type under it will always catch that
o

specific exception if it has not already been caught. The branch with the specific exception will never
execute, making it pointless.
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Solutions
e
ut
ib
tr
is
D
or
e
at
lic
up
D
ot
N
o
D

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Glossary

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 An operator that tests the relation between


A numeral system with a base of 2. two values.
lic

binary operator compiler


An operator that performs an operation on Software that translates high-level source
two operands. code to a lower-level language. Also
up

referred to as an ahead-of-time (AOT)


bitwise operator compiler to distinguish it from just-in-time
An operator that performs an operation on (JIT) compilers.
D

binary values.
concatenation
Boolean The process of combining strings end to
ot

A data type that can hold either True or end.


False values.
conditional statement
N

bytecode An object that requires the program to


Intermediary code designed to be make a decision based on certain
o

efficiently executed by an interpreter, conditions.


usually through a virtual machine.
D

constant
call stack An identifier with a value that does not
The sequence of functions called by the change.
interpreter.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


170 | Certified Entry-Level Python Programmer (PCEP™)

CPython floor division


The default and most widely used Python The arithmetic operation of dividing two
interpreter. numbers and returning the nearest whole
number that is less than or equal to the
data structure result of the division.
A collection of data values stored in an
organized format. function
A block of reusable code that performs a
data type

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

execution or attempted execution of code. (Integrated Development and Learning


Environment) The default Python IDE.
escape character
lic

See escape code. immutable


A description indicating that an object's
escape code value cannot change after it is created.
up

A way to represent characters in a string


literal that can't be represented directly. indexing
The process of retrieving a single value
exception from an object like a string or list by the
D

A type of error that indicates the position of that value in the object.
interpreter is able to understand the code
integer
ot

but cannot complete the code's action due


to numerous possible circumstances. A whole number that can be either positive
or negative and can't include a decimal.
N

exception handling
The process of anticipating and responding interactive mode
to program exceptions. A Python feature in which the interpreter
o

presents a command prompt/shell to the


float user for immediate code execution.
D

A less precise version of a decimal number


that can use scientific notation to represent interpreter
a very large or very small number. Software that executes source code
directly.
floating-point number
See float.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Glossary
Certified Entry-Level Python Programmer (PCEP™) | 171

JIT compiler numeral system


(just-in-time compiler) Software that translates A way of writing numbers using a set of digits.
source code into lower-level code when it's
needed by the program, combining ahead-of- octal
time (AOT) compilation with interpretation. A numeral system with a base of 8.

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 error that occurs when a program has PEP 8


unintended or unpredictable results due to The official documentation that prescribes
lic

improperly implemented code. style guidelines for Python code.

logical operator project folder


up

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

A two-dimensional list. range


An immutable sequence of integers that is
N

modulo commonly used to iterate through a process.


The arithmetic operation of finding the
remainder in a division. recursion
o

The act of a function calling itself.


mutable
D

A description indicating that an object's value reserved word


can change after it is created. See keyword.

nesting
The act of placing a programming construct
within another programming construct.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Glossary
172 | Certified Entry-Level Python Programmer (PCEP™)

scope syntax error


The property that defines where a particular An error that occurs when a programming
object is valid in source code and where it is language cannot understand a piece of code
not. that the programmer has written.

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

in a string literal with their corresponding


values.
N

string literal
A value that is enclosed in single or double
quotation marks.
o

syntax
D

The rules that govern how to write


programming code for it to execute properly.

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


Glossary
Index

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

JIT compiler 4 overview 74


overview 3 processing 75
lic

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

if...else statement 87 escape characters 20


if statement 86 See also escape codes
escape codes 20
ot

logical operators 89
nested if statement 88 exception handling
order of operations 91 delegate to calling function 140
N

overview 86 propagate to multiple places 139


constants 18 specific 138
CPython 4 try...except statement 138
o

exception ordering 139


exceptions
D

D built-in 137
data structures hierarchy 136
mutable vs. immutable 62 overview 136
sequences 62 raise statement 139
data types

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM


174 | Certified Entry-Level Python Programmer (PCEP™)

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

Integrated Development and Learning numeral systems


Environment, See IDLE base 10 49
integrated development environment, See binary 49
ot

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

See also order of operations


operators
K defined 18
keywords 18 unary vs. binary 19
order of operations
arithmetic 19
in conditional statements 91
Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM
Index
Certified Entry-Level Python Programmer (PCEP™) | 175

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

variable shadowing 124


semantics 17
lic

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

Licensed For Use Only By: Student 01 Feb 10 2025 10:26AM

You might also like