unit-1-tutorials-program-basics
unit-1-tutorials-program-basics
INSIDE UNIT 1
Learning to Code
Programming Mindset
Thinking Through Examples
Forming an Algorithm
Guide to Using Replit
Testing
Data Types
Programming Mindset
by Sophia
WHAT'S COVERED
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 1
In this lesson, you will learn about how to think like a developer and what’s involved in the development process.
Specifically, this lesson covers:
1. Writing Programs
2. Input, Processing, and Output
3. Understanding the Development Life Cycle
1. Writing Programs
Writing programs (or programming) is a very creative and rewarding activity. You can write programs for many reasons, ranging
from making your living or solving a difficult data analysis problem, to having fun or helping someone else solve a problem.
This course assumes that everyone needs to know how to program, and that once you know how to program you will figure
out what you want to do with your newfound skills.
We are surrounded in our daily lives with computers ranging from laptops to cell phones. We can think of these computers as
our “personal assistants” who can take care of many things on our behalf. The hardware in our current-day computers is
essentially built to continuously ask us the question, “What would you like me to do next?”
Our computers are fast and have vast amounts of memory and can be very helpful to us if we know the language to speak to
explain to the computer what we would like it to “do next.” If we knew this language, we could tell the computer to do tasks on
our behalf that were repetitive. Interestingly, the kinds of things computers can do best are often the kinds of things that we
humans find boring and mind-numbing.
EXAMPLE
For instance, look at the first three paragraphs of this lesson and tell me the most commonly used word and how many times
the word is used. While you were able to read and understand the words in a few seconds, counting them is almost painful
because it is not the kind of problem that human minds are designed to solve. For a computer, the opposite is true. Reading
and understanding text from a piece of paper is hard for a computer to do, but counting the words and telling you how many
times the most used word was used is very easy for the computer.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 2
This very fact that computers are good at things that humans are not is why you should become skilled at talking “computer
language.” Once you learn this new language, you can delegate mundane tasks to your partner (the computer), leaving more
time for you to do the things that you are uniquely suited for. You bring creativity, intuition, and inventiveness to this
partnership.
In the rest of this course, we will turn you into a person who is skilled in the art of programming. In the end you will be a
programmer—perhaps not a professional programmer, but at least you will have the skills to look at a data/information
analysis problem and develop a program to solve the problem.
First, you need to know the programming language (Python)—its vocabulary and grammar. You need to be able to spell
the words in this new language properly and know how to construct well-formed “sentences” in this new language.
Second, you need to “tell a story.” When writing a story, you combine words and sentences to convey an idea to the
reader. There is a skill and art in constructing the story, and skill in story-writing is improved by doing some writing and
getting some feedback. In programming, our program is the “story” and the problem you are trying to solve is the “idea.”
Once you learn one programming language such as Python, you will find it much easier to learn a second programming
language such as JavaScript or C++. This new programming language may have a very different vocabulary and grammar, but
the problem-solving skills will be the same across all programming languages.
You will learn the “vocabulary” and “sentences” of Python pretty quickly. It will take longer for you to be able to write a
coherent program to solve a brand-new problem. We teach programming much like we teach writing. We start reading and
explaining programs, then we write simple programs, and then we write increasingly complex programs over time. At some
point you “get your muse." You begin to see the patterns on your own and can see more naturally how to take a problem and
write a program that solves that problem. And once you get to that point, programming becomes a very pleasant and creative
process.
The definition of a program at its most basic is a sequence of Python statements that have been crafted to do something. It
might be easiest to understand what a program is by thinking about a problem that a program might be built to solve, and then
looking at a program that would solve that problem.
Let's say you're doing social computing research on Facebook posts and you're interested in the most frequently used word in
a series of posts. You could print out the stream of Facebook posts and pore over the text looking for the most common word,
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 3
but that would take a long time and be very mistake-prone. You would
be smarter to write a Python program to handle the task quickly and
accurately, so you can spend the weekend doing something fun.
TERM TO KNOW
Program
A sequence of computer language statements that have been crafted to do something.
Imagine having to cook a recipe for the first time. You’d need to have the specific ingredients and their amounts, as well as the
detailed instructions of how to prepare the recipe. Similarly, a computer program consists of lines of code that the computer
runs and uses variables to perform them. Things must run in a specific order. For example, if you were baking a cake, you
wouldn’t put the cake in the oven prior to mixing in the ingredients. You must think about all of the steps in logical order.
Typically there are three main types of operations that are executed in any program.
The first is the input to the program. The input to the program allows data to be entered in through a variety of ways,
including by you through the keyboard and mouse. It could also be from files on the computer, other hardware devices,
images, sounds or many other potential options. The input from these sources is stored and placed into the memory of
the computer and can include all types of data, including text and numeric values.
The next type of operation is processing. When it comes to processing data, there can be many different steps that are
performed on the data. It could be storing them, using them for calculations, validating the data or sorting the data.
The last type of operation is the output. After the data has been processed, output is sent to the monitor, printer, email,
file, report, or other means where individuals can view the resulting data. The goal of most programs is to take the raw
data or input, process it into information that can be useful, and then output it to the user.
In order to write these programs, we need to use a programming language that the computer understands, such as Python,
Java, C++ or C#. In this course, we will be using Python. Each programming language has its strengths and weaknesses for the
task at hand. Most of these languages have similar logic behind them so you can carry that between the different languages.
Where they differ are the rules called syntax. Each programming language has a very specific set of syntax rules that needs to
be followed. Computers are not smart enough to understand a program unless the syntax is correct.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 4
Python was created as a programming language for those who aren’t doing software development around the clock, but
instead for those who are interested in code to handle common tasks. When we write a program using programming
languages like C or C++, we have to compile it. In the process of compiling it, the compiler takes the human-readable code that
we write and translates it to machine code (also known as machine language) that can be executed by the computer. If a
program is successfully compiled, the compiler creates a file that can be run. A compiled program has limitations as it can only
be run on specific platforms that it is written for.
Python, on the other hand, is an interpreted language similar to Java. It is not a compiled language (although we still go
through and compile our code). With Python, it is written as a .py file and when it is compiled into bytecode, it is saved as a .pyc
or .pyo format. The bytecode is different from the machine code, as the bytecode is a low-level set of instructions that can be
run through an interpreter. This interpreter has to be installed on the computer. Instead of running the program directly on the
computer, the bytecode is run through a virtual machine. One of the key reasons why interpreted languages are preferred is
because they are platform independent. This means that as long as the bytecode and the virtual machine have the same
version, a Python program can be run on any platform regardless of if it is a Windows, MacOS, or Linux system. Although there
are differences in how compilers and interpreters function, the core purpose is the same, with interpreters having that added
step.
TERMS TO KNOW
Input
Ways a program gets its data; user input through the keyboard, mouse, or other device.
Processing
Takes the data inputs and prompts and calculates the results (output).
Output
The results at the end of a program based on user input and system processing.
Syntax
The syntax is the “grammar” rules of the programming language. Each programming language (like Python) has its own syntax.
Compiler
A compiler scans an entire program and attempts to convert the whole program at once to machine code.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 5
Machine Code
Also known as machine language. The computer uses binary (0s and 1s) to perform tasks. At a high level, the programming
language code that you write gets translated or compiled to the machine code that the computer understands.
Bytecode
An intermediary step for code conversion between the programming language that you write and the machine code that a
computer uses.
Interpreter
An interpreter takes the bytecode one line at a time and converts it to machine code.
Virtual Machine
A software program that behaves like a completely separate computer within an application.
STEP BY STEP
If we don’t understand what the problem is that we’re trying to solve, we’ll have errors right from the start. This step may
require some planning to gather the requirements from those that are affected or what we consider as stakeholders. As
developers, we may not have the knowledge about the industry that we’re building the program for and have to rely on those
subject matter experts to provide their input on the business processes.
THINK ABOUT IT
For example, if you are tasked with writing a program for a high school to email to the students how much the school fees are,
we may have some questions. For example, are the fees the same for all students, or are they different by year, or perhaps by
the courses that they take? When should the students be notified? Where do we find the student list? Are there exemptions to
the fees? These are not questions that as a developer you can answer, and in order to understand the problem, you have to go
to someone that can provide that guidance.
Once we understand what the problem is, we can then start to plan the logic to break it down further. We’ll explore this in
upcoming lessons, but the idea is that we want to break it down in detail so that the computer can understand what needs to
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 6
be done. Imagine if you had to direct someone that was blindfolded through an obstacle course. You would need to be very
specific with the steps that they would need to take and when. If you accidentally told them to jump when they should duck
under a pole, they may hurt themselves. In the same way, programs need to be written in the correct logical order for them to
work correctly. This is the process where we’ll form an algorithm as the sequence of steps to solve the problem.
With the algorithms in place, the program can then be developed in a programming language. In our course, we will focus on
Python, but there are hundreds of languages that could be selected. Each has their advantages and disadvantages, so
selecting one can be based on several criteria. One advantage may be familiarity; there are some programming languages
like C++, C#, Java, and Python that are fairly widely used in various methods. If you are already familiar with the language, you
may choose to use that method.
Another criterion, if you are developing a program for an organization, is what languages they use within the organization. As a
program could be developed by many individuals and teams, having consistency across the developers is important. Another
important criterion is the support for specific libraries and programs that you want to use. Different programs will have
different levels of support for programming languages. For example, if we are developing code for a game engine called
Unity, we would have to use C#, Boo (similar to Python), or JavaScript. We don’t have a choice to use other options.
Although we do have many different programming languages, at the computer level, there is only the machine code that’s
coded in 0s and 1s. These 0s and 1s are set up as electrical switches that can be turned off and on, which are represented by
the 0s and 1s respectively. At a high level, the programming language code that you write gets translated or compiled to the
machine code that the computer understands.
If there are errors in the syntax, this is normally caught during the prior step. Without the program written correctly, the
compiler would throw an error to the user to fix. It would be similar to having an English program that said, “The ct and mouse
were friends.” This would result in an error, because “ct” isn’t a word in the English language. We meant to have it as “cat.”
Logical errors are issues that the computer wouldn’t catch. For example, if the program meant to give everyone a 10% discount
on their orders, but it was accidentally coded to give everyone a 100% discount, that wouldn’t be caught by the compiler and
would be a logical error. In order to find these errors, we have to test the code and compare the results with the expected
values.
Once the code has been tested, it can then be deployed for the program to be used for the purpose that it was originally
developed.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 7
Once a program is deployed, there may be bugs or errors that come up that have to be addressed and patched. There may
be improvements to performance that have to be addressed. All of these factors may require maintenance. In some cases, it
may require some additional development, which in turn would start right back at understanding the problem again.
SUMMARY
In this lesson, we learned what programming is and about the purpose of writing programs to solve problems. We
also learned the three main types of operations of a program: input, processing, and output. Finally, we talked about
how the development life cycle requires a high-level process for planning, creating, testing, and deploying an
application. Developers generally do not just sit down and start writing code; rather, they break the process down into
individual steps.
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
TERMS TO KNOW
Bytecode
An intermediary step for code conversion between the programming language that you write and the machine code that a
computer uses.
Compiler
A compiler scans an entire program and attempts to convert the whole program at once to machine code.
Input
Ways a program gets its data; user input through the keyboard, mouse, or other device.
Interpreter
An interpreter takes the bytecode one line at a time and converts it to machine code.
Machine Code
Also known as machine language. The computer uses binary (0s and 1s) to perform tasks. At a high level, the programming
language code that you write gets translated or compiled to the machine code that the computer understands.
Output
The results at the end of a program based on user input and system processing.
Processing
Taking the data inputs and prompts and calculates the results (output).
Program
A sequence of computer language statements that have been crafted to do something.
Syntax
The syntax is the “grammar” rules of the programming language. Each programming language (like Python) has its own
syntax.
Virtual Machine
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 8
A software program that behaves like a completely separate computer within an application.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 9
Thinking Through Examples
by Sophia
WHAT'S COVERED
In this lesson, you will review various problems and determine how to break them down into discrete steps.
Specifically, this lesson covers:
1. First Steps
2. Real-World Example
3. Is It Raining or Snowing?
4. Coding Example
1. First Steps
BEFORE YOU START
Before we get started with any new problem that we want to design a program for, we need to understand what the problem
is. For example, we need to determine what the goal or purpose of the program is. Try to think about what the program is
supposed to do and what users should be able to expect when they run a particular program. For example, if we run a
program to convert temperature from Celsius to Fahrenheit, we should expect that if we pass in a temperature value of 0
(which is 0 Celsius), we should get a result of 32 Fahrenheit.
Once we define the goal and purpose of the program, we need to be able to then start to break down the problem into the
smallest possible individual steps that are needed to perform the necessary tasks. We should not leave out any instructions or
add in extra instructions that are not needed for the program.
For us to have a program work correctly, we have to ensure that the logic and syntax are correct. We’ll get into the specific
syntax of Python later in the course, but remember that syntax is the specific grammar rules for the language. For now, we will
focus on planning the logic of a program. For us to write a program that works properly, the proper logic with the correct
program instructions must be in the right order. If certain steps are not performed in the right order, we’ll run into a lot of
potential issues.
EXAMPLE
For example, consider the steps it takes for you to wash your face. Would it make sense to dry your face prior to putting water
on your face? Or would it make sense to put on soap after you’re done drying your hands? Thinking about the steps in a
program is done in a similar manner. We need to have the specific steps defined as a starting point.
Once we’ve defined those steps in the right order, we can start to think about what items could be stored as variables. A
variable is a term that you’ll hear about quite often in programming. It is defined as a name that is used for a location in
memory where the value that’s stored in that location can hold different values at various points throughout the program. Using
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 10
our example of the temperature conversion, we may have the temperature as a variable, as we would want to get the input
from the user to make the conversion in the code. In a larger program, there could be many other variables that could be used
within the program. Any potential user input or a result of a calculation could be a variable that could be defined and used.
Once we have those variables defined, we’ll need to then start to look at the logic beyond the sequence of steps. There may
be scenarios where we have conditions or branching of decisions based on user input or other variables. For example, if you
ask the user if they are hungry, there could be one path if they are hungry and another path of statements if they are not. We
could also have other elements to think about such as certain statements being possible to run more than once. In these
cases, we may make use of repetition or break down those statements into sub-parts of a program.
TERM TO KNOW
Variable
A named memory location that has the ability to hold various distinct values at different points in time in the program.
2. Real-World Example
Analyzing problems can potentially seem overwhelming when you think about all of the steps involved. So, let’s break things
down into smaller steps to start demonstrating what’s involved! There are many different examples that exist around us that
can make use of the process of breaking down problems and understanding how the steps are intertwined.
EXAMPLE
Let’s have someone make a glass of orange juice with these steps:
1. Get oranges.
2. Get knife.
3. Get cutting board.
4. Get juicer.
5. Turn on juicer.
6. Add bread.
7. Place halved oranges in juicer.
8. Turn off juicer.
9. Get glass.
10. Place glass under juicer.
11. Cut oranges in halves on cutting board.
First of all, it looks like we added bread into the orange juice; that wouldn’t work so well. Other steps are out of sequence,
some are missing, and some are obviously for other procedures outside of making orange juice. The logical order of the
statements is very important, as a computer program can only execute the steps that you tell it to in that specific order. We
would probably need to change our steps to:
1. Get cutting board.
2. Get juicer.
3. Get glass.
4. Get oranges.
5. Get knife.
6. Cut oranges in halves on cutting board.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 11
7. Place glass under juicer.
8. Turn on juicer.
9. Place halved oranges in juicer.
10. Turn off juicer.
THINK ABOUT IT
There are some steps where the order doesn’t matter and we could swap them around, such as the first five steps in which we
are getting items to complete the task. Think of some of your daily tasks that you do and how you would break down the steps
so that a robot could follow them exactly as is.
3. Is It Raining or Snowing?
Let’s take a look at a bit more complex scenario where we’ll have to incorporate more areas of consideration. Say we have
Sophie, who walks to work from Monday to Friday. She checks the weather forecast. If it’s raining during the day, she'll bring a
rain jacket. If it’s snowing, she’ll bring her winter jacket. On the weekends, she needs to bring the car keys, as she drives to
visit her family on Saturday and visit her friends on Sunday.
To start, we’ll need to break things down into various parts of the program.
EXAMPLE
First, we need to make note that the selection (as a start) is based on the day of the week. If it’s Saturday or Sunday, Sophie just
needs the car keys:
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 12
• if weatherForecast is equal to snow
• itemToBring = "winter jacket"
We’re incorporating a few new features with the use of conditions here, which is a big part of programming. We’ll get into that
level of detail later on, but the idea is that we can represent any scenario in code as long as we can break it down into specific
steps.
The logic sample above is not in any programming language. But this type of approach to writing down the logic is useful
regardless of what programming language is used. For example, on the first line, we don’t need to know how to check the day
of the week. Rather, we just state that this is what we’re intending to do. Within a programming language, it could be one line
of code or a dozen lines of code, but we care more about the logic at this point instead. We’ll dive into this example a bit
further in the upcoming lesson.
4. Coding Example
We discussed the basic elements of input, processing and output, so let’s consider how we can use a computer program to do
something that we want. Consider a program that asks the user to enter in two numbers, calculates the sum, and then outputs
the results to the user. In order to break this down, we want to think about what we’re trying to do in logical steps with input,
processing, and output. Rather than get lost in syntax, we can write it in pseudocode or English-like statements. We want to
start by first asking the user to enter in a number; otherwise, the user wouldn’t know what they should be doing:
The next step is to take the user’s input and store that into a variable. We’ll simply name it as firstNumber , as that reflects
what it is supposed to contain. This is an important part to consider. You want to define the variable so that later on in the code,
you know what it references. If you name it as X or Y, in a larger program, it’ll be hard to keep track without constantly
referencing back to the start of the code when it was first defined. Notice as well that we don’t have any spaces in the variable.
This is important too, because in programming languages, variables cannot contain any embedded spaces.
Remember that a variable is a named memory location that has the ability to hold various distinct values at different points in
time in the program. For example, the first time the program is run, we may have it set to 1. The next time, we could have it set
to 1000. If we needed to change the value later on in the program, we could do so as well.
input firstNumber
The next step is to prompt the user for the second number. Take note that we should always quote the literal string. A literal
string is simply a series of characters that are combined together and enclosed in quotes. For example, "Enter in the second
number" is a literal string. A string is a data type that can store a literal string as a value. You will learn a lot more about strings
in a future lesson.
input secondNumber
The next step is the processing step, where we will take the sum of the firstNumber and the secondNumber and store it in
a new variable called total .
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 13
The last step will output a string of text and then the calculated total from the prior step. What’s unique about this statement is
that it combines a literal string with the value of the variable as part of the output.
If this were a program that was being executed (run), it would look like the following:
STEP BY STEP
Lastly, the last line would take the literal string and concatenate it with the value of the variable total , resulting in the
following output:
CONCEPT TO KNOW
You just read the term concatenate (concatenation) and you will hear this term throughout this course. Concatenate means to
combine words or numbers. For example, to concatenate the numbers 1234 and 5678 would result in 12345678. To
concatenate the words "snow" and "ball" would result in "snowball." There are specific features in Python that allow values to
be concatenated together. We will cover those in upcoming lessons.
TERMS TO KNOW
Pseudocode
English-like statements that describe the steps in a program or algorithm.
String
A data type that can store a literal string as a value.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 14
Literal String
A series of characters that are combined together and enclosed in quotes; for example, "Enter in the second number" is a
literal string.
SUMMARY
In this lesson, we learned that the first steps of solving a problem are to break down the problem into the smallest
possible steps needed to perform the necessary tasks. We used a real-world example of making orange juice to see
this breakdown. Then, we added the use of conditions in the "Is it raining or snowing?" scenario where decisions can
be added to the process. Finally, we also looked at coding examples to understand how to break down problems into
individual steps.
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
TERMS TO KNOW
Literal String
A series of characters that are combined together and enclosed in quotes; for example, "Enter in the second number" is a
literal string.
Pseudocode
English-like statements that describe the steps in a program or algorithm.
String
A data type that can store a literal string as a value.
Variable
A named memory location that has the ability to hold various distinct values at different points in time in the program.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 15
Forming an Algorithm
by Sophia
WHAT'S COVERED
In this lesson, you will review various problems and find patterns to help build a solution to those problems prior to
writing code. Specifically, this lesson covers:
1. Introduction to Algorithms
2. Guessing Game
3. Algorithm to Guess the Guessing Game
1. Introduction to Algorithms
With any problem that we're building a program for, we must define what the algorithm needs to be. Recall that the algorithm is
the logical step-by-step plan that we need to build to solve the problem. When you design an algorithm, it’s also important to
think about different ways you can solve the problem and to find the best way to do it. As you learn about new functionality in a
programming language, you’ll find potentially better ways to optimize a solution.
THINK ABOUT IT
Before we get started, we should think about the big picture of the algorithm. In the end, what is the final goal of the problem?
Consider other aspects like how often this program is meant to run, when the program creation deadline is, or how complex
the problem is. For example, if a program is only meant to run once, it probably would be acceptable if it weren’t fully
optimized. However, if a program is meant to run millions of times a day, the optimization of a solution would be crucial. Think
about a mobile app that you use on a regular basis. Would you continue to use that app if it took five minutes for the app to
even load? Most would probably not.}}
Once we have the big picture in mind, we then want to think about the individual stages and steps that will need to be broken
down. There are some basic criteria that you should think about, as we discussed in the programming mindset lesson.
STEP BY STEP
1. To start, we need to ask what the inputs into the problem are and where they are coming from. This should give us a
starting point to the problem.
2. Next, we should look at what the outputs of the problem are. This is different than just the items that we output throughout
the problem; rather, we should ask what the end result of the program should be. That could be a single output line, but it
could also be a file, an email, or a report being generated.
3. Next, we need to think about what the order of the steps should be. The order is important as it helps define the actions
that need to occur.
4. Within the program, we should look at what types of decisions need to be made. You’ll remember in our prior lesson that
we had Sophie needing to bring different items with her depending on the day or weather forecast. These types of
decisions add a layer of choice and options based on the input and other variables.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 16
NOTE: Also consider if there are any areas of the problem that could be repeated.
You will learn about solutions for addressing repeatability in the coming lessons. For now, look for patterns in your algorithm.
Finding patterns can help reduce the number of steps it takes to get to your expected solution. These patterns can be
converted to code later to help with processes that need to be repeated over and over again. So, rather than having to write
for every single situation (step), you can streamline the code with the use of loops, functions, classes, and methods. You'll want
to keep this in the back of your mind as you work through your algorithm to avoid having to rewrite step(s) many times. Don’t
worry too much yet about what loops, functions, classes, and methods are. We will be identifying all those possible coding
solutions later. Just know for now that you can optimize your code by finding repeating patterns.
EXAMPLE
On the topic of repeatability and looking for patterns, here is a real-
world example. Think about going to an ATM machine to withdraw
money. You're initially presented with a menu option. Once you’ve
completed a transaction like withdrawing money, you’re presented
with the menu again. You can complete as many transactions as you
want before the program ends. Rather than having to completely exit
out of the program after a single transaction, the menu is repeated
over and over again until a selection is entered to exit out of the
program.}}
TERM TO KNOW
Algorithm
A logical step-by-step plan that we need to build for solving a problem.
2. Guessing Game
EXAMPLE
In this example, we’ll create a simple guessing game that allows the user to guess a random value between 1 and 100. The
user will be able to keep guessing the number until the number is found. After each guess, the program will tell the user if the
guess is too high or too low. Once the user has guessed the number, the program will tell the user how many times it took the
user to guess and exit the program.
To start, we’ll have to define the input elements of the program. In this case, we need to have a random number that is
generated between 1 and 100. Let’s call it randomNumber . We’ll also need to store the input from the user for the guess. Let’s
call it guess . Lastly, we’ll need a counter, to count the number of guesses that the user made before they guessed the number
correctly. We’ll call that variable numberOfGuesses .
Next, we’ll determine what the output at the end of the program should be. This should be the numberOfGuesses output to
the screen once the user has guessed the number correctly.
THINK ABOUT IT
Do we have any elements of conditions? We do this in this program. One is to check if the guess is higher than the
randomNumber , after which we should increase the numberOfGuesses and inform the user. If the guess is lower than the
randomNumber , we should also increase the numberOfGuesses and inform the user. If the guess is equal to the
randomNumber , we’ll end the program after outputting the result to the user.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 17
Do we have any repeating elements? In this case, we do. We want to keep running the check and output to the user until the
guess is equal to the randomNumber .
Let’s take a look at what this would look like in code. Don’t try to decipher the code below. You will learn later what functions
do and how to write lines of code. Just see if you can follow the logic and read the comments (identified by the hashtags).
HINT
Comments: The “#” (hashtag) is used in Python code to identify a comment. Commented lines of code are ignored by the
compiler during run time. A programmer adds comments throughout the code to explain how the program or function works.
This makes it easier for the programmer or anyone else looking at the code to identify the intention of that section of code.
Keep in mind that some programs are hundreds of lines of code or more, so commenting is a necessary practice. We will talk
more about commenting and its use in a later lesson.
For this code example, we will only bold the actual compiled code that is running.
#We are importing a module that we need to be able to generate random numbers
import random
#Once the guess is equal to the randomNumber, we can output this line
print("You guessed correctly", numberOfGuesses, "guesses!")
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 18
Below is a screenshot of the code from a programming editor application.
TERMS TO KNOW
Comments
The “#” (hashtag) is used in Python code to identify a comment. Commented lines of code are ignored by the compiler during
run time. A programmer adds comments throughout the code to explain how the program or function works.
Module
A self-contained piece of code that can be used in different programs.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 19
With this in mind, we could build in an algorithm—which we’ll call AI—to do this for us using that same algorithm. Again, don’t try
to decipher the code; just see if you can follow the logic. The changes from the previous code are in red text.
#We are importing a module that we need to be able to generate random numbers
import random
#We are setting the AI to guess the middle number between the lower and upper limit
guess = int((lowerLimit + upperLimit)/2)
print("AI guesses ", guess)
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 20
lowerLimit = guess #Since the guess is too low, we reset the lowerLimit to the guess
guess = int((lowerLimit + upperLimit)/2) #Our new guess is between the new lower and upper limit
print("AI guesses ", guess)
else: #If the guess is the same (since we've checked both ranges already)
print("AI got it! ")
#Once the guess is equal to the randomNumber, we can output this line
print("AI guessed correctly ", numberOfGuesses, "guesses!")
Again, here's a screenshot of the code now with the AI algorithm included from a programming editor application.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 21
There were some lucky guesses along the way, but the algorithm did function as expected.
SUMMARY
In this lesson, we were introduced to algorithms as a logical step-by-step plan that is built to create a solution to a
problem. We also had a chance to see some conditional and repeatable elements in the sample Guessing Game
code. Finally, we saw that this basic guessing game can be enhanced by using an algorithm (AI) to guess the guessing
game that can produce consistent tries. It’s important to note that it’s not the underlying code that matters at this point,
but rather the logical steps behind the algorithm.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 22
Best of luck in your learning!
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
TERMS TO KNOW
Algorithm
A logical step-by-step plan that we need to build for solving a problem.
Comments
The “#” (hashtag) is used in Python code to identify a comment. Commented lines of code are ignored by the compiler
during run time. A programmer adds comments throughout the code to explain how the program or function works.
Module
A self-contained piece of code that can be used in different programs.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 23
Guide to Using Replit
by Sophia
WHAT'S COVERED
In this lesson, you will review the integrated development environment that will be used in this class for Python.
Specifically, this lesson covers:
1. Introduction to Replit
2. Running a Program
1. Introduction to Replit
When it comes to programming, there are different ways to write your code and run it. For many languages, you have the
option to use an Integrated Development Environment (IDE) to write your code. An IDE can be viewed as a text editor that has
additional functionality to allow developers to perform some additional tasks to simplify the workflow of the development
process. Different individuals and organizations have their preferences of what IDE they prefer.
Throughout this course, we’ll be using Replit for Python. It has some unique features in that it’s a tool that is completely run
through a browser. This means you can use it from any computer, tablet, or mobile device to write, build, and run your code.
Within Replit, you can deploy any of the code that you create externally with just a click. There’s no need to copy code or make
changes to the underlying environment. In addition, Replit can fully manage your environment that you use to build and run
your code. This means that you don’t have to worry about having the right version of Python or the right library, which is
prewritten code collections that you can use.
Even though you don’t need an account to use Replit, you should still create one. By doing so, you will be able to use all the
features that are required for this course.
STEP BY STEP
Step 1: To get started, you can access the following site: https://replit.com/signup
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 24
Step 3: Once you’re done creating your account, click on the “+ Create” button in the top right. This will allow you to create a
new Python project.
Note: Replit is a free professional and educational application, and is constantly evolving with updates based on members'
suggestions and language changes. As such, you may see different colors and/or icons other than what is depicted in the
following images. The functionality of the application remains consistent—just know that a color or icon may be different.
Step 4: The “Create a repl” window appears. Select “Python” from the dropdown languages. If you have used Replit for Python
coding previously, Python may appear at the top under “Favorites.”
Step 5: By default, a random project name will be generated in the “Title” field. Please change that to anything you wish the
project name to be.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 25
It’s important to note that by default, your repl will be public. This means that your project can be accessed by anyone on
the internet. Although this can be very useful when it comes to collaboration and sharing of code, you should be careful
not to use any personal identifiable information or passwords in any of your projects.
Once your project is created, the Replit IDE layout will appear.
The IDE consists of three (3) main panes and a “Run” button. Let’s cover these main elements in a left to right order.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 26
The left pane consists of the menu bar and the files and configuration pane. Each menu bar item will change what you see in
the pane. Although the menu bar has quite a few features, you don’t need to know what they all do. In most cases, when you
use an IDE, you will only use some its features rather than all of them.
This will display all of the files in your project and allow
Files you to add new files or folders into your project. This item
is the default menu bar item.
This isn’t one that you’ll need now, but if you need to track
your changes and roll back to prior versions (similar to
Version Control
“Track Changes” in MS Word), using this feature will allow
you to do so.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 27
To the right of the menu bar is the files and configuration pane. By default, this pane displays the “Files” menu bar information,
which displays the files that make up the project. Depending on what menu bar feature is selected, this pane will update
accordingly.
The middle pane is the code editor. This is the pane that you will spend the most time with, as this is where you’ll be writing
your Python code. The code editor has some unique features that we’ll get into. You may notice that in the files and
configuration pane, you have a main.py file listed. By default, when you create a Python project, Replit creates that main.py file.
The code that you enter is saved to that main.py file.
The last pane on the right is the output sandbox. This is the section where you can see your code run. All the output that your
code creates will display in that output sandbox. This pane also acts as a sandbox to run small pieces of code that we’ll take a
look at later.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 28
Above the main panes, you’ll see some added functionality, but the important one to be aware of is the run button in the
middle at the top. When you click on that green “Run” button, the code in the code editor pane will be built and will run in the
output sandbox pane.
CONCEPT TO KNOW
NOTE: Replit has the ability to change from a light to a dark theme. For ease of visibility, this course will depict the editor panel
from here on with the dark theme applied. To change themes, select the menu icon (it looks like a hamburger, three vertical
lines) in the top left-hand corner in Replit.
Once the menu opens, near the bottom you should see a "moon" icon. Selecting the icon will change the theme to dark. You
can switch back to the light theme here too.
Now the Replit application is on dark theme. Instead of just the output sandbox panel, all panels now display with a dark
background.
Again, moving forward, you will notice any code shown in the code editor pane on future lessons will have a dark background.
TERMS TO KNOW
Libraries/Library
Prewritten code collections that you can use when developing a program.
2. Running a Program
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 29
Now that you’ve had a tour of the Replit application, let’s get right into your first program. To get started, we can enter in some
code to test it and see what happens.
TRY IT
Directions: In the Replit code editor, enter the code below. When finished, select the “Run” button.
print("Hello World")
Notice that on the left of the command, a number is displayed. This is not part of the code and just indicates a line number. This
will be useful, as you’ll see in the next lesson.
Select the “Run” button at the top and you should see “Hello World” output in the right output sandbox pane.
What happened? The program was compiled and executed in Replit. In doing so—since our code didn’t have any errors—it
displayed the result of the print command on screen.
Congratulate yourself as you’ve written your first Python program, built it, and run it. That is how easy it is to run it!
SUMMARY
In this lesson, we set up a Replit IDE account and were introduced to the Replit IDE (Integrated Development
Environment). Replit will provide us with a working platform to try, write, test, and debug code as we progress through
this course. At the end of this lesson, we were able to write and run our very first Python program!
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
TERMS TO KNOW
Libraries/Library
Prewritten code collections that you can use when developing a program.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 30
Testing
by Sophia
WHAT'S COVERED
In this lesson, you will work through testing code and identify some common problems and issues. Specifically, this
lesson covers:
1. Syntax Errors
2. Comments
3. Best Practices With Comments
4. Edge and Corner Cases
1. Syntax Errors
It’s great when all goes well, but what happens when there are issues? Before we answer that, let’s explore the first line of
code we wrote in the last lesson.
print("Hello World")
The command print() is a function that allows Python to output data to the console (screen). Inside of the brackets, we have a
string enclosed in double-quotes. The quotes can be single or double, but they must be the same, otherwise you will get an
error.
EXAMPLE
For example, this could be:
print("Hello World")
as well as this:
print('Hello World')
TRY IT
print('Hello World")
Directions: Then, select the Run button at the top.
First, in the code editor pane, there is a red squiggly on the closing bracket ).
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 31
Second, in the output sandbox, after you selected the Run button, you received an error that looks like this:
The red squiggly line indicates that it detected a syntax error. A syntax error means that you have violated the “grammar” rules
of Python. Python does its best to point right at the line and character where it noticed it was confused. This is a good place to
start looking for errors in your code. It may not always be exactly where the error is detected, but it's a good place to start. In
the output console, you will also see more details about which file and line the error is on. In the code editor, you should see
the line numbers to the left of the code. It’s important to note that these numbers are not part of the code.
The only tricky bit of syntax errors is that sometimes the mistake that needs fixing is actually earlier in the program than where
Python noticed it was confused. So again, the line and character that Python indicates in a syntax error may just be a starting
point for your investigation.
Python will also inform you what the potential errors are. With any error message, if you’re unsure of what it means, you can
always copy it into Google to learn what the potential issue(s) could be. This is a good step to follow if you’re not sure about
what the error represents for any programming language.
Another important thing to note is that if you see multiple errors (which is quite common in larger programs), you should fix the
issues from the top down. In many instances, an issue at the top of the error list could seemingly show that there are many
more errors than there really are. Don’t worry about the number of errors; put your focus on the first one.
Remember we noted that we needed the quotes around the literal string. If we don’t use quotes around the literal string,
Python will assume that it is a variable or another keyword. We will get into that in Challenge 2.
TERMS TO KNOW
print()
The print() function allows Python to output data to the console (screen).
Syntax Error
A syntax error means that you have violated the “grammar” rules of Python.
2. Comments
It’s commonplace to see developers add in notes or comments in the code to explain what the code is doing for both
themselves and for other developers who review the code later on. In order to add a comment, you would start the comment
with a #. Then, Python will ignore everything else on the line.
TRY IT
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 32
#This code outputs Hello World 5 times
print("Hello World")
print("Hello World")
print("Hello World")
print("Hello World")
print("Hello World")
Notice that after running the code, the code does not produce any errors, because Python simply ignores anything after the #.
We could have a comment after a line as well.
EXAMPLE
#This code outputs Hello World 5 times
print("Hello World")
print("Hello World")
print("Hello World") #The third output line
print("Hello World")
print("Hello World")
Developers may also use the # to temporarily remove lines. There may be certain parts of the code that aren’t functioning and
need to be tested further. For example, let’s add in an error with the missing quotes:
If we didn’t know how to fix the issue and the line didn’t affect the rest of the code, we can simply comment out the line as
shown below:
TRY IT
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 33
print("Hello World")
#print(Hello World)
print("Hello World")
print("Hello World")
Since the third line was commented out, the line wasn’t output. It’s not quite obvious, so let’s change the output slightly:
TRY IT
EXAMPLE
Let’s take a look at the following program, which can feel a bit daunting:
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 34
def max_of_two( firstNumber, secondNumber ):
if firstNumber > secondNumber:
return firstNumber
return secondNumber
def max_of_three( firstNumber, secondNumber, thirdNumber ):
return max_of_two( firstNumber, max_of_two( secondNumber, thirdNumber ))
print(max_of_three(20, 30, -10))
In looking at the program, can you guess what it's doing? Even if you did, it probably took you a bit of time to figure it out. If you
have to take that extra time each time you evaluated a program, it would probably add up quite quickly. Let’s take the program
and add on some of those comments as a starting point:
EXAMPLE
#Author: Sophia
#Created Date: August, 21, 2021
#Description: This program has two functions to find the maximum
#value of three numbers.
#Example of usage: print(max_of_three(20, 30, -10))
#Result: function returns 30
Now, we do have two separate functions ( max_of_two and max_of three ). Don’t worry if you don’t know what those are yet;
for now, think of them as small, reusable pieces of code. Rather than redeveloping everything from scratch each time, you can
make use of these functions later on. Rather than explain what the code does directly, see if you can figure it out based on the
comments that are added:
EXAMPLE
#Author: Sophia
#Created Date: August, 21, 2021
#Description: This program has two functions to find the maximum
#value of three numbers.
#Example of usage: print(max_of_three(20, 30, -10))
#Result: function returns 30
#Function: max_of_two
#Purpose: This function accepts two numbers, compares them,
#and returns the value that is larger.
def max_of_two( firstNumber, secondNumber ):
if firstNumber > secondNumber:
return firstNumber
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 35
return secondNumber
#Function: max_of_three
#Purpose: This function accepts three numbers and sends the second and third
#numbers to max_of_two. It then takes the result of that comparison to
#send the first number and the result to get the larger value
#of all three.
def max_of_three( firstNumber, secondNumber, thirdNumber ):
return max_of_two( firstNumber, max_of_two( secondNumber, thirdNumber ) )
#Testing the function max_of_three
print(max_of_three(20, 30, -10))
Even though you may not understand the logic of the code, you get the gist of what the code is meant to do.
TRY IT
Directions: In Replit, give it a try with the following code with a test to see if it functioned as you expected it to: Note: If you copy
and paste this code in Replit, make sure to indent the functions where they are below. For example, if firstNumber >
secondNumer: is indented once (typically 2 spaces), return firstNumber is indented twice (typically 4 spaces). The
importance of indentations will be discussed in a later tutorial.
#Author: Sophia
#Created Date: August, 21, 2021
#Description: This program has two functions to find the maximum
#value of three numbers.
#Example of usage: print(max_of_three(20, 30, -10))
#Result: function returns 30
#Function: max_of_two
#Purpose: This function accepts two numbers, compares them,
#and returns the value that is larger.
def max_of_two( firstNumber, secondNumber ):
if firstNumber > secondNumber:
return firstNumber
return secondNumber
#Function: max_of_three
#Purpose: This function accepts three numbers and sends the second and third
#numbers to max_of_two. It then takes the result of that comparison to
#send the first number and the result to get the larger value
#of all three.
def max_of_three( firstNumber, secondNumber, thirdNumber ):
return max_of_two( firstNumber, max_of_two( secondNumber, thirdNumber ) )
#Testing the function max_of_three
print(max_of_three(20, 30, -10))
Try to change around the values that were being passed in as well. Were the results what you expected to see?
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 36
Whenever we have a program, we want to make sure that it works correctly logically. Although we can’t assume every
potential input, it’s generally a good idea to also test edge and corner cases. The edge cases are values that are at the end of
a testing range.
Let’s take the following program that should take in a score for an exam. If the score is between 90 and 100, it should tell the
student that they received an A. If the score is between 80 and 89, it should tell the student that they received a B. If the score
is between 70 and 79, it should tell the student that they received a C. Any grade less than 70 should tell the student that they
did not pass the exam.
As such, this was the (flawed) program that was created for this request:
EXAMPLE
All of these seem to work as expected. However, all of these tests are interior tests. The interior tests are test values that are
within a specific range where the precise values that we entered within that range did not matter. In our case, we tested 92, 93
and 94, which fall in the same range. Although it is important to have a test of the interior tests, we should also be testing edge
cases, or the values at the beginning or the end of the range, to ensure that the program works. Let’s try to enter in 100, as that
is at the end of the first range, and see what happens.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 37
Oops! You’d expect a student that had a perfect grade to have the same congratulatory message as the one that had a 94,
right? We’ll dig into the code a bit further in later tutorials, but the issue here is that in the check, the score doesn’t include 100;
it only checks if the score is less than 100. As a quick fix, we’ll change that second line.
EXAMPLE
Success! Well, for now. We have to continue testing all of the other edge and corner cases as well. A corner case is when the
value you are testing is in between two edge cases. In our scenario, a value of 90 and 80 would be considered corner cases,
as they are in between those two edge cases. Let’s see what happens if we enter in 90.
Oops! Similar to our check on 100, we need to ensure that the value 90 is part of one of the ranges. At this point, 90 is not in
either range. Let’s go ahead to do the same thing as we did on the 100 and change line 4 to include 90.
EXAMPLE
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 38
That’s not quite right, as a score of 90 should be an A. Instead, we should have changed line 2 to include 90 as part of the
range.
EXAMPLE
We’ll also need to do the same thing for the next two conditions as well, so let’s fix those issues.
EXAMPLE
Directions: Enter the fixed code above into Replit, making sure to indent the print functions.
Go ahead and test those corner and edge cases within that range and see what happens. Once you’ve done so, try to consider
what happens if the user enters in 101 or -1, which are on the edge cases of the entire program. With a negative number, having
a note that the user didn’t pass the example is acceptable. However, if the number is set to a value larger than 100, it’s most
likely a larger error that we have to handle.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 39
Try to think about how you could handle that scenario. What should the result be? Should the user be informed that they
entered an incorrect value?
TERMS TO KNOW
Edge Case
Values that are at the end of a testing range.
Interior Test
Test values that are within a specific range where the precise values that we entered within that range did not matter.
Corner Case
The value you are testing is in between two edge cases.
SUMMARY
In this lesson, we learned what a syntax error is and how Python does its best at helping us identify the right line and
character where it notices a violation of the “grammar” rules. We then looked at how to create comments within code
to help with testing and documenting, and we identified some of the best practices for commenting. Finally, we
learned how to test a program using interior testing and testing values at edge and corner cases.
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
TERMS TO KNOW
Corner Case
The value you are testing is in between two edge cases.
Edge Case
Values that are at the end of a testing range.
Interior Test
Test values that are within a specific range where the precise values that we entered within that range did not matter.
Syntax Error
A syntax error means that you have violated the “grammar” rules of Python.
print( )
The print() function allows Python to output data to the console (screen).
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 40
Data Types Introduction
by Sophia
WHAT'S COVERED
In this lesson, you will learn about values, variables and the basic data types used in Python. Specifically, this lesson
covers:
1. Values and Variables
2. Python Basic Data Types
If you're not sure what type a value has, the interpreter can tell you by putting the variable in a function named type() . As
you’d expect, it will tell you what the type of a variable is:
EXAMPLE
print(type("Hello World"))
In the output, “Hello World” is identified as a class string
We’ve mentioned variables a few times so far, but in essence, they are containers we use to store data values. We need these
variables so the programs we write can change as the program executes. Unlike many other languages, you do not need to
define the data type when you assign a value to your variable. This is unique to Python, but it also forces you to think about the
data types and the variables if you want to make use of them later on, because the results may not be what you intended them
to be. In Python, the variable does not need to be declared or defined in advance. With Python, we use an assignment
operator to assign a value to a variable. We can simply do that using the = operator (equal sign).
EXAMPLE
myVar = 1
What this will do is set the variable myVar to a value of 1. Once this is done, we can then use myVar in a statement (a unit of
code that the Python interpreter can execute) or an expression (a combination of values, variables, and operators) where the
value that’s stored in myVar would be output, such as the following:
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 41
EXAMPLE
myVar = 1
print(myVar)
Here is the output.
Later on, if we wanted to change the value of myVar and use it again, the new value would be changed instead.
EXAMPLE
myVar = 1
print(myVar)
myVar = 2
print(myVar)
The variable myVar has changed.
CONCEPT TO KNOW
Since they are case sensitive, all of these would reference different variables due to the case sensitivity.
EXAMPLE
myVar="1"
MYVAR="2"
myvar="3"
MyVar="4"
These are also legal variable names as they follow the variable naming rules.
EXAMPLE
_MyVar="5"
myVar2="6"
Let’s see what this looks like if we output them all.
EXAMPLE
myVar="1"
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 42
MYVAR="2"
myvar="3"
MyVar="4"
_MyVar="5"
myVar2="6"
print(myVar, MYVAR, myvar, MyVar, _MyVar, myVar2)
Looks like they all worked.
It’s important to note that even though we can create different variables in the same program with the same name but different
cases, it’s generally a bad practice. It would be confusing to you and anyone else that’s reviewing the code.
To you, or to someone else especially, these examples could cause confusion if they are all used in the same program.
EXAMPLE
myVar
mYVar
MYVAR
These, on the other hand, are illegal variable names:
EXAMPLE
2myVar – illegal due to it starting with a number.
my-var – illegal due to it having a "-". Only letters, numbers and underscores are permitted.
My var – illegal due to it having a space between My and var. Only letters, numbers, and underscores are permitted.
It’s always important to name our variables with names that are descriptive enough to indicate what they are being used for.
There are also situations where you may have variables that use multiple words as part of the naming. There are certain
techniques that can make it easier to follow.
Camel Case:
Camel case is one of the most widely used practices of combining phrases without spaces (remember a Python variable
cannot contain spaces). We’ve used camel case in our examples so far, where each word except the first word starts with a
capital letter.
EXAMPLE
Examples of camel case:
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 43
myVar
myVarForLaterUse
Even though this type of case is seen extensively in programming, you have likely seen this in the non-programming world as
well. Think of iPhone or eBay. That’s right—they use camel case too.
Pascal Case:
There’s also Pascal case, which is similar to camel case, except the first word also starts with a capital letter.
EXAMPLE
Examples of Pascal case:
MyVar
MyVarForLaterUse
Snake Case:
One last option is snake case, where all words are lowercase but separated by an underscore.
EXAMPLE
Examples of snake case:
my_var
my_var_for_later_use
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 44
It doesn't matter which approach you use, as long as you’re consistent.
TERMS TO KNOW
Value
One of the basic units of data, like a number or string, that a program manipulates.
=
The = operator (equal sign) is an assignment operator that is used to assign values to variables.
Statement
A unit of code that the Python interpreter can execute.
Expression
A combination of values, variables, and operators.
Camel Case
Combining words where each word except the first word will start with a capital letter.
Pascal Case
Combining words where each word starts with a capital letter.
Snake Case
Combining words where each word is separated by an underscore and all of the words are in lowercase.
Text
Numeric
Boolean
EXAMPLE
An example of a string would be:
myVar="Hello World"
Numeric Type Category
Within the numeric type, we have three main built-in data types. These are int , float , and complex.
int refers to an integer or a whole number. It can either be a positive or a negative number, but it does not have any decimals.
EXAMPLE
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 45
An example of an integer would be:
myInt = 1
myOtherInt = -200
float refers to a floating-point number. It is a number that can be positive or negative and uses decimal values.
EXAMPLE
An example of a float would be:
myFloat = 3.141517
MyOtherFloat = -20.1
A complex number is the sum of a real number and an imaginary number. This is one that we won’t get into. They are written
with the character j, which is the imaginary part:
EXAMPLE
An example of a complex would be:
myComplex = 20+4j
myOtherComplex = 6j
Boolean Type Category
The boolean type category just has the bool data type. This type can only have one of two values—True or False. These
values are also considered numeric values, where True is equal to 1 and False is equal to 0.
Beyond these common basic types, there are other advanced, built-in data types that we’ll cover later in the course. These
include:
These data types are more complex and each have specific uses.
TERMS TO KNOW
Str
A text data type consisting of characters that are enclosed in either single or double quotes.
Int
A numeric data type consisting of an integer or a whole number. It can either be a positive or a negative number but it does not
have any decimals.
Float
A numeric data type referring to a floating point number. It is a number that can be positive or negative and uses decimal
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 46
values.
Complex
A numeric data type consisting of a number that is the sum of a real number and an imaginary number.
Bool
A boolean data type consisting of a value of either True or False.
SUMMARY
In this lesson, we learned more about values and variables, including how a value is one of the basic things a program
works with, like a letter or number. We discussed that the variables hold values and can change values within a
program. We learned that variables need to be named appropriately based on some “rules” and that their names
should be meaningful. We also demonstrated the basics of writing variables in different case structures. Finally, we
learned about Python basic data types including text, numeric, and boolean.
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
TERMS TO KNOW
=
The = operator (equal sign) is an assignment operator that is used to assign values to variables.
Bool
A boolean data type consisting of a value of either True or False.
Camel Case
Combining words where each word except the first word will start with a capital letter.
Complex
A numeric data type consisting of a number that is the sum of a real number and an imaginary number.
Expression
A combination of values, variables, and operators.
Float
A numeric data type referring to a floating point number. It is a number that can be positive or negative and uses decimal
values.
Int
A numeric data type consisting of an integer or a whole number. It can either be a positive or a negative number but it
does not have any decimals.
Pascal Case
Combining words where each word starts with a capital letter.
Snake Case
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 47
Combining words where each word is separated by an underscore and all of the words are in lowercase.
Statement
A unit of code that the Python interpreter can execute.
Str
A text data type consisting of characters that are enclosed in either single or double quotes.
Value
One of the basic units of data, like a number or string, that a program manipulates.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 48
Using Integers and Floats
by Sophia
WHAT'S COVERED
In this lesson, you will learn about using integer and float variables and values. Specifically, this lesson covers:
1. Integers and Number Systems
2. Floating-Point Numbers
EXAMPLE
For example, all of these are integers:
myFirstInt = 100
mySecondInt = 0
myThirdInt = -999
Something unique with how Python uses the integer or int data type is that there is no limit to how long the integer value can
be. It’s only constrained by the amount of memory on your computer. So, you could set an int variable like:
myInt = 123456789123456789123456789123456789123456789123456789
CONCEPT TO KNOW
By default, any integer value without a prefix indicates that it is a base 10 number. A prefix is a set of characters prior to the
integer value that indicates that the integer is of another base type, such as 0b for base 2, 0o for base 8, or 0x for base 16.
Most individuals may only be familiar with base 10 number systems. Base 10 numbers are also called decimal values; this
represents any number using 10 digits that go from 0 to 9. Base 2 numbers are called binary numbers and represent numbers
using 2 digits with a 0 or a 1. This is important as computers store everything as 0s and 1s behind the scenes. There are also
base 8 numbers called octal, which represent numbers using 8 digits going from 0 to 7. Lastly, we have base 16 numbers or
hexadecimal. These represent any number using 10 digits and 6 characters going from 0 to 9 and then A, B, C, D, E, and F.
Since we’re most familiar with the base 10 (decimal) numbers, let's look at how we write our numbers.
We start by writing from 0 and then go up to 9. Once we’ve used up all of our symbols, we add another symbol to the left and
make the right symbol a 0, which is how we go from 9 to 10. Then, we go again, until we’ve used up all of our symbols on the
right side, and then we increase the symbol to the left of it by one symbol, which goes from 19 to 20. We keep following that
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 49
pattern until we’ve used up all of the symbols at 99. To move up, we make both of them 0 and add 1 to the left to have 100, and
keep going there.
When we have 10 different symbols (0 to 9 in this case), we have each position worth 10 times more than the prior one, as you’ll
see in this quick example:
EXAMPLE
____1
___10
__100
_1000
10000
In essence, if we have a number like 483, we break it down into separate parts:
This may seem obvious, but it is important because it also applies to other number systems.
For example, with binary, we only have two digits that represent a number with 0 and 1. Then we’re out of symbols, so we have
to apply the same rules as the decimal system.
We start with 0 and then 1. Next, we make the right digit a 0 and add 1 to the left, meaning that our next number is ‘10’. Then we
move the right digit to the next item, which is now 11. So, let’s see what numbers we have so far:
EXAMPLE
0, 1, 10, 11
What happens next? We do the same thing as we did for the decimals, since we’re out of symbols. We put 0s in both of those
places and put a 1 at the left, so, 100. The binary system is based on 2 digits, and as such, each position is worth two more
times than the prior position. It is similar to reading numbers in decimal, but instead of each number being 10 times the next,
it’s only 2 times.
EXAMPLE
For the conversion to decimal, these are the binary values:
Decimal Binary
0 0
1 1
2 10
3 11
4 100
5 101
6 110
7 111
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 50
8 1000
9 1001
For larger numbers, the binary system continues to add a digit to the left that is 2 times the amount of the digit to its right.
EXAMPLE
Here is a breakdown of the decimal number 563:
Binary 1 0 0 0 1 1 0 0 1 1
512 + 32 + 16 + 2 + 1 = 563
You can see how the pattern functions, and it works the same for octal and hexadecimal numbers. With hexadecimal numbers,
we have 10 digits and 6 letters to represent the values. Let’s expand our table to include hexadecimal and octal numbers and
run it up to decimal 30:
EXAMPLE
Decimal (Base 10) Binary (Base 2) Octal (Base 8) Hexidecimal (Base 16)
0 0 0 0
1 1 1 1
2 10 2 2
3 11 3 3
4 100 4 4
5 101 5 5
6 110 6 6
7 111 7 7
8 1000 10 8
9 1001 11 9
10 1010 12 A
11 1011 13 B
12 1100 14 C
13 1101 15 D
14 1110 16 E
15 1111 17 F
16 10000 20 10
17 10001 21 11
18 10010 22 12
19 10011 23 13
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 51
20 10100 24 14
21 10101 25 15
22 10110 26 16
23 10111 27 17
24 11000 30 18
25 11001 31 19
26 11010 32 1A
27 11011 33 1B
28 11100 34 1C
29 11101 35 1D
30 11110 36 1E
To represent an integer in a different number system than decimal, we need to add a prefix.
For binary numbers, we add a prefix of 0b (number zero and letter b). For octal numbers, we add a prefix of 0o (number zero
and letter o). For hexadecimal numbers, we add a prefix of 0x (number zero and letter x).
Using the table that we have above, let’s output decimal 16 and its equivalent to see what the output results look like.
EXAMPLE
MyDecimalNum = 16
myBinaryNum = 0b10000
myOctNum = 0o20
myHexNum = 0x10
print("Decimal", MyDecimalNum)
print("Binary", myBinaryNum)
print("Octal", myOctNum)
print("Hexadecimal", myHexNum)
As expected, the output for all of them is the same:
TERMS TO KNOW
Base 10 Numbers
Also called decimal values, these are numbers using 10 digits that go from 0 to 9.
Base 2 Numbers
Also called binary numbers, these are numbers using two digits, 0 or 1.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 52
Base 8 Numbers
Also called octal numbers, these are numbers using 8 digits, going from 0 to 7.
Base 16 Numbers
Also called hexadecimal numbers, these are any numbers using 10 digits (0 to 9) and 6 letters (A, B, C, D, E, and F).
2. Floating-Point Numbers
The data type float represents a floating-point number. Float values generally have a decimal point. This is the key
difference between an int and the float in Python. Float values can be positive or negative.
EXAMPLE
For example, these would all be valid decimal values:
myFirstFloat = 8.2
mySecondFloat = 0.0000001
myThirdFloat = -192.12387
The type() function takes a value or variable as input and returns the type of the value or variable. This is helpful with
debugging since it shows what type the variable is set to. We’ll talk about debugging in a later lesson. For now, we can check if
a variable is set up as a float by using the type() function and printing it out.
myFirstFloat = 8.2
print(type(myFirstFloat))
The type() function identifies the value as float .
Assigning a value to a float is the same as with an int except the value being set contains a decimal point.
TERM TO KNOW
type()
The type() function takes a value or variable as input and returns the type of the value or variable.
SUMMARY
In this lesson, we learned more about integers and various numbering systems including binary (base 2) and decimal
(base 10). We discussed that by default, Python treats an integer as a base 10 number unless there is a specific prefix
included, in which case we can switch to other bases. Finally, we explored that a float data type represents a floating-
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 53
point number that generally has a decimal point and can be either a positive or negative value.
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
TERMS TO KNOW
Base 10 Numbers
Also called decimal values, these are numbers using 10 digits that go from 0 to 9.
Base 16 Numbers
Also called hexadecimal numbers, these are any numbers using 10 digits (0 to 9) and 6 letters (A, B, C, D, E, and F).
Base 2 Numbers
Also called binary numbers, these are numbers using two digits, 0 or 1.
Base 8 Numbers
Also called octal numbers, these are numbers using 8 digits, going from 0 to 7.
type()
The type() function takes a value or variable as input and returns the type of the value or variable.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 54
Operators and Operands
by Sophia
WHAT'S COVERED
In this lesson, you will learn how to use operators to perform mathematical operations on integers and float variables.
Specifically, this lesson covers:
1. Common Mathematical Operators
2. Exponent and Modulus Operator
3. Order of Operations
Name Operator
Add +
Subtract -
Multiply *
Divide /
Exponent **
These operators are the same in most programming languages. To use them, we’ll use an expression. An expression is a
combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the
following are all legal expressions (assuming that the variable x has been assigned a value):
EXAMPLE
17
x
x + 17
In a script, an expression all by itself doesn’t do anything. This is a common source of confusion for beginners.
TRY IT
Directions: For an example, enter the following code into Replit and run it.
x = 10
x + 17
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 55
As expected, nothing happens.
Directions: Now enter this code into Replit and run it.
x = 10
print(x + 17)
You should be seeing 27 as the output.
Rather than just output the expression, we would generally set it to a variable and then output the variable.
x = 10
result = x + 17
print(result)
So we would see an output of 27.
There are some instances where we need to perform operations on the same variable. For example, we may need to add a
value to it or deduct a value. The code may look like this.
myValue = 2
myValue = myValue + 2
print(myValue)
Other Assignment Operators
In Python, there is another way to perform operations on variables using some basic assignment operators. We have already
been using the most basic assignment operator, the = operator (equal sign). However, there are more available. Here are a
few that work with mathematical operations:
Note: The term operand is used to describe any object that is capable of being manipulated.
= Assigns the value of the right operand to the left operand. x=5 x=5
Add and Assign: Adds the right operand value with the left operand value
+= x += y 5 += 5 will be 10
and then assigns to the left operand.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 56
Subtract AND: Subtracts the right operand value from the left operand
-= x -= y 5 -= 3 will be 2
value and then assigns to the left operand.
Multiply AND: Multiplies the right operand value with the left operand value
*= x *= y 5 *= 5 will be 25
and then assigns to the left operand.
Divide AND: Divides the left operand value by the right operand value and 5 /= 3 will be
/= x /= y
then assigns to the left operand. 1.66666
We can simplify the previous operation of myValue = myValue + 2 with the add and assign operator like below:
myValue = 2
myValue += 2
print(myValue)
This works for all of the operators to modify the variable.
TRY IT
Directions: Enter the following code into Replit and run it.
myValue = 2
print(myValue)
myValue += 2
print(myValue)
myValue *= 2
print(myValue)
myValue -= 3
print(myValue)
myValue /= 2
print(myValue)
You should see the following output:
TRY IT
Directions: Try changing the initial myValue value. Does each assignment operation make sense? Try changing some of the
numeric values in each operation and run the code snippet.
10 ** 2
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 57
Or, in code using the variables and then output, as shown below:
TRY IT
Directions: Enter the following code into Replit and run it.
base=10
exponent=2
result = base ** exponent
print(result)
You should see the following output:
The modulus operator works on integers and yields the remainder when the first operand is divided by the second. In Python,
the modulus operator is a percent sign (%). The syntax is the same as for other operators.
TRY IT
Directions: Enter the following code into Replit and run it.
remainder = 7 % 3
print(remainder)
You should see the following output:
The modulus operator turns out to be surprisingly useful. For example, you can check whether one number is divisible by
another: if x % y is zero, then x is divisible by y.
TRY IT
Directions: Enter the following code into Replit and run it.
remainder = 99 % 3
print(remainder)
You should see the following output:
You can also extract the right-most digit or digits from a number. For example, x % 10 yields the right-most digit of x (in base 10).
Similarly, x % 100 yields the last two digits.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 58
TRY IT
Directions: Enter the following code into Replit and run it.
remainder = 6849 % 10
print(remainder)
3. Order of Operations
We can also add multiple different operators in a single statement. When more than one operator appears in an expression,
the order of evaluation depends on the rules of precedence.
For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the
rules.
PEMDAS Definitions
P Parentheses have the highest precedence and can be used to force an expression to evaluate in the
(Parentheses) order you want. Since expressions in parentheses are evaluated first:
2 * (3-1) is 4, and
(1+1)**(5-2) is 8.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 59
You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even if it
doesn’t change the result.
Multiplication and Division have the same precedence, which is higher than Addition and Subtraction,
MD
which also have the same precedence, so:
(Multiplication and
2*3-1 is 5, not 4, and
Division)
6+4/2 is 8, not 5.
AS
Operators with the same precedence are evaluated from left to right, so:
(Addition and
5-3-1 is 1, not 3, because 5-3 happens first and then 1 is subtracted from 2.
Subtraction)
If you’re ever unsure about the order of operations, always put parentheses in your expressions to make sure the
computations are performed in the order you intend.
TRY IT
Directions: Below are a few examples to work out in Replit. This will help you see how the order of operations is important.
Read the example and enter the example's code, replacing the underlined area with the code that will produce the correct
answer. The solutions are at the bottom below the Summary.
Example 1:
Let’s say we have 20 pizza slices. You’ve eaten two and then gave half of the pizza slices to your work. How many pizza slices
are left? How would you structure that calculation?
pizzaSlices = 20
remainingSlices = your code here
print(remainingSlices)
Example 2:
Let’s say that you’ve put in a $300 investment into a new company. The company had to use a third of the initial funds for
marketing. Then, they had to take $50 for product development. After that, they were able to successfully deploy their project
and gave 5 times the remaining funds to each investor. How much money did they give back to you?
investment = 300
money = your code here
print(money)
Example 3: How much profit did you make from that initial investment?
investment = 300
profit = your code here
print(profit)
SUMMARY
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 60
In this lesson, we learned the common mathematical operators that Python can utilize to perform mathematical
operations on integers and float variables. We also discussed how the exponent and modulus operators work. We
saw that the order of operations is very important and how using the acronym PEMDAS is a useful way to remember
the rules. Finally, we had an opportunity to apply some calculations that follow the conventional mathematical order of
operations.
Example Solutions:
Example 1
pizzaSlices = 20
remainingSlices = ( pizzaSlices - 2) / 2
print(remainingSlices)
Example 2
investment = 300
money = (( investment * 2/3) - 50) * 5
print(money)
Example 3
investment = 300
profit = (( investment * 2/3) - 50) * 5 - investment
print(profit)
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 61
Using Strings
by Sophia
WHAT'S COVERED
In this lesson, you will learn about strings and how to use them. Specifically, this lesson covers:
1. More About Strings
2. Escaping Strings
3. Assigning Multiple Variables
TRY IT
myVar=1
print(myVar)
myVar="I am now a String"
print(myVar)
You should see the following output: myVar originally declared as an integer, then switched to a string.
Recall that a String is a string of text. This can come in many different forms:
CONCEPT TO KNOW
An empty string (“”) is a string that is identified but does not contain anything; it is essentially empty.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 62
Also recall that the use of literal strings are surrounded by quotation marks. You can use single quotes (') or double quotes (")
when you define strings, like the following:
EXAMPLE
But take care not to mismatch them, as that will not work and will raise an error.
Being able to switch them can be useful, especially if you want to have one of the quotes as part of the string. Observe what
happens if we use a single quote for the string and have a single quote in the string as well:
TRY IT
That’s not working quite right. The syntax error is pointing at the “s” or the character to the right of the issue. One approach is
to switch the outer quotes to double quotes:
TRY IT
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 63
myString1 = "It's working"
print(myString1)
Now the output should look correct.
TERM TO KNOW
Empty String
An empty string is a string that is identified but does not contain anything; it is essentially empty.
2. Escaping Strings
The previous example is not an ideal approach, as you could have a string that has both single quotes and double quotes in it.
EXAMPLE
Here is another example of a string using both types of quotes.
Rather, the better method is to escape the characters. In doing so, we can use any characters that would generally raise an
error. The escape character is a backslash \ followed by the character that we want to add. Using the same example from
above, we’ll add the backslash in front of the single quote:
EXAMPLE
Success with no errors! There are other important escape characters that you should be aware of, like the newline and tab that
can be placed in a string.
EXAMPLE
Instead of having these in separate print statements as shown below.
print("First Line.")
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 64
print("Second Line.")
print("Third Line.")
With output like this.
They can be combined in a single print statement using the \n for the new line, like this:
TRY IT
Directions: Try some of these other escape characters to see them in action in Replit:
Escape
Description Sample Code
Character
print("First Line.\nSecond
\n The \n adds a new line after each \n.
Line.\nThird Line.")
TERM TO KNOW
Escape Character
Special characters that when added to a string will allow quotes of a string to be escaped.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 65
TRY IT
On the flip side, you can also have it such that all of the variables are assigned to a single value.
SUMMARY
In this lesson, we learned more about strings and how literal string values should use quotes around them. We
learned how combining single and double quotes can create syntax issues. We identified that there may be times we
need both single and double quotes in a string and in that case, we can escape strings by using the escape character.
Finally, we learned how to assign multiple variables to strings and had a chance to try some out.
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
TERMS TO KNOW
Empty String
An empty string ("") is a string that is identified but does not contain anything; it is essentially empty.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 66
Escape Character
Special characters that when added to a string will allow quotes of a string to be escaped.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 67
String Operations
by Sophia
WHAT'S COVERED
In this lesson, you will learn about how to modify strings using basic operations. Specifically, this lesson covers:
1. Common Operations
2. Simple Data Conversion
1. Common Operations
One of the most common operations for strings is the use of concatenation. The concatenation operator should look familiar
to you as it is the + operator (plus sign). The + operator is the addition operator on integers; however, it can also function as a
concatenation operator when applied to string variables, which means it joins the variables by linking them end to end. An
error will appear if trying to use this operator on variables that are a mix of string and integer.
So, another way to put it is that with strings, this operator can combine values together to form a new one. The act of adding
one string to another with the + operator can be referred to as string concatenation.
TRY IT
myVar1 = 'Learning'
myVar2 = 'Python'
result = myVar1 + myVar2
print(result)
This should be the concatenated output.
Notice that the strings are concatenated, but there isn’t a space in between them. If we did want to add a space, we can simply
add the space in the concatenation.
TRY IT
myVar1 = 'Learning'
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 68
myVar2 = 'Python'
result = myVar1 + ' ' + myVar2
print(result)
Now with the space added, we see:
Let’s see what happens if we have the variables as integers (without quotes around the values).
TRY IT
myVar1 = 111
myVar2 = 222
result = myVar1 + myVar2
print(result)
With the following output.
We’ll see that the myVar1 was added to myVar2 , and the results of it as we expected. Now, let’s try this out again as strings,
by adding quotes around each of the values.
TRY IT
Directions: Now try the code changing the integers into strings.
myVar1 = '111'
myVar2 = '222'
result = myVar1 + myVar2
print(result)
The output of the string values.
As expected, since myVar1 and myVar2 are now strings, even though they contain numbers, they are concatenated together
and placed into the result variable.
Another operation with strings is the * (asterisk sign) or multiplication operator. The * operator is unique to Python as it can
multiply integers and can also be used as a replication operator with strings and integers (floats will not work). As a replication
operator, it will repeat (make a copy of) the variable based on the number of times it is multiplied by.
TRY IT
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 69
myString = 'Python is great'
result = myString * 5
print(result)
Output all on one line.
This may not be what we intended. Adding in the newline character will help us ensure that we have each string on a new line.
TRY IT
Python also provides a membership operator that can be used in strings. The in operator is a reserved keyword and used as a
membership operator that checks if the first operand is contained in the second. If it is contained, it returns true; otherwise, it
returns false. It can also be used to iterate through a sequence in a for loop. More on loops in later tutorials.
TRY IT
Directions: Let’s try the in operator. Add the following code to Replit.
stringToFind = 'some'
sentence = 'Python is quite a fun language to learn. There can be some great string functions to use.'
result = stringToFind in sentence
print(result)
We have stringToFind setup as a variable for the string that we want to find in the sentence. In this case, we are looking for
the word ‘some’.
If we had passed in a string that didn’t exist, it would return False. Let’s add a string we know is NOT in the sentence.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 70
Directions: Now try this stringToFind that we know is not in there.
stringToFind = 'grrrr'
sentence = 'Python is quite a fun language to learn. There can be some great string functions to use.'
result = stringToFind in sentence
print(result)
As expected, that string was not found.
We looked at the use of escape characters to add in a newline. However, we can also assign multiline strings without using the
newline character by using three double quotes or three single quotes.
TRY IT
Just be careful in Replit when you enter in a double quote or single quote, as Replit automatically adds in the second quote
when you enter in the first. In the next challenge, we’ll explore more string functions and methods.
TERMS TO KNOW
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 71
Concatenation
The operation of joining or merging two or more strings together.
+
The + operator (plus sign) is the addition operator on integers; however, it can also function as a concatenation operator when
applied to string variables, which means it joins the variables by linking them end to end. An error will appear if trying to use
this operator on variables that are a mix of string and integer.
*
The * operator (asterisk sign) or multiplication operator is unique to Python as it can multiply integers and can also be used as
a replication operator with strings and integers (floats will not work). As a replication operator, it will repeat (make a copy of)
the variable based on the number of times it is multiplied by.
in
The in operator is a reserved keyword and used as a membership operator that checks if the first operand is contained in the
second. If it is contained, it returns true; otherwise, it returns false. It can also be used to iterate through a sequence in a for
loop.
EXAMPLE
For example, let’s take the previous integer example.
myVar1 = 111
myVar2 = 222
result = myVar1 + myVar2
print(result)
That has 333 as the output.
If those variables were already set as integers, we can convert them to a string using the str function.
TRY IT
myVar1 = 111
myVar2 = 222
result = str(myVar1) + str(myVar2)
print(result)
Now we see the output as two strings concatenated.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 72
Likewise, if we had those variables as strings, we can convert them to an int using the int function.
myVar1 = '111'
myVar2 = '222'
result = myVar1 + myVar2
print(result)
Just a long string again.
Directions: Now try using the int function to convert the strings to integers and add them.
myVar1 = '111'
myVar2 = '222'
result = int(myVar1) + int(myVar2)
print(result)
As expected, the sum of the two integers.
SUMMARY
In this lesson, we learned about the common string operations, including concatenation, the asterisk operator, and the
membership operator in . We also learned how to do some simple data conversion using the str and int functions.
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
TERMS TO KNOW
*
The * operator (asterisk sign) or multiplication operator is unique to Python as it can multiply integers and can also be used
as a replication operator with strings and integers (floats will not work). As a replication operator, it will repeat (make a
copy of) the variable based on the number of times it is multiplied by.
+
The + operator (plus sign) is the addition operator on integers; however, it can also function as a concatenation operator
when applied to string variables, which means it joins the variables by linking them end to end. An error will appear if
trying to use this operator on variables that are a mix of string and integer.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 73
Concatenation
The operation of joining or merging two or more strings together.
in
The in operator is a reserved keyword and used as a membership operator that checks if the first operand is contained in
the second. If it is contained, it returns true; otherwise, it returns false. It can also be used to iterate through a sequence in
a for loop.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 74
Debugging Operations
by Sophia
WHAT'S COVERED
In this lesson, you will learn about some of the common errors with operations. Specifically, this lesson covers:
1. Common Variable Errors
2. Common Operations Errors
EXAMPLE
For example:
Using the words “class” and “yield” as variable names. These are Python reserved keywords.
Using “odd~job” and “US$” as variable names. These contain illegal characters like the ~ and $ characters.
So, if you put a space in a variable name, Python thinks it is two operands without an operator.
EXAMPLE
Reserved Words
Python has 35 reserved keywords that are used to recognize the structure of a program. Since they are reserved,
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 75
they cannot be used as variable names. These are the reserved words:
Let's see what happens if we try to use one of the reserved words as a variable name.
EXAMPLE
class = 'test'
We get an error on Replit's output sandbox screen when trying to compile it.
On Replit's code editor screen, we’ll also see the squiggly red line with the error.
The runtime error that you will most likely make is to use a variable before assigning it a value. You can run into this error if you
have a typo in the variable name.
EXAMPLE
principal = 327.68
rate = 5
interest = principle * rate
print(interest)
This produces an error on output.
As you’ll see here, we intended to have principal (PAL) instead of principle (PLE) when we were doing the calculation.
We can also run into an error if we simply did not assign a value to a variable before trying to use it. Those types of errors will
generate a NameError as seen above.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 76
EXAMPLE
principal = 327.68
interest = principal * rate
print(interest)
In this case, rate has not been assigned a value. However, we are trying to use it to calculate interest .
Don’t forget that variable names are case sensitive, so Principal and principal would not be the same.
EXAMPLE
Principal = 327.68
rate = 2
interest = principal * rate
print(interest)
Now principle is throwing an error.
Note that if you have the variable defined in both ways in a program, the issue becomes a logical error that you would have to
catch, as you won’t get an error while compiling.
EXAMPLE
Rate = 100
principal = 327.68
rate = 0
interest = principal * rate
print(interest)
In this case, we have rate and Rate . If we intended to use the Rate of 100 but instead used the rate of 0, this would run but
return the interest value of 0 instead of 32768.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 77
EXAMPLE
var1 = "3"
var2 = "4"
var3 = var1 + var2
print(var3)
What would you assume the results to be?
Oops, the reason for that is the double quotes, which makes them strings that are concatenated instead of added. Instead, we
want to ensure that if we intend to add the values, we don’t use quotes around them.
var1 = 3
var2 = 4
var3 = var1 + var2
print(var3)
Now the addition looks correct.
Another situation may be if we have a mixed scenario of using an operator on incompatible data types. This can create an
issue because Python doesn’t understand if we intended to concatenate the values or add them together since in this case,
one is a string and the other is an int. This will cause a TypeError.
EXAMPLE
var1 = 3
var2 = "4"
var3 = var1 + var2
print(var3)
Here is the expected error on output.
Another common error is a logical error with the order of operations. For example, if we had three grades and we wanted to
calculate the average, we would want to add the three grades and divide by 3. We may do something like the following:
EXAMPLE
grade1 = 86
grade2 = 100
grade3 = 72
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 78
average = grade1 + grade2 + grade3 / 3
print(average)
The output doesn't look correct.
That’s definitely an error due to the order of operations. What happened in this case is that grade3 / 3 occurred first. Then
grade1 was added to grade2 and the result of the grade3 / 3. We need to use parentheses to ensure that the grades are
added together first, before dividing them all by 3.
grade1 = 86
grade2 = 100
grade3 = 72
average = (grade1 + grade2 + grade3) / 3
print(average)
Now, this looks better.
Remember for mathematical operators, the acronym PEMDAS is a useful way to remember the rules.
PEMDAS Definitions
Parentheses have the highest precedence and can be used to force an expression to evaluate in the
order you want. Since expressions in parentheses are evaluated first:
P 2 * (3-1) is 4, and
(Parentheses) (1+1)**(5-2) is 8.
You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even if it
doesn’t change the result.
Multiplication and Division have the same precedence, which is higher than Addition and Subtraction,
MD
which also have the same precedence, so:
(Multiplication and
2*3-1 is 5, not 4, and
Division)
6+4/2 is 8, not 5.
AS
Operators with the same precedence are evaluated from left to right, so:
(Addition and
5-3-1 is 1, not 3, because the 5-3 happens first and then 1 is subtracted from 2.
Subtraction)
Remember with these logical errors Python has no way of knowing what you actually meant to write. You won’t get any error
messages—you simply get the wrong answer. It is always good to validate and double-check any calculations outside of
Python.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 79
SUMMARY
In this lesson, we learned about common variable errors, including spaces in variable names and using Python
reserved keywords as variables. We also learned some common operation errors, including mixing data types and
having an unexpected order of operations.
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 80
Coding Your First Program
by Sophia
WHAT'S COVERED
In this lesson, you will learn how to think like a developer and review what’s involved in the program development
process. Specifically, this lesson covers:
1. Mentalism Program
2. Validating and Debugging
1. Mentalism Program
For this first program, we’ll make use of the various parts of a program that we’ve looked at so far. Our goal will be to create a
program that can perform a mentalism magic trick in Python. Let’s first try it out on you—no programming yet!
Wow!
It’s important to note that the number that you originally chose doesn’t have any effect on the result at all. The only number that
mattered was the number that was added (the number 8 in our trick), as the result is half that number (the number 4). To ensure
that we have nice round numbers, the number that was added must be an even number. All the rest of the calculation was an
illusion to hide what was being done in the program. Viewing this in equation form may also help to reveal the “magic.” With x
as the number guessed, the math above yields:
((((x*2) + 8)/2) – x), and this simplifies to ((x + 4) – x), which equals 4.
What inputs do we have? We want to ask the person’s name. In this case, for our code, we don’t need to ask the person for the
number that they are guessing since that number doesn’t affect us directly. What we do need to do is generate a random even
number for the person to add.
Our processing will involve random number generation. For simplicity, we will first generate a random number between 1 and
5. That will be the final answer. The number that the person will have to add (to the number they are thinking of) will be that
number multiplied by 2, as it will need to be even.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 81
Our output will be letting the user know what number they have at the end of the calculations. Let’s see what that program
would look like:
TRY IT
Directions: Let’s try to add the following code snippets to Replit. We will explain what is happening before each snippet.
In this first line, we have a comment describing what the code is meant to do. This is good practice to start adding in these
comments to define what the code represents. We can tell it’s a comment with the # that starts the line.
#We are importing a module that we need to be able to generate random numbers
This next line is meant to import a specific module called random. There are some modules or pieces of code that are created
for you that you can make use of. The random module is one that allows you to generate pseudo-random numbers, which we’ll
use. Notice that the code and the comments will be in different colors in the editor. That may be different depending on your
settings in Replit.
import random
In this next set of lines, we’ll describe what it is that we’re intending to do as part of the program. Remember that the lines with
the # are comments which are not run by the program. Rather, they are for you as the programmer to explain what the code is
doing.
randomFinalNumber = random.randrange(1, 5)
numberToAdd = randomFinalNumber * 2
Next, we’ll define another variable called name . We’ll use the function input to wait on input from the user and have it set to the
variable name . Prior to that, it’ll prompt the user (without quotes) "Hello! What is your name?". Then, it will wait for the user to
enter a response. The response is then stored in the variable name that we’ve declared.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 82
answer = input("Ready for the next step? ")
print("Now, add...let's see...")
print(numberToAdd)
answer = input("Ready for the next step?")
print("Now, divide the number you have by 2.")
answer = input("Ready for the next step? ")
print("Now, subtract the original number that you thought about.")
answer = input("Ready for the last step? ")
Lastly, we’ll print the randomFinalNumber to the screen and watch the astonished user compare the same number, had they
been following the steps of the program.
TRY IT
Directions: Let's try this again. Enter the following code to Replit. Updates/changes for lines of code have comments after
them.
#We are importing a module that we need to be able to generate random numbers
import random
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 83
#We are creating a random even number between 2 and 10 by
#first randomizing an integer between 1 and 5. This will be our
#final number. The number to add will take this final number and multiply it by 2.
randomFinalNumber = random.randrange(1, 5)
numberToAdd = randomFinalNumber * 2
enteredNumber = int(input("Enter in a number between 1 and 10: ")) # this is a new line
print("Multiply the result by 2.")
The next new line we are adding starts the calculation. Here, we’re taking the enteredNumber that the user entered in and
multiplying it by 2 and setting it to the variable userNumber . Then, in the following line, we’ll be outputting to the screen what
that userNumber is currently set to.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 84
Finally, these last two lines of code will deduct the initial number that the user entered at the beginning of the code. Then, we’ll
be outputting to the screen what that userNumber is currently set to.
Once we are done, we can simply comment out the lines of code that shouldn’t be output to the screen.
TRY IT
Directions: Using Replit, make sure you comment out the lines of code used for testing (see what is commented out below) so
your testing variable does not show to the end-user.
#We are importing a module that we need to be able to generate random numbers
import random
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 85
answer = input("Ready for the next step? ")
print("Now, add...let's see...")
print(numberToAdd)
#userNumber = userNumber + numberToAdd
#print(">> userNumber at this step = " + str(userNumber))
answer = input("Ready for the next step?")
print("Now, divide the number you have by 2.")
answer = input("Ready for the next step? ")
#userNumber = userNumber / 2
#print(">> userNumber at this step = " + str(userNumber))
print("Now, subtract the original number that you thought about.")
answer = input("Ready for the last step? ")
TRY IT
Directions: Try removing the testing code from the main program and add it to the bottom like you see in the program below.
#We are importing a module that we need to be able to generate random numbers
import random
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 86
#Guessing the number
print("Well " +name +", let me read your mind...The number that you have right now is a....")
print(randomFinalNumber)
To see the final version of this program visit Sophia's Replit page.
SUMMARY
In this final lesson of Challenge 1.2, we had the chance to think like a developer while we reviewed the first coding
program, the Mentalism Program. We added code snippets of the program to Replit to test individually. We also had a
chance to validate and debug the program by outputting variables to the screen as the program progressed through
the code.
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 87
Functions and Methods Introduction
by Sophia
WHAT'S COVERED
In this lesson, you will learn how to use functions and methods in Python. Specifically, this lesson covers:
1. Functions
a. len() Function
b. int() Function
c. float() Function
d. str() Function
2. Built-In String Methods
a. .index() Method
b. .capitalize() Method
c. .lower() Method
d. .upper() Method
e. .swapcase() Method
f. .title() Method
1. Functions
A function is a section of code that runs when it is called. We have the ability to pass data into functions, through parameters,
and this data can then be used within the function. After the function has been processed, it can return data as an option,
although functions don’t need to do so. We are already familiar with the print function, where we output variables like the
following:
EXAMPLE
myFunction()
Data can be passed into functions as arguments. These arguments are specified within the parentheses. You will see the
terms parameter and argument used for information that is being passed into a function. A parameter is the actual variable
name(s) when we define a function definition.
Note: You do not need to worry about creating functions now, but it’s good to see how it is defined.
A function definition is the first line when we create a new function to be used in a program. An argument is the actual value(s)
being passed into the function when it is called. We can add in multiple arguments as long as the function supports it. We
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 88
would separate them by a comma.
EXAMPLE
Let’s look at an example to help clarify function items.
#first we define the function definition by using the reserved keyword “def” to define it
#then set up the function myFunction with three parameters firstName, middleInitial, and lastName.
#to end a function, we place a colon at the end
#here is where we call myFunction and pass it the actual values as arguments
myFunction("John", "R", "Doe")
Here is the snippet in the code editor screen:
Don’t worry too much if you’re still unsure about what all of the components of creating your own functions are, as we’ll
continue to cover them later on.
Note: When you do review Python documentation, you’ll see the arguments often shortened as “args” in the documentation
about Python.
There are many other built-in functions that we can use as part of the string. So, rather than immediately printing a string out,
we can do other things. Let’s look at a few functions.
EXAMPLE
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 89
The len() function counts all characters, including punctuation and spaces, which is why it prints out 14.
In past lessons, we’ve used data type functions to change variables. This is called type-casting, or casting. Casting is when you
convert a variable’s value from one data type to another. It is important to understand what they do since these functions allow
us to convert data from one type to another so that we can perform the right operations on the data. For example, if we
wanted to add 1 + 1, we want the result to be 2. However, if we wanted the result to be 11 using the same values, we would need
to cast them to a string first so that the values are concatenated rather than added.
EXAMPLE
print(int(100))
print(int(2.95))
print(int("200"))
Here is the output once the code is run.
It’s important to note that the int for float removes the decimals rather than rounding the decimals. For example, the result of
the int(2.95) is 2 and not 3.
EXAMPLE
print(float(100))
print(float(2.95))
print(float("200"))
Here is the output once the code is run.
EXAMPLE
print(str(100))
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 90
print(str(2.95))
print(str("200"))
Here is the output once the code is run.
TRY IT
Now that you have had a chance to see a few of the built-in functions in Python, try your hand at a few of them.
Directions: Using Replit, try using the functions you just learned in the examples.
TERMS TO KNOW
Functions
A function is a piece of code that runs when it is called. We have the ability to pass in data into those functions, which are called
parameters.
Parameter
A parameter is the actual variable name(s) when we define a function definition.
Argument
An argument is an actual value(s) that is being passed into the function when it is being called.
len()
The len() function counts all characters, including punctuation and spaces.
Casting (or Type-Casting) Casting is when you convert a variable’s value from one data type to another.
int()
The int() function creates an integer number from an integer literal, a float literal (by removing all of the decimals), or a
string literal (assuming the string represents a whole number).
float()
The float() function can create a float number from an integer literal, float literal, or a string literal as long as the string has a
float or an integer.
str()
The str() function creates a string from various data types, including strings, integer literals, and float literals.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 91
In the same way that a function is used, a method is called to perform a specific task. However, it is called by using the object
name, a period, and the method name.
There are over 40 String Methods in Python! To learn more about what they are and their functions, check out: Python String
Methods
That is a bunch of methods! We can’t cover them all now, but we can show a few in the examples below.
EXAMPLE
This method prints out 5 because the first occurrence of the letter "n" ends up being 5 characters away from the first character.
This may seem confusing, as the first "n" is the sixth character. In most programming languages, including Python, the first
position starts at 0 rather than 1. This means that the index of the last character of the string will be the length of the string
minus 1.
Using the same string, this table will show the indices for each character in the string.
P y t h o n i s f u n !
0 1 2 3 4 5 6 7 8 9 10 11 12 13
It is important to note that the index function only finds the first instance of the character. Even though the second "n" appears
in the 12th index, 5 is returned.
EXAMPLE
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 92
2b. .lower() Method
The .lower() method will convert all of the characters of a string to lowercase, including the first character.
EXAMPLE
EXAMPLE
EXAMPLE
EXAMPLE
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 93
TRY IT
Now that you have had a chance to see a few of the built-in methods in Python, see if you can test some you just learned.
Directions: Using Replit, try using the methods you just learned in the examples.
TERMS TO KNOW
Object An object is an instance of a class that has properties and methods that are encapsulated or part of it.
Methods Methods are a specialized type of procedure that is directly associated with an object and called to perform a
specific task by using the object name, a period, and then the method name.
.index() The .index() method can find the location of a character or a string within another string.
.capitalize() The .capitalize() method will convert the first character of the string to an uppercase with all of the other
characters to lowercase.
.lower() The .lower() method will convert all of the characters of a string to lowercase, including the first character.
.upper() The .upper() method is the opposite of the .lower() method and converts all of the characters of a string to
uppercase.
.swapcase() The .swapcase() method returns a copy of the string with the uppercase characters converted to lowercase and
the lowercase characters converted to uppercase.
.title() The .title() method returns a copy of the string with the first letter of each word converted to uppercase and the
other characters converted to lowercase.
SUMMARY
In this lesson, we learned about some basic Python functions and their use. This included the len() , int() ,
float() , and str() functions. We were also introduced to a few of the Python built-in string methods including the
index() , capitalize() , lower() , upper() , swapcase() , and title() methods. We will learn how to use these
functions and methods in a future lesson.
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
TERMS TO KNOW
.capitalize()
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 94
The .capitalize() method will convert the first character of the string to an uppercase with all of the other characters to a
lowercase.
.index()
The .index() method can find the location of a character or a string within another string.
.lower()
The .lower() method will convert all of the characters of a string to lowercase including the first character.
.swapcase()
The .swapcase() method returns a copy of the string with the uppercase characters converted to lowercase and the
lowercase characters converted to uppercase.
.title()
The .title() method returns a copy of the string where the first letter of each word is converted to uppercase with the other
characters converted to lowercase.
.upper()
The .upper() method is the opposite of the .lower() method and converts all of the characters of a string to uppercase.
Argument
An argument is an actual value(s) that is being passed into the function when it is being called.
Functions
A function is a section of code that runs when it is called. We have the ability to pass in data into those functions, which
are called parameters.
Methods
Methods are a specialized type of procedure that’s directly associated with an object and called to perform a specific task
by using the object name, a period, and then the method name.
Object
An object is an instance of a class that has properties and methods that are encapsulated or part of it.
Parameter
A parameter is the actual variable name(s) when we define a function definition.
float()
The float() function can create a float number from an integer literal, float literal, or a string literal as long as the string has a
float or an integer.
int()
The int() function creates an integer number from an integer literal, a float literal (by removing all of the decimals), or a
string literal (assuming the string represents a whole number).
len()
The len() function counts all characters, including punctuation and spaces.
str()
The str() function creates a string from various data types, including strings, integer literals, and float literals.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 95
Conditional Statements
by Sophia
WHAT'S COVERED
In this lesson, you will learn about conditional statements and how to use them in Python. Specifically, this lesson
covers:
1. if Statements
2. Boolean Expressions
3. elif Statements
4. else Statements
1. if Statements
In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the
program accordingly. Conditional statements give us this ability. A conditional statement is a statement that controls the flow of
execution depending on some condition. The simplest form of a conditional statement is the if statement:
EXAMPLE
temperature = 82
if temperature > 0 :
print('temperature is positive')
The boolean expression after the if statement (the “>”) is called the condition. A condition is a boolean expression in a
conditional statement that determines which branch is executed. To finish this simple if statement, we end the statement with a
colon character (:) and the line(s) after the if statement is indented.
If the logical condition is true, then the indented statement gets executed, and ‘temperature is positive’ is the output to the
screen. If the logical condition is false, the indented statement is skipped.
Note that if statements have the same structure as function definitions. The if statement consists of a header line that ends with
the colon character (:) followed by an indented block. Statements like this are called compound statements because they
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 96
stretch across more than one line.
EXAMPLE
Indentation is vital for Python coding. Many other programming languages use indentation as a means to keep the code
readable. However, for Python, indentation is a requirement.
Python uses indentation to indicate blocks of code. As you are using Replit, you will notice vertical lines that automatically
appear as you indent code.
The print() function is indented; do you notice the grey vertical line? That tells Python that line 3, the print() function, is
included with the if statement. Python knows it is a compound statement.
Just how important is indenting? Let's see what happens when we forget to indent.
There is no limit on the number of statements that can appear in the body, but there must be at least one. The body consists of
the lines of code that are part of the condition. In essence, the body includes all of the lines of code that are indented.
Occasionally, it is useful to have a body with no statements (usually as a placeholder for code you haven’t written yet). In that
case, you can use the pass statement.
EXAMPLE
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 97
if temperature < 0 :
pass #need to handle negative temperatures!!
If you remember, pass is a reserved keyword in Python. A pass statement is essentially a statement that will do nothing. The
difference between a pass statement and a comment is that comments are completely ignored by the interpreter, whereas
the pass statement is not. It is seen, but it does nothing.
TERMS TO KNOW
Conditional Statement
A conditional statement is a statement that controls the flow of execution depending on some condition.
Condition
A condition is a boolean expression in a conditional statement that determines which branch is executed.
Compound Statement
A statement that consists of a header line that ends with the colon character (:) followed by an indented block. It is called
compound since it stretches across more than one line.
pass
A pass statement is a reserved keyword that is essentially a statement that will do nothing.
2. Boolean Expressions
Previously we mentioned that a condition is a boolean expression in a conditional statement that determines which branch is
executed. A boolean expression is an expression that is either true or false. In the previous example, we used the greater than
symbol (“>”) to check if the temperature was greater than 0 and if so, print it to the screen. We used the greater than symbol as
the comparison operator. A comparison operator is one of a group of operators that compares two values. Let’s list out and
define the six (6) comparison operators.
== Equal x == y x is equal to y
TERMS TO KNOW
Boolean Expression
A boolean expression is an expression whose value is either true or false.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 98
Comparison Operator
A comparison operator is one of a group of operators that compares two values. These include ==, !=, >, <, >=, and <=.
3. elif Statements
Using only if statements on their own can be problematic because they each run independently. Let’s take a look at this
snippet of code.
EXAMPLE
grade = 85
if grade > 90:
print("You got an A")
if grade > 80:
print("You got a B")
if grade > 70:
print("You got a C")
if grade > 60:
print("You got a D")
if grade <= 60:
print("You got a F")
In looking at this code, it seems that if the grade was an 85, “You got a B” (without the quotation marks) should be output to the
screen. However, this is what is the output:
That’s certainly not what should happen. Since each of the if statements run independently and aren’t connected, each if
statement is tested separately.
When there are more than two possibilities in a conditional statement, we need more than two branches. One way to express
a computation like that is a chained conditional. A chained conditional is a conditional statement with a series of alternative
branches. The conditions are checked one at a time and the program exits the conditional statement if any branch is true.
In order to make our previous code a cohesive single set of statements, we can make a chained conditional by making use of
the elif statement. The elif stands for “else if” and it matches an existing if statement. It is basically stating that if the current
condition is not true, try the next condition. This way, once any conditional statement is true, only that branch is output, and the
overall if statement ends.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 99
Let's go back to our example code using elif.
EXAMPLE
grade = 85
if grade > 90:
print("You got an A")
elif grade > 80:
print("You got a B")
elif grade > 70:
print("You got a C")
elif grade > 60:
print("You got a D")
elif grade <= 60:
print("You got a F")
Here is the output screen from using the elif statements.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 100
When running the code with the elif statements, the first if statement came back false. Then, the next condition (first elif) was
checked. That came back true (85 > 80), so we received that elif statement's indented output as we expected.
TERM TO KNOW
Chained Conditional
A chained conditional is a conditional statement with a series of alternative branches.
4. else Statements
The else statement can be viewed as a catchall case whereby if none of the if or elif statements were satisfied, the else
statement would run. Note that we do not need to have any conditional criteria on the else statement. Using the same
example, we can change it such that the last condition is an else.
EXAMPLE
grade = 15
if grade > 90:
print("You got an A")
elif grade > 80:
print("You got a B")
elif grade > 70:
print("You got a C")
elif grade > 60:
print("You got a D")
else:
print("You got a F")
With the output, we received an "F".
Since we changed the original grade variable to 15 points, we received what we expected, an F. Each of the elif statements
proved false and it continued to the else statement.
We can use our first example with the temperature check to use all three statements to consider the scenario of the
temperature being positive, 0, or negative. We will change the temperature variable to -5 for this test run.
EXAMPLE
temperature = -5
if temperature > 0 :
print('temperature is positive')
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 101
elif temperature == 0:
print('temperature is 0')
else:
print('temperature is negative')
Here is that output.
TRY IT
You have seen examples using if, elif, and else statements.
Directions: Use Replit to test out some of the statements you have just learned.
SUMMARY
In this lesson, we learned about conditional statements, starting with the if statement. We found out that conditional
statements are also called compound statements because they stretch across more than one line to include an
indented block of code. We also saw the importance of indenting these blocks of code since Python requires it to
function correctly. We were then introduced to the boolean expressions that can be used when creating conditional
statements. Finally, we learned that the if statement can be problematic since if statements each run independently.
Therefore, it makes sense to create a chained conditional utilizing the elif and else statements to ensure all conditions
are tested.
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
TERMS TO KNOW
Boolean Expression
A boolean expression is an expression whose value is either true or false.
Chained Conditional
A chained conditional is a conditional statement with a series of alternative branches.
Comparison Operator
A comparison operator is one of a group of operators that compares two values. These include ==, !=, >, <, >=, and <=.
Compound Statement
A statement that consists of a header line that ends with the colon character (:) followed by an indented block. It is called
compound since it stretches across more than one line.
Condition
A condition is a boolean expression in a conditional statement that determines which branch is executed.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 102
Conditional Statement
A conditional statement is a statement that controls the flow of execution depending on some condition.
pass
A pass statement is a reserved keyword that is essentially a statement that will do nothing.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 103
Boolean Operators
by Sophia
WHAT'S COVERED
In this lesson, you will learn how to use multiple boolean operators to handle various conditions in Python. Specifically,
this lesson covers:
1. Single Argument Boolean Operators
a. not Operator
2. Multiple Argument Boolean Operators
a. and Operator
b. or Operator
In addition to the bool type, Python provides three boolean operators (also called logical operators): and , or , and not .
Boolean operators allow us to build and combine more complex boolean expressions from basic expressions. Boolean
operators will take boolean inputs and return boolean results.
Since the boolean values can only have one of two values (True or False), we can specify the operators assigned in a truth
table. A truth table is a small table that lists every possible input value and gives results for the operators.
EXAMPLE
Here is the most simplistic truth table (A is a bool type and can be either True or False):
True
False
Remember that boolean operators allow us to build more complex boolean expressions from basic expressions. That is
where singular vs. multiple arguments come into play. One of the three boolean operators only works with a singular
argument.
EXAMPLE
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 104
Here is what the not operator in a truth table looks like.
A not A
True False
False True
Here is a simple example to compare two values when they are equal, which should return True.
EXAMPLE
num=1
if num==1:
print('True')
else:
print('False')
Here is the output.
EXAMPLE
num=1
if num == 0:
print('True')
else:
print('False')
Here is the output.
Now let’s try the same example, but this time adding in the not boolean operator.
EXAMPLE
num=1
if not (num == 1):
print('True')
else:
print('False')
Here is the output.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 105
This time num does equal 1, but the not boolean operator causes it to output False.
EXAMPLE
num=1
if not (num == 0):
print('True')
else:
print('False')
Here is the output.
This time num does not equal 0, but the not boolean operator causes it to output True.
TERMS TO KNOW
Boolean Operators
Boolean operators (also known as logical operators) allow us to build and combine more complex boolean expressions from
more basic expressions.
Truth Table
A truth table is a small table that lists every possible input value and gives results for the operators.
not
The not operator is a reserved keyword and boolean operator that works with one argument and returns the opposite truth
value of the argument.
A B A and B
CONCEPT TO KNOW
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 106
Short-Circuit Evaluation
Python boolean operators such as and and or use an evaluation method called short-circuit evaluation. Python reads code
from left to right, just like we read. Python will start evaluating the left operand and when it detects that there is nothing to be
gained by evaluating the rest of a logical expression, it stops its evaluation and does not do the computations in the rest of the
logical expression. This is called short-circuit evaluation, when the evaluation of a logical expression stops because the
overall value is already known.
For example, as seen in the truth table above, if Python evaluates a False in the first operand, it can stop evaluating since the
overall value has to be False.
So, looking back at the table above, the operator short-circuits if the first input is False. That means that if the first input is
False, the second input isn’t even evaluated.
We can double-check this through code to ensure that the conditions match the truth table above.
EXAMPLE
num1 = 1
num2 = 2
if num1 == 0 and num2 == 0:
print('A is False, B is False: True')
else:
print('A is False, B is False: False')
As you’ll see, the and operator outputs True if and only if both inputs result in True.
2b. or Operator
The or boolean operator is a reserved keyword and boolean operator that outputs True if either input is True (or both). It only
outputs False if both inputs are set to False. Let’s take a look at the truth table below for the or boolean operator.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 107
A B A or B
1. Exclusive or
There is the “exclusive or”, where you can only have one of two conditions. For example, we can say: “You can stay
home or you can go to the grocery store.” This means that you cannot do both at the same time; you have to choose
one of the two.
2. Inclusive or
The “inclusive or” is sometimes used with and/or as part of a phrase. For example, we can say: “You can have ice cream
and/or a cookie for dessert.” This means that you could either eat ice cream, a cookie, or even both. Python and other
programming languages evaluate the or operator using the “inclusive or”. This means that if either input is True or if
both inputs are True, the result is True.
In this case, the or operator also uses short-circuit evaluation. If the first input is True, the result is True and there’s no need to
evaluate the second argument. Let’s see what this looks like in code that evaluates each possibility:
EXAMPLE
num1 = 1
num2 = 2
if num1 == 0 or num2 == 0:
print('A is False, B is False: True')
else:
print('A is False, B is False: False')
if num1 == 0 or num2 == 2:
print('A is False, B is True: True')
else:
print('A is False, B is True: False')
if num1 == 1 or num2 == 0:
print('A is True, B is False: True')
else:
print('A is True, B is False: False')
if num1 == 1 or num2 == 2:
print('A is True, B is True: True')
else:
print('A is True, B is True: False')
Here is that "or" output.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 108
}}
TRY IT
You have seen how boolean operators can affect your conditions.
Directions: Using Replit, try some of the boolean operators out and see if you can change the output based on what you have
just learned.
TERMS TO KNOW
and
The and operator is a reserved keyword and boolean operator that takes two arguments and returns a boolean value of
False unless both inputs are True.
Short-Circuit Evaluation
Short-circuit evaluation is when the evaluation of a logical expression stops because the overall value is already known.
or
The or operator is a reserved keyword and boolean operator that outputs True if either input is True (or both).
SUMMARY
In this lesson, you learned how Python provides three boolean operators (also called logical operators): and , or , and
not . We discovered that these operators allow us to build and combine more complex boolean expressions from
basic expressions. We found that the not boolean operator works with a singular argument to return a True or False
value. In a multiple argument situation, the and and or boolean operators are used. Finally, we learned that Python
conducts short-circuit evaluation on and and or operations, meaning Python will stop evaluating logical expressions if
the overall value is already known.
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
TERMS TO KNOW
Boolean Operators
Boolean operators (also known as logical operators) allow us to build and combine more complex boolean expressions
from more basic expressions.
Short-Circuit Evaluation
Short-circuit evaluation is when the evaluation of a logical expression stops because the overall value is already known.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 109
Truth Table
A truth table is a small table that lists every possible input value and gives results for the operators.
and
The and operator is a reserved keyword and boolean operator that takes two arguments and returns a boolean value of
False unless both inputs are True.
not
The not operator is a reserved keyword and boolean operator that works with one argument and returns the opposite truth
value of the argument.
or
The or operator is a reserved keyword and boolean operator that outputs True if either input is True (or both).
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 110
Multiple Conditions
by Sophia
WHAT'S COVERED
In this lesson, you will learn how to use nested conditional statements and their outcomes with multiple variables.
Specifically, this lesson covers:
1. Nested Conditionals with One Variable
2. Nested Conditionals with Multiple Variables
EXAMPLE
grade = 75
if grade > 60:
print("You passed")
else:
print("You did not pass")
We also looked at chained conditional statements with if/elif/else statements.
EXAMPLE
Here is an example in a flowchart.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 111
EXAMPLE
Here is a code example.
If the car’s speed is less than 100, we should get the results from the second condition.
If the car’s speed is exactly at 100, the result is the third output from the else.
Conditional statements are able to be nested conditionals, meaning they can appear in one of the branches of another
conditional statement using multiple conditions. You can represent chained conditional statements using nested conditionals.
Using our second example in a nested conditional statement, let’s see what a flowchart could look like.
EXAMPLE
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 112
As we can see, the outer conditional contains two branches. The first branch contains a simple statement. The second branch
contains another if statement, which has two branches of its own. Those two branches are both simple statements, although
they could have been conditional statements as well.
Remember the importance of indenting with conditional statements? In a past lesson we explained that to finish a conditional
statement, we end the statement with a colon character (:) and the line(s) after the if statement is/are indented. This applies to a
nested condition as well, only now each nested condition’s block needs to be indented further to match the nested condition.
Now, let’s look at a nested condition with Python code. Notice the indentation of the nested condition. The entire nested if
statement is indented so you can see which else statement links to which if statement.
EXAMPLE
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 113
The conditions end up being very similar to one another. But the chained conditional statement may be easier to follow
logically, because there is only one variable being tracked in the nested conditional statements with the carSpeed .
Let’s revisit an example of a chained conditional statement that we used in a previous lesson to see how the use of nested
conditionals can make the logic easy to follow.
EXAMPLE
grade = 85
if grade > 90:
print("You got an A")
elif grade > 80:
print("You got a B")
elif grade > 70:
print("You got a C")
elif grade > 60:
print("You got a D")
elif grade <= 60:
print("You got a F")
Remember this one? We used the elif statement to determine what the correct output should be.
Instead of using the elif for each condition, we could split each condition separately and nest the conditional statements
instead.
EXAMPLE
grade = 85
if grade > 90:
print("You got an A")
else:
if grade > 80:
print("You got a B")
else:
if grade > 70:
print("You got a C")
else:
if grade > 60:
print("You got a D")
else:
if grade <= 60:
print("You got a F")
Visually, this is easier to follow compared to the chained conditional statement that we originally had.
TERM TO KNOW
Nested Conditional
A conditional statement that appears in one of the branches of another conditional statement.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 114
2. Nested Conditionals with Multiple Variables
Nested conditional statements become easier to follow when you have multiple variables that are being tracked for various
criteria. Let’s take a look at an example with multiple variables based on two different conditions. The first condition is whether
or not we are hungry and the second condition is whether we want a healthy meal.
EXAMPLE
hungry = "y"
healthy = "y"
if hungry == "n" and healthy == "n":
print("Not hungry.")
elif hungry == "n" and healthy == "y":
print("Not hungry.")
elif hungry == "y" and healthy == "n":
print("Getting some junk food.")
elif hungry == "y" and healthy == "y":
print("Getting a healthy meal.")
You may notice that the results look like a truth table. In converting this to a nested conditional, we will have the outer if
statement based on whether or not we are hungry, and the inner conditions based on whether we want to have a healthy meal
or not. Each inner condition is entered only if the outer condition is satisfied, so if we are not hungry, the inner condition is
never tested.
EXAMPLE
hungry = "y"
healthy = "y"
if hungry == "n":
if healthy == "n":
print("Not hungry.")
else
print("Not hungry.")
else:
if healthy == "n":
print("Getting some junk food.")
else:
print("Getting a healthy meal.")
Note that if we’re not hungry, the check on the healthy meal isn’t necessary, since the output is the same. This is the same as a
short-circuit evaluation of the criteria. We can also further combine the criteria.
EXAMPLE
hungry = "y"
healthy = "y"
if hungry == "n":
print("Not hungry.")
else:
if healthy == "n":
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 115
print("Getting some junk food.")
else:
print("Getting a healthy meal.")
Visually, this makes it much easier to follow than the chained conditional statement. We could make a change to get the user’s
input as well in choosing the answers.
EXAMPLE
hungry = input("Are you hungry? Enter y if you are and n if you are not: ")
healthy = input("Did you want a healthy meal? Enter y if you do and n if you do not: ")
if hungry == "n":
print("You are not hungry.")
else:
if healthy == "n":
print("Getting some junk food.")
else:
print("Getting a healthy meal.")
Note that this is partially flawed, because there’s no point asking the user if they want a healthy meal or not if they aren’t
hungry. We could change this to only prompt the user about what type of meal they want if they said that they were hungry. To
do that, we would first prompt the user to see if they were hungry. Then, within the else condition if the user is hungry, we can
prompt if they want a healthy meal or not. Let’s see what the code would look like with that change.
EXAMPLE
hungry = input("Are you hungry? Enter y if you are and n if you are not: ")
if hungry == "n":
print("You are not hungry.")
else:
healthy = input("Did you want a healthy meal? Enter y if you do and n if you do not: ")
if healthy == "n":
print("Getting some junk food.")
else:
print("Getting a healthy meal.")
This approach works much better, and is an example that couldn’t be performed in a chained conditional statement.
SUMMARY
In this lesson, we learned how we can use simple conditions and chained conditions in nested conditionals. Using one
variable in the carSpeed and grade examples, we noticed how the logic stayed the same in a chained condition
example versus a nested example, but it was easier to follow the logic with one method over another depending on
what was being compared. Next, we saw the hungry/healthy example that used multiple variables. We learned how
the logic and outcome can be improved by using nested conditionals. By nesting the conditionals, it simplified the
program and made it easier to follow the logic.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 116
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
TERMS TO KNOW
Nested Conditional
A conditional statement that appears in one of the branches of another conditional statement.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 117
Exceptions
by Sophia
WHAT'S COVERED
In this lesson, you will learn how to catch exceptions using the try and except statements. Specifically, this lesson
covers:
1. Catching Exceptions Using try and except Statements
Let’s take a look at some code where we used the input and int functions to read and convert the input, which normally returns
a string to an integer number entered by the user. Can you see any possible problems that could happen with the following
user input request?
EXAMPLE
Consider this example, where the user asks a question instead of providing the expected input.
EXAMPLE
A valid question, right? Maybe the user has several cars and wants to make sure they are answering the input request for the
proper car.
Notice that when the error occurred, the script immediately stopped in its tracks with a traceback. A traceback is a list of
functions that are executed and printed to the screen when an exception occurs. It will not execute any statement(s) that follow
the exception. With the traceback that we see above, we can identify which line the error was found on, and what the error was
that caused the program to stop.
Even if our code is written correctly (no syntax errors), it can error out when an attempt is made to execute it, as in our incorrect
user input example above. Errors detected during execution are called exceptions. These exceptions are not due to a
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 118
programming error. Rather, they are due to a real-world error that prevents the program from running correctly.
Here is another example, a sample program to convert a Fahrenheit temperature to a Celsius temperature:
EXAMPLE
Entering 72 for the Fahrenheit temperature produces the equivalent Celsius temperature. Since the code converted the input
to a floating-point number, we could have entered any integer, such as 35.7, -13.9, etc. They would all work correctly.
But again, what if we try to execute this code with invalid input?
As expected, it fails.
So, how can we handle these exceptions? There is a conditional execution structure built into Python to handle these types of
expected and unexpected errors called the “try / except” statement. If you recall from an earlier lesson, try and except are
Python keywords, meaning they cannot be used as variables. These two keywords have a primary function within code. The
idea of the try and except statement is that if you know that some sequence of instruction(s) may have a problem, you can add
some statements to be executed if an error occurs. These extra statements (the except block) are ignored if there is no error.
You can think of the try and except feature in Python as an “insurance policy” on a sequence of statements. Otherwise, the
exception will terminate the program if it is left unhandled.
EXAMPLE
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 119
As we'll see here, instead of receiving an unfriendly error message, we can see a message that can help us understand why
there was a problem.
To break this down, Python starts by executing the sequence of statements in the try block. If all goes well, it skips the except
block and proceeds. If an exception occurs in the try block, Python jumps out of the try block and executes the sequence of
statements in the except block.
Handling an exception with a try statement is called catching an exception. In this example, the except statement prints a
helpful error message. In general, catching an exception gives you a chance to fix the problem, or try again, or at least end the
program gracefully.
BIG IDEA
It’s important to note that catching of the exception, as we have done here, hides all of the errors, even those that may not be
expected. Although this is useful in this scenario, it’s not an ideal situation, as there may be other errors that could potentially
occur. We also can’t tell what the error was, specifically, either.
Let's look back at the original exception error message before we added the try except statement:
EXAMPLE
We can see that there was a ValueError exception. This way, if we ran into the ValueError exception, we would see our
exception message.
Want to catch specific exceptions? If we know an exception based on a traceback or in the event we just want to look out for a
probable exception, we can set up code to catch a specific exception. To catch a specific exception, we place the type of
exception after the except keyword. Remember to finish the line off with the colon (:).
EXAMPLE
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 120
This is useful, but we may also want to know what the actual error was from Python. We can do that as well, by setting the
exception and placing it into a variable named error. This way, we can see exactly what may have gone wrong. We will need to
output the variable error to see what the issue was as well.
Including the as keyword after the exception error allows us to set the error message and handle it accordingly. In our
example below, we’ll set the variable error if there’s a ValueError exception and output it to the screen. The as keyword is one
of Python’s reserved keywords and simply is used to create an alias. So, for our example, the as keyword places the error
message to a variable.
EXAMPLE
The try statement is executed up to the point where we run into the first exception that can occur. In this case, it was the
conversion of the variable inp to a float.
fahr = float(inp)
Notice that we tried to enter in the string “sophia” in inp , which the float function attempts to convert to a float value. When
that happens, it goes to the except statement that’s specific to the error—which in our case is the ValueError exception. Then,
we process the exception from there. This allows us to anticipate different exceptions and how the program should be able to
respond to those exceptions.
TERMS TO KNOW
Traceback
A traceback is a list of functions that are executed and printed to the screen when an exception occurs.
Exceptions
Errors detected during execution (running of the code) are called exceptions.
as
The as keyword is one of Python’s reserved keywords and simply is used to create an alias.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 121
SUMMARY
In this lesson, we learned about exception handling through the use of a try and except set of statements to catch
specific errors/exceptions. In particular, we learned about catching a common exception called the ValueError
exception, which is caused when we try to convert a variable from one data type to another. The exception occurs if
the variable cannot be converted to another data type. We also learned about using the as keyword to set a variable
to a common exception and output it to the screen during execution.
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
TERMS TO KNOW
Exceptions
Errors detected during execution (running of the code) are called exceptions.
Traceback
A traceback is a list of functions that are executed and printed to the screen when an exception occurs.
as
The as keyword is one of Python’s reserved keywords and simply is used to create an alias.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 122
Debugging Conditional Statements
by Sophia
WHAT'S COVERED
In this lesson, you will learn how to debug code and conditional statements in Python. Specifically, this lesson covers:
1. Debugging Tips
2. Debugging Conditional Statements
a. Adding Breakpoints
b. Running the Debugger
1. Debugging Tips
In a previous lesson, we discussed and practiced debugging techniques. We learned that the difference between testing and
debugging is that testing identifies if there are bugs or issues, whereas debugging is going through the process of fixing those
issues.
Conditional statements can create a number of potential issues with coding that require debugging. With large chained and
nested statements, syntax and other errors can happen unexpectedly. One common issue is the use of whitespace errors,
such as spaces or tabs. Whitespace errors can be tricky because spaces and tabs are invisible and we're used to ignoring
them.
EXAMPLE
For example, look at the following code.
x = 5
y = 6
When run, this gives us an error.
In this example, the problem is that the second line is indented by one space. But the error message points to y, which is
misleading. In general, error messages indicate where the problem was discovered, but the actual error might be earlier in
the code, sometimes on a previous line.
In general, error messages tell you where the problem was discovered, but that is often not where it was caused. The best
way to avoid these problems is to use spaces exclusively (no tabs). Tabs and spaces are usually invisible, which makes them
hard to debug, so try to find a text editor that manages indentation for you. Most text editors that know about Python do this by
default, but some don’t.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 123
DID YOU KNOW
Replit is a perfect example of an IDE and text editor. A text editor is a program that allows you to edit plain text without the
added formatting features. Notepad on Windows is a very common text editor. An IDE has other features and functionalities
that allow a programmer to interact with the code directly in the program. For example, Replit allows you to create and run
code in a number of popular programming languages, including Python. Have you noticed that when you write an if statement
in Replit and hit enter to move to the next line, it automatically indents the block line?
TRY IT
Maybe up to this point you have only copied and pasted code into Replit. Let’s take a step back and write some code. We'll
need it for the next topic anyway.
Directions: Open Replit and add the following code line by line and notice how Replit’s text editor automatically indents
conditional statements.
grade = 85
if grade > 90:
print("You got an A")
elif grade > 80:
print("You got a B")
elif grade > 70:
print("You got a C")
elif grade > 60:
print("You got a D")
elif grade <= 60:
print("You got a F")
print("We are done!")
Notice the auto indentations? You can write a lot of code in Replit and other text editors using the return and backspace keys.
Pretty nice, huh?
EXAMPLE
Although we have an idea of what happens, we’re not quite sure if our assumptions are correct or not. In order to help with
this, we need to use the Debugger feature in Replit, which is the third item in the left column. If you click on it, the Files and
Configuration column (panel) to the right will be changed to the debugger tool.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 124
BEFORE YOU START
One thing to note is that your debugger panel and the debugger tools may not be the same color as the images that follow.
The functionality is identical but depending on your Replit theme (dark/light), browser, etc., the colors may be different. Just
know that the directions and steps will not be affected.
Also, we used the "Settings" icon to change the Replit layout to "stacked"—that way we can see both the debugging and output
on top of one another instead of side by side.
In order to establish a breakpoint, we click beside a line number. This will then allow us to step through from that point.
TRY IT
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 125
Let’s click to the left of line 2 to add a breakpoint to that conditional statement. We should see a dot appear beside line 2, and
see it listed under the Breakpoints.
TRY IT
To start the debugging process, we will click on the Run arrow in the Debugger column. The program will start executing and
stop on line 2, because that is where we set our breakpoint.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 126
We should see that line 2 is highlighted in the code editor. There isn’t any output yet, so the console (output sandbox) at the
bottom is still empty. In the Debugger column, we will see the variables that are currently declared in the code and the value
that they are set to. In this case, we have the variable grade that is set to 85, which was executed and set in line 1. We also see
that the Run button has now turned into a Stop button. The program is currently stopped.
Since the program is stopped at the breakpoint at line 2, there are two options:
1. We can click on the Next Step (single arrow) button to move to the next line.
The Next Step button will allow you to run through the code line by line, stopping at each line.
2. The other choice is the Next Breakpoint (double arrow) button, which will continue running the program until the
next set breakpoint.
On stopped and highlighted line 2, the conditional statement is checking if the grade is greater than 90. Since it is
not, we can see what happens next.
TRY IT
Notice now that line 4 is highlighted since that is the next condition to be checked.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 127
We can see now that line 5 is highlighted, as the condition was entered (since 85 is greater than 80).
We now see that the “You got a B” displays in the output on the screen and line 12 is now highlighted. This is because all of the
other elif statements are skipped since the condition on line 4 satisfied the overall condition.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 128
The last line “We are done!” is now outputted to the screen and the breakpoint area is reset.
By stepping through the execution of a program using the breakpoints, it allows us to quickly spot what path the code takes.
Now let’s try a situation where we may have multiple breakpoints to help track the path of each condition.
TRY IT
hungry = input("Are you hungry? Enter y if you are and n if you are not: ")
if hungry == "n":
print("You are not hungry.")
else:
healthy = input("Did you want a healthy meal? Enter y if you do and n if you do not: ")
if healthy == "n":
print("Getting some junk food.")
else:
print("Getting a healthy meal.")
print("All done!")
Directions: Enter the debug function. Let’s place some breakpoints on each condition on lines 2 and 6. That way we can skip
over a breakpoint to fast forward to the next breakpoint if needed.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 129
Directions: Start the debug tool using the Run button. It should ask us the input question in line 1 and await our input. Enter the
first input using a “y” for now.
It should now stop on line 2 to await the next step. Perhaps we may have finished testing the first condition. One option is to
remove the breakpoint by clicking on the dot beside the line. The other option is to still include that breakpoint but skip over it
by clicking on the Next Breakpoint (double arrow) button.
This will allow you to step over the other breakpoint on line 6 and the commands that would normally be stopped after that
point.
Directions: Select the Next Breakpoint button. It will first ask you whether or not you want a healthy meal question. Make sure
to answer that.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 130
In our demo, we answered “y” to a healthy meal. Therefore, we skipped down to our second breakpoint on line 6. If we were
to continue in debug mode:
We could watch line by line using the Next Step button. Next Step would drop us down to line 9, since we selected a
healthy meal. Selecting Next Step again, we would see the output “Getting a healthy meal.” Finally, one more click, and we
would see the output of “All done!” from line 10, and the debugger column would clear and reset.
Or, we could have pressed the Next Breakpoint button. Since we did not have another breakpoint set, we would have
seen the outputs “Getting a healthy meal.” and “All done!” appear, and the debugger column would clear and reset.
TRY IT
Directions: Using the code we just debugged, or any other code of your choice with conditional statements included, try
setting up your own breakpoints and executing the code through the debugger feature. The more you use this feature, the
easier it will become.
SUMMARY
In this lesson, we learned about some debugging tips that included making sure we watch for common whitespace
errors like spaces and tabs. Since they appear invisible to us, they can be tricky to spot. That is why it is always good
practice to code with a text editor that is familiar with Python. Replit is perfectly suited for this reason. Next, we used
the Replit debugger feature to debug some conditional statements. We learned that using breakpoints and “walking”
through the code as it executes is a great way to determine the path the code is following. We will see in future
lessons just how helpful the debugger tool is with lengthy code.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 131
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 132
Drink Order Program
by Sophia
WHAT'S COVERED
In this lesson, you will learn how to use conditional statements and their outcomes in Python. Specifically, this lesson
covers:
1. Planning the Algorithm
2. Writing the Code
Water
Hot
Cold
Ice/No Ice
Coffee
Decaffeinated or Not?
Milk or Cream or None
Sugar or None
Tea
Green
Black
In looking at these options, the user should first be prompted with the choice of water, coffee, or tea. Based on those
selections, there are additional prompts that are unique to each one. As the user enters each option, a string should be built to
indicate the entire order to be output at the end.
THINK ABOUT IT
Before we get into any coding, look at the selections again. Can you envision which questions we need to ask the user? Based
on the user’s input, what conditionals do you think we will need? What outputs are you expecting the user to see? Given the
input, what should happen next?
All these questions help formulate the algorithm for this program.
TRY IT
Directions: We covered pseudocode in a previous lesson. Pseudocode comprises the English-like statements that describe
the steps in a program or algorithm. Try writing down the steps you believe will be needed to make this program successful.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 133
BIG IDEA
For the final project in Unit 4, you will identify a problem that you would like to address through a program. Now is a great time
to start “flexing” your algorithm step-building muscles.
TRY IT
Directions: Let’s enter the following code that initially checks the drink types. As you enter the code, feel free to add any
comments you wish to help you better understand what is happening. Note: we are using the escape character with the new
line character “\n”. Remember that the escape character allows us to write a single line that will present as multiple lines in the
output since the \n adds a new line after each use of \n.
drinkDetails=""
drink = input('What type of drink would you like to order?\nWater\nCoffee\nTea\nEnter your choice: ')
if drink == "Water":
drinkDetails=drink
elif drink == "Coffee":
drinkDetails=drink
elif drink == "Tea":
drinkDetails=drink
else:
print("Sorry, we did not have that drink available for you.")
print("Your drink selection: ",drinkDetails)
Directions: Great! Now let’s go ahead and run the code. Try running a few options.
Now we’ll need to break down the options for each drink selection. We’ll start with the water selection. We’ll need to prompt
the user to determine if they want to have hot or cold water.
TRY IT
Directions: Enter the following code inside the water conditional. Take note that in the water conditional, we are assigning the
variable drinkDetails as Water. Then, after the input of Hot or Cold, we concatenate that response on the output string
using the concatenate char + . Remember, concatenation is the operation of joining or merging two or more strings together.
And we are also using the += operator to add two values together and assign that final value to the variable.
drinkDetails=""
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 134
drink = input('What type of drink would you like to order?\nWater\nCoffee\nTea\nEnter your choice: ')
if drink == "Water":
drinkDetails=drink
temperature = input("Would you like your water? Hot or Cold: ")
if temperature == "Hot":
drinkDetails += ", " + temperature
elif temperature == "Cold":
drinkDetails += ", " + temperature
else:
drinkDetails += ", unknown temperature entered."
elif drink == "Coffee":
drinkDetails=drink
elif drink == "Tea":
drinkDetails=drink
else:
print("Sorry, we did not have that drink available for you.")
print("Your drink selection: ",drinkDetails)
We can test both options of hot and cold water, as well as an incorrect option.
TRY IT
Did you get the same outputs? We tried Medium as the water temperature, and of course, received the unknown temperature
output.
The next step would be if the user selected cold water, whether they would like ice.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 135
TRY IT
Directions: Go ahead and add the code to determine if the user wants ice added to their cold water. Now we will concatenate
that decision onto the drinkDetails variable.
drinkDetails=""
drink = input('What type of drink would you like to order?\nWater\nCoffee\nTea\nEnter your choice: ')
if drink == "Water":
drinkDetails=drink
temperature = input("Would you like your water? Hot or Cold: ")
if temperature == "Hot":
drinkDetails += ", " + temperature
elif temperature == "Cold":
drinkDetails += ", " + temperature
ice = input("Would you like ice? Yes or No: ")
if ice == "Yes":
drinkDetails += ", Ice"
else:
drinkDetails += ", unknown temperature entered."
elif drink == "Coffee":
drinkDetails=drink
elif drink == "Tea":
drinkDetails=drink
else:
print("Sorry, we did not have that drink available for you.")
print("Your drink selection: ",drinkDetails)
Directions: Go ahead and run the program again, testing each water option.
Notice that we don’t have to worry about the check if the selection is no ice, because we don’t have to include that as part of
the items to add. If we did want to include it, we can use the elif to check if the response is a No or not.
Since the tea selection is the easiest next option, we can now fill that part out for the selection of the green or black tea.
TRY IT
Directions: Now add the code to determine if the user wants green or black tea with a Tea drink choice decision.
drinkDetails=""
drink = input('What type of drink would you like to order?\nWater\nCoffee\nTea\nEnter your choice: ')
if drink == "Water":
drinkDetails=drink
temperature = input("Would you like your water? Hot or Cold: ")
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 136
if temperature == "Hot":
drinkDetails += ", " + temperature
elif temperature == "Cold":
drinkDetails += ", " + temperature
ice = input("Would you like ice? Yes or No: ")
if ice == "Yes":
drinkDetails += ", Ice"
else:
drinkDetails += ", unknown temperature entered."
elif drink == "Coffee":
drinkDetails=drink
elif drink == "Tea":
drinkDetails=drink
teaType = input("What type of tea would you like? Black or Green: ")
if teaType == "Black":
drinkDetails += ", " + teaType
elif teaType == "Green":
drinkDetails += ", " + teaType
else:
print("Sorry, we did not have that drink available for you.")
print("Your drink selection: ",drinkDetails)
Directions: Go ahead and run the program again, testing the Tea drink options.
That was the only criteria that we had to set up for the tea. With the coffee option, we have three separate parts, but they are
very similar to one another.
TRY IT
Directions: Finally, let’s add the code for the sub-options for coffee.
drinkDetails=""
drink = input('What type of drink would you like to order?\nWater\nCoffee\nTea\nEnter your choice: ')
if drink == "Water":
drinkDetails=drink
temperature = input("Would you like your water? Hot or Cold: ")
if temperature == "Hot":
drinkDetails += ", " + temperature
elif temperature == "Cold":
drinkDetails += ", " + temperature
ice = input("Would you like ice? Yes or No: ")
if ice == "Yes":
drinkDetails += ", Ice"
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 137
else:
drinkDetails += ", unknown temperature entered."
elif drink == "Coffee":
drinkDetails=drink
decaf = input("Would you like decaf? Yes or No: ")
if decaf == "Yes":
drinkDetails += ", Decaf"
milkCream = input("Would you like Milk, Cream or None: ")
if milkCream == "Milk":
drinkDetails += ", Milk"
elif milkCream == "Cream":
drinkDetails += ", Cream"
sugar = input("Would you like sugar? Yes or No: ")
if sugar == "Yes":
drinkDetails += ", Sugar"
elif drink == "Tea":
drinkDetails=drink
teaType = input("What type of tea would you like? Black or Green: ")
if teaType == "Black":
drinkDetails += ", " + teaType
elif teaType == "Green":
drinkDetails += ", " + teaType
else:
print("Sorry, we did not have that drink available for you.")
print("Your drink selection: ",drinkDetails)
It’s a good idea to test out each of the cases, but we’ll just test one here.
TRY IT
Directions: Go ahead and run the program and test out all the Coffee drink options.
Although this concludes the program that we have here, there are some underlying issues with this type of code. One of the
issues is that the program becomes very difficult to read, as it gets larger and contains many branches. We’ll look at cleaning
this up when it comes to creating more complex functions later. Additionally, if an incorrect input is entered at any point, we’re
not prompting the user to enter in a value a second time (or even a third). To help with this, we’ll make use of loops, which we
will begin to talk about in the next unit.
TRY IT
Directions: This program is finished to this point and consists of more conditional statements than anything you've seen
previously. This would be a good program to get a better understanding of the debugger tool. Try adding breakpoints at
certain lines of code to “walk” yourself through the execution path. See what invalid input errors you get. Have fun!
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 138
To see the final version of this program visit Sophia's Replit page.
SUMMARY
In this lesson, we were given a project request from a company to build a drink order program. We first looked at the
drink order options and did some preliminary algorithm planning. Based on the drink options, we required a number
of conditional statements to move through the options. We were able to write the code for a program that, when
executed, would provide the user with some input choices and output of their final selection.
Source: THIS CONTENT AND SUPPLEMENTAL MATERIAL HAS BEEN ADAPTED FROM “PYTHON FOR EVERYBODY” BY DR.
CHARLES R. SEVERANCE ACCESS FOR FREE AT https://www.py4e.com/html3/
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 139
Terms to Know
*
The * operator (asterisk sign) or multiplication operator is unique to Python as it can multiply integers and
can also be used as a replication operator with strings and integers (floats will not work). As a replication
operator, it will repeat (make a copy of) the variable based on the number of times it is multiplied by.
+
The + operator (plus sign) is the addition operator on integers; however, it can also function as a
concatenation operator when applied to string variables, which means it joins the variables by linking
them end to end. An error will appear if trying to use this operator on variables that are a mix of string
and integer.
.capitalize()
The .capitalize() method will convert the first character of the string to an uppercase with all of the other
characters to a lowercase.
.index()
The .index() method can find the location of a character or a string within another string.
.lower()
The .lower() method will convert all of the characters of a string to lowercase including the first character.
.swapcase()
The .swapcase() method returns a copy of the string with the uppercase characters converted to
lowercase and the lowercase characters converted to uppercase.
.title()
The .title() method returns a copy of the string where the first letter of each word is converted to
uppercase with the other characters converted to lowercase.
.upper()
The .upper() method is the opposite of the .lower() method and converts all of the characters of a string to
uppercase.
=
The = operator (equal sign) is an assignment operator that is used to assign values to variables.
Algorithm
A logical step-by-step plan that we need to build for solving a problem.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 140
Argument
An argument is an actual value(s) that is being passed into the function when it is being called.
Base 10 Numbers
Also called decimal values, these are numbers using 10 digits that go from 0 to 9.
Base 16 Numbers
Also called hexadecimal numbers, these are any numbers using 10 digits (0 to 9) and 6 letters (A, B, C, D,
E, and F).
Base 2 Numbers
Also called binary numbers, these are numbers using two digits, 0 or 1.
Base 8 Numbers
Also called octal numbers, these are numbers using 8 digits, going from 0 to 7.
Bool
A boolean data type consisting of a value of either True or False.
Boolean Expression
A boolean expression is an expression whose value is either true or false.
Boolean Operators
Boolean operators (also known as logical operators) allow us to build and combine more complex
boolean expressions from more basic expressions.
Bytecode
An intermediary step for code conversion between the programming language that you write and the
machine code that a computer uses.
Camel Case
Combining words where each word except the first word will start with a capital letter.
Chained Conditional
A chained conditional is a conditional statement with a series of alternative branches.
Comments
The “#” (hashtag) is used in Python code to identify a comment. Commented lines of code are ignored by
the compiler during run time. A programmer adds comments throughout the code to explain how the
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 141
program or function works.
Comparison Operator
A comparison operator is one of a group of operators that compares two values. These include ==, !=, >, <,
>=, and <=.
Compiler
A compiler scans an entire program and attempts to convert the whole program at once to machine code.
Complex
A numeric data type consisting of a number that is the sum of a real number and an imaginary number.
Compound Statement
A statement that consists of a header line that ends with the colon character (:) followed by an indented
block. It is called compound since it stretches across more than one line.
Concatenation
The operation of joining or merging two or more strings together.
Condition
A condition is a boolean expression in a conditional statement that determines which branch is executed.
Conditional Statement
A conditional statement is a statement that controls the flow of execution depending on some condition.
Corner Case
The value you are testing is in between two edge cases.
Edge Case
Values that are at the end of a testing range.
Empty String
An empty string ("") is a string that is identified but does not contain anything; it is essentially empty.
Escape Character
Special characters that when added to a string will allow quotes of a string to be escaped.
Exceptions
Errors detected during execution (running of the code) are called exceptions.
Expression
A combination of values, variables, and operators.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 142
Float
A numeric data type referring to a floating point number. It is a number that can be positive or negative
and uses decimal values.
Functions
A function is a section of code that runs when it is called. We have the ability to pass in data into those
functions, which are called parameters.
Input
Ways a program gets its data; user input through the keyboard, mouse, or other device.
Int
A numeric data type consisting of an integer or a whole number. It can either be a positive or a negative
number but it does not have any decimals.
Interior Test
Test values that are within a specific range where the precise values that we entered within that range
did not matter.
Interpreter
An interpreter takes the bytecode one line at a time and converts it to machine code.
Libraries/Library
Prewritten code collections that you can use when developing a program.
Literal String
A series of characters that are combined together and enclosed in quotes; for example, "Enter in the
second number" is a literal string.
Machine Code
Also known as machine language. The computer uses binary (0s and 1s) to perform tasks. At a high level,
the programming language code that you write gets translated or compiled to the machine code that the
computer understands.
Methods
Methods are a specialized type of procedure that’s directly associated with an object and called to
perform a specific task by using the object name, a period, and then the method name.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 143
Module
A self-contained piece of code that can be used in different programs.
Nested Conditional
A conditional statement that appears in one of the branches of another conditional statement.
Object
An object is an instance of a class that has properties and methods that are encapsulated or part of it.
Output
The results at the end of a program based on user input and system processing.
Parameter
A parameter is the actual variable name(s) when we define a function definition.
Pascal Case
Combining words where each word starts with a capital letter.
Processing
Taking the data inputs and prompts and calculates the results (output).
Program
A sequence of computer language statements that have been crafted to do something.
Pseudocode
English-like statements that describe the steps in a program or algorithm.
Short-Circuit Evaluation
Short-circuit evaluation is when the evaluation of a logical expression stops because the overall value is
already known.
Snake Case
Combining words where each word is separated by an underscore and all of the words are in lowercase.
Statement
A unit of code that the Python interpreter can execute.
Str
A text data type consisting of characters that are enclosed in either single or double quotes.
String
A data type that can store a literal string as a value.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 144
Syntax
The syntax is the “grammar” rules of the programming language. Each programming language (like
Python) has its own syntax.
Syntax Error
A syntax error means that you have violated the “grammar” rules of Python.
Traceback
A traceback is a list of functions that are executed and printed to the screen when an exception occurs.
Truth Table
A truth table is a small table that lists every possible input value and gives results for the operators.
Value
One of the basic units of data, like a number or string, that a program manipulates.
Variable
A named memory location that has the ability to hold various distinct values at different points in time in
the program.
Virtual Machine
A software program that behaves like a completely separate computer within an application.
and
The and operator is a reserved keyword and boolean operator that takes two arguments and returns a
boolean value of False unless both inputs are True.
as
The as keyword is one of Python’s reserved keywords and simply is used to create an alias.
float()
The float() function can create a float number from an integer literal, float literal, or a string literal as long
as the string has a float or an integer.
in
The in operator is a reserved keyword and used as a membership operator that checks if the first operand
is contained in the second. If it is contained, it returns true; otherwise, it returns false. It can also be used
to iterate through a sequence in a for loop.
int()
The int() function creates an integer number from an integer literal, a float literal (by removing all of the
decimals), or a string literal (assuming the string represents a whole number).
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 145
len()
The len() function counts all characters, including punctuation and spaces.
not
The not operator is a reserved keyword and boolean operator that works with one argument and returns
the opposite truth value of the argument.
or
The or operator is a reserved keyword and boolean operator that outputs True if either input is True (or
both).
pass
A pass statement is a reserved keyword that is essentially a statement that will do nothing.
print( )
The print() function allows Python to output data to the console (screen).
str()
The str() function creates a string from various data types, including strings, integer literals, and float
literals.
type()
The type() function takes a value or variable as input and returns the type of the value or variable.
© 2023 SOPHIA Learning, LLC. SOPHIA is a registered trademark of SOPHIA Learning, LLC. Page 146