Chapter 1

Python Review

All the stuff you should know already!

Subsections of Python Review

Programming Overview

YouTube Video

Programming

Computer Code Computer Code1

Programming is the act of writing source code for a computer program in such a way that a modern computer can understand and perform the steps described in the code. There are many different programming languages that can be used, such as high-level languages like Java and Python.

To run code written in those languages, we can use a compiler to convert the code to a low-level language that can be directly executed by the computer, or we can use an interpreter to read the code and perform the requested operations on the computer.

At this point, we have most likely written some programs already. This chapter will review the important aspects of our chosen programming language, giving us a solid basis to build upon. Hopefully most of this will be review, but there may be a few new terms or concepts introduced here as well.

Flowcharts and Pseudocode

In this course, we will primarily be learning different ways to store and manipulate data in our programs. Of course, we could do this using the source code of our chosen programming language, but in many cases that would defeat the purpose of learning how to do it ourselves!

Instead, we will use several different ways to represent the steps required to build our programs. Let’s review a couple of them now.

Natural Language

One of the simplest ways to describe a computer program is to simply write what it does using our preferred language, such as English. Of course, natural language can be very ambiguous, so we must be careful to make our written descriptions as precise as possible. So, it is a good idea to limit ourselves to simple, clear sentences that aren’t written as prose. It may seem a bit boring, but this is the best way to make sure our intent is completely understood.

A great example is a recipe for baking. Each step is written clearly and concisely, with enough descriptive words used to allow anyone to read and follow the directions.

Flowcharts

Programming Flowchart Template Programming Flowchart Template

One method of representing computer programs is through the use of flowcharts. A flowchart consists of graphical blocks representing individual operations to be performed, connected with arrows which describe the flow of the program. The image above gives the basic building blocks of the flowcharts that will be used in this course. We will mostly follow the flowchart design used by the Flowgorithm program available online. The following pages in this chapter will introduce and discuss each block in detail.

Pseudocode

We can also express our computer programs through the use of pseudocode. Pseudocode is an abstract language that resembles a high-level programming language, but it is written in such a way that it can be easily understood by any programmer who is familiar with any one of several common languages. The pseudocode may not be directly executable as written, but it should contain enough detail to be easily understood and adapted to an actual programming language by a skilled programmer.

There are many standards that exist for pseudocode, each with their own unique features and uses. In this course, we will mostly follow the standards from the International Baccalaureate Organization. In the following pages in this chapter, we’ll also introduce pseudocode for each of the flowchart blocks shown above.

References

Syntax Overview

Let’s discuss some of the basic concepts we need to understand about the Python programming language.

Program Structure

To begin, let’s look at a simple Hello World program written in Python:

def main():
    print("Hello World!")


# main guard
if __name__ == "__main__":
    main()

This program contains multiple important parts:

  1. First, we define a function called main(). Python does not require us to do this, since we can write our code directly in the file and it will execute. However, since we are going to be building larger programs in this course, it is a good idea to start using functions now.
  2. The function definition ends with a colon :, and then the code inside of that function comes directly after it. The code contained in the function must be indented a single level. By convention, Python files should use 4 spaces to indent the code. Thankfully, Codio does that for us automatically.
  3. At the bottom of the file, we’ve included a main guard that determines if this file is being executed. If it is, it will call the main() function to run the program.

Of course, this is a very brief overview for the Python programming language. To learn more, feel free to refer to the references listed below, as well as the textbook content for previous courses.

Try It!

See if you can use the code above to write your own Hello World program a file named HelloWorld.py. We’ll learn how to compile and run that program on the next page.

References

Running Code

YouTube Video

Now that we’ve written our first Python program, we must run the program to see the fruits of our labors. There are many different ways to do this using the Codio platform. We’ll discuss each of them in detail here.

Terminal

Codio includes a built-in Linux terminal, which allows us to perform actions directly on a command-line interface just like we would on an actual computer running Linux. We can access the Terminal in many ways:

  1. Selecting the Tools menu, then choosing the Terminal option
  2. Pressing SHIFT + ALT + T in any Codio window (you can customize this shortcut in your Codio user preferences)
  3. Pressing the Open Terminal icon in the file tree
  4. Selecting the Open Terminal option from the Run menu (it is the first menu to the right of the Help menu)

Additionally, some pages may already open a terminal window for us in the left-hand pane, as this page so helpfully does. As we can see, we’re never very far away from a terminal.

New to Linux?

No worries! We’ll give you everything you need to know to run your Python programs in this course.

If you’d like to learn a bit more about the Linux terminal and some of the basic commands, feel free to check out this great video on YouTube:

YouTube Video

Let’s go to the terminal window and navigate to our program. When we first open the Terminal window, it should show us a prompt that looks somewhat like this one:

Initial Terminal View Initial Terminal View

There is quite a bit of information there, but we’re interested in the last little bit of the last line, where it says ~/workspace. That is the current directory, or folder, our terminal is looking at, also known as our working directory. We can always find the full location of our working directory by typing the pwd command, short for “Print Working Directory,” in the terminal. Let’s try it now!

Enter this command in the terminal:

pwd

and we should see output similar to this:

pwd Command Output pwd Command Output

In that output, we’ll see that the full path to our working directory is /home/codio/workspace. This is the default location for all of our content in Codio, and it’s where everything shown in the file tree to the far left is stored. When working in Codio, we’ll always want to store our work in this directory.

Next, let’s use the ls command, short for “LiSt,” to see a list of all of the items in that directory:

ls

ls Command Output ls Command Output

We should see a whole list of items appear in the terminal. Most of them are directories containing examples for the chapters this textbook, including the HelloWorld.py file that we edited in the last page. Thankfully, the directories are named in a very logical way, making it easy for us to find what we need. For example, to find the directory for Chapter 1 that contains examples for Python, look for the directory with the name starting with 1p. In this case, it would be 1p-hello.

Finally, we can use the cd command, short for “Change Directory,” to change the working directory. To change to the 1p-hello directory, type cd into the terminal window, followed by the name of that directory:

cd 1p-hello

cd Command Output cd Command Output

We are now in the 1p-hello directory, as we can see by observing the ~/workspace/1p-hello on the current line in the terminal. Finally, we can do the ls command again to see the files in that directory:

ls

ls Command Output ls Command Output

We should see our HelloWorld.py file! If it doesn’t appear, try using this command to get to the correct directory: cd /home/codio/workspace/1p-hello.

Once we’re at the point where we can see the HelloWorld.py file, we can move on to actually running the program.

Running in Terminal

To run it, we just need to type the following in the terminal:

python3 HelloWorld.py

python Command Output python Command Output

That’s all there is to it! We’ve now successfully run our first Python program. Of course, we can run the program as many times as we want by repeating the previous python3 command. If we make changes to the HelloWorld.py file that instruct the computer to do something different, we should see those changes the next time we run the file..

Problems?

If the python3 command doesn’t give you any output, or gives you an error message, that most likely means that your code has an error in it. Go back to the previous page and double-check that the contents of HelloWorld.py exactly match what is shown at the bottom of the page. You can also read the error message output by python3 to determine what might be going wrong in your file.

Also, make sure you use the python3 command and not just python. The python3 command references the newer Python 3 interpreter, while the python command is used for the older Python 2 interpreter. In this book, we’ll be using Python 3, so you’ll need to always make sure you use python3 when you run your code.

We’ll cover information about simple debugging steps on the next page as well. If you get stuck, now is a great time to go to the instructors and ask for assistance. You aren’t in this alone!

Try It!

See if you can change the HelloWorld.py file to print out a different message. Once you’ve changed it, use the python3 command to run the file again. Make sure you see the correct output!

Codio Assessments

Last, but not least, many of the Codio tutorials and projects in this program will include assessments that we must solve by writing code. Codio can then automatically run the program and check for specific things, such as the correct output, in order to give us a grade. For most of these questions, we’ll be able to make changes to our code as many times as we’d like to get the correct answer.

As we can see, there are many different ways to compile and run our code using Codio. Feel free to use any of these methods throughout this course.

Debugging

Codio also includes an integrated debugger, which is very helpful when we want to determine if there is an error in our code. We can also use the debugger to see what values are stored in each variable at any point in our program.

To use the debugger, find the Debug Menu at the top of the Codio window. It is to the right of the Run Menu we’ve already been using. On that menu, we should see an option for Python - Debug File. Select that option to run our program in the Codio debugger.

As we build more complex programs in this course, we’ll be able to configure our own debugger configurations that allow us to test multiple files and operations.

The Codio debugger only works with input from a file, not from the terminal. So, to use the debugger, we’ll need to make sure the input we’d like to test is stored in a file, such as input.txt, before debugging. We can then give that file as an argument to our program in our debugger configuration, and write our program to read input from a file if one is provided as an argument.

Learning how to use a debugger is a hands-on process, and is probably best described in a video. You can find more information in the Codio documentation to get up to speed on working in the Codio debugger.

Codio Documentation - Debugger

We can always use the debugger to help us find problems in our code.

Visualizer

Codio Visualizer Codio Visualizer1

Codio now includes support for Python Tutor, allowing us to visualize what is happening in our code. We can see that output in the second tab that is open to the left.

Unfortunately, students are not able to open the visualizer directly, so it must be configured by an instructor in the Codio lesson. If you find a page in this textbook where you’d like to be able to visualize your code, please let us know!

Variables

YouTube Video

A variable in a programming language is an abstraction that allows storing one value in each instant of time, but this value can change along with the program execution. A variable can be represented as a box holding a value. If the variable is a container, e.g., a list (or array or vector), a matrix, a tuple, or a set of values, each box in the container contains a single value.

Characteristics

A variable is characterized by:

  1. An identifier or name. The name represents the most important information since it allows us to identify the variable inside the program. This name has to be unique inside the program and it allows us to identify the variable. In order to improve program legibility, and facilitate debugging, and understanding it is important to choose a representative name for the variable that clearly represents the function of the variable. Representative names could be results, number_of_nodes, number_of_edges. For writing variable names composed of two or more words in Python we can use underscores to separate the words.
  2. A single value, i.e. the value that is stored in the variable. The value of the variable can be modified during program execution but at each instant of time, the variable holds a single value.
  3. A data type. The data type characterizes the set of values that the variable can take. For example, the integer type contains numbers without a decimal part. The decimal or floating point type contains numbers with a decimal part. In mathematics, we call these real numbers. The string type (text) characterizes character sequences, and the Boolean type contains true or false values and is used to hold the result of the conditions. In some untyped languages, like Scratch and Python, the data type is deduced from the value that contains the variable. Since the value can change, its type can also change. For example, a variable can contain an integer value at the beginning of the program, a value that is subsequently changed to a real number. In other programming languages, such as Java, the type must be explicitly indicated at the time of declaration and cannot change.
  1. A memory address, which is the memory address, in the RAM of the computer, where the value is stored. We won’t work directly with memory addresses in this course, but we may see them when using a visualizer or debugger to execute our programs.

Other Features

Depending on the programming language, we could also specify for a variable:

  1. Visibility. An area of visibility or purpose, which is where inside the program the variable is visible. In Python and Java, visibility can be specified at the global level, i.e. visible in all the program, or local, i.e. visible at the individual procedure level.
  2. A lifetime. The lifetime of a variable is closely related to its visibility: when the program performs an instruction outside the purpose of the variable, i.e. outside the scope of a variable, the variable itself ends its life.

Variable Operations

A programming language allows to perform two basic operations with a variable:

  1. Reading the value of a variable. This value can be used in expression allowing to relate variables by means of operators. The basic operators are:
    1. Arithmetic operators: such as addition +, and subtraction -. They allow performing basic arithmetic operations with numbers.
    2. Comparison operators: such as less than <, and greater than >. Usually, they allow to comparing two operands, each of which could be a variable. The result of the comparison is either the Boolean value true or the Boolean value false.
    3. Logic operators: such as and , or, and not. This operator allows us to relate logical conditions together to create more complex statements.
    4. String operators: such union or concatenation of strings of characters. For example, we can use the plus symbol + to concatenate the strings “Hello” and the string “world” to produce the string “Hello world”. These operators allow us to manipulate strings.
  2. Writing or storing a value inside a variable. This can be performed by an assignment operation such as a = b.

Variables in Flowcharts & Pseudocode

The table below lists the flowchart blocks used to represent variables, as well as the corresponding pseudocode:

Operation Flowchart Pseudocode
Declare Declare Variable Flowchart Block Declare Variable Flowchart Block X = 0
Assign Assign Variable Flowchart Block Assign Variable Flowchart Block X = 5
Declare & Assign Declare and Assign Variable Flowchart Block Declare and Assign Variable Flowchart Block X = 5

Notice that variables must be assigned a value when declared in pseudocode. By default, most programming languages automatically assign the value $0$ to a new integer variable, so we’ll use that value in our pseudocode as well.

Likewise, variables in a flowchart are given a type, whereas variables in pseudocode are not. Instead, the data type of those variables can be inferred by the values stored in them.

Variables in Python

Variables in Python are simply defined by giving them a value. The type of the variable in inferred from the data stored in it at any given time, and a variable’s type may change throughout the program as different values are assigned to it.

To define a variable, we can simply use an assignment statement to give it a value:

x = 5
y = 3.5

Casting

We can also convert, or cast, data between different types. When we do this, the results may vary a bit due to how computers store and calculate numbers. So, it is always best to fully test any code that casts data between data types to make sure it works as expected.

To cast, we can simply use the new type as a function and place the value to be converted in parentheses:

x = 1.5
y = int(x)

This will convert the floating point value stored in x to an integer value stored in y.

Conditionals

YouTube Video

The conditional statement, also known as the If-Then statement, is used to control the program’s flow by checking the value of a Boolean statement and determining if a block of code should be executed based on that value. This is the simplest conditional instruction. If the condition is true, the block enclosed within the statement is executed. If it is false, then the code in the block is skipped.

A more advanced conditional statement, the If-Then-Else or If-Else statement, includes two blocks. The first block will be executed if the Boolean statement is true. If the Boolean statement is false, then the second block of code will be executed instead.

Simple conditions are obtained by means of the relational operators, such as <, >, and ==, which allow you to compare two elements, such as two numbers, or a variable and a number, or two variables. Compound conditions are obtained by composing two or more simple conditions through the logical operators and, or, and not.

Boolean Logic Review

YouTube Video

Recall that the Boolean logic operators and, or, and not can be used to construct more complex Boolean logic statements.

Or

For example, consider the statement x <= 5. This could be broken down into two statements, combined by the or operation: x < 5 or x == 5. The table below, called a truth table, gives the result of the or operation based on the values of the two operands:

Operand 1 Operand 2 Operand 1 or Operand 2
False False False
False True True
True False True
True True True

As shown above, the result of the or operation is True if at least one of the operands is True.

And

Likewise, to express the mathematical condition 3 < a < 5 we can use the logical operator and by dividing the mathematical condition into two logical conditions: a > 3 and a < 5. The table below gives the result of the and operation based on the values of the two operands:

Operand 1 Operand 2 Operand 1 or Operand 2
False False False
False True False
True False False
True True True

As shown above, the result of the and operation is True if both of the operands are True.

Not

Finally, the not logical operator is used to reverse, or invert, the value of a Boolean statement. For example, we can express the logical statement x < 3 as not (x >= 3), using the not operator to invert the value of the statement. The table below gives the result of the not operation based on the value of its operand:

Operand not Operand
False True
True False

In propositional logic, the completeness theorem shows that all other logical operators can be obtained by appropriately combining the and, or and not operators. So, by just understanding these three operators, we can construct any other Boolean logic statement.

Conditionals in Flowcharts & Pseudocode

The table below lists the flowchart blocks used to represent conditional statements, as well as the corresponding pseudocode:

Operation Flowchart Pseudocode
If-Then If-Then Flowchart Block If-Then Flowchart Block
if A < 5 then
A = 5
end if
If-Then-Else If-Then-Else Flowchart Block If-Then-Else Flowchart Block
if A < 5 then
A = 5
else
A = 10
end if

Conditionals in Practice

The mechanism for determining which block an If-Then-Else statement executes is the following:

  1. If the initial condition is true, execute the instructions enclosed between if and else
  2. If the initial condition is false, execute the instructions between the else and the end of the block

To understand how a conditional statement works, let’s look at this example of a simple If-Then-Else statement. Consider the following flowchart:

If-Then-Else Flowchart Block If-Then-Else Flowchart Block

In this case, if a is less than zero, the output message will be “The value of a is less than zero”. Otherwise, if a is not less than zero (that is, if a is greater than or equal to zero), the output message will be “The value of a is greater than or equal to zero”.

Nesting

We can also nest conditional statements together, making more complex programs.

Consider the following flowchart:

If-Then-Else Nested Flowchart Block If-Then-Else Nested Flowchart Block

In this case, if a is less than zero the output message will be “The value of a is less than zero”. Otherwise (that is, if a is not less than zero so if a is greater than or equal to zero) the block checks whether a is equal to zero; if so, the output message will be “The value of a is equal to zero”. Otherwise (that is, if the first condition is false, i.e. a >= 0 and the second condition is false, i.e. is nonzero; the two conditions must be both true as if they were bound by a logical and, and they are the same as the condition a > 0) the output message will be “The value of a is greater than zero”.

Conditionals in Python

To see how conditional statements look in Python, let’s recreate them from the flowcharts shown above.

If-Then Flowchart Block If-Then Flowchart Block

if a < 5:
    a = 5

If-Then-Else Flowchart Block If-Then-Else Flowchart Block

if a < 5:
    a = 5
else:
    a = 10

If-Then-Else Nested Flowchart Block If-Then-Else Nested Flowchart Block

if a < 0:
    print("The value of a is less than zero")
elif a == 0:
    print("The value of a is equal to zero")
else:
    print("The value of a is greater than zero")

As we can see in the examples above, we must carefully indent each block of code to help set it apart from the other parts of the program. In addition, each line containing if, elif and else must end in a colon :.

Loops

YouTube Video

Loops are another way we can control the flow of our program, this time by repeating steps based on a given criteria. A computer is able to repeat the same instructions many times. There are several ways to tell a computer to repeat a sequence of instructions:

  • Repeat an infinite number of times, e.g. while true. This construct is useful in software applications such as servers that will offer a service. The service is supposed to be available forever.
  • Repeat a specific number of times, e.g. Repeat 10 times or for i = 1 to 10. This loop can be used when you know the number of repetitions. There are also loops that allow you to repeat as many times as there are elements of a collection, such as for each item in list
  • Repeat according to a condition. The number of repetitions depends on the condition. Most programming languages support the while loop, which repeats while the condition is true.

In repeat while loops, the number of repetitions depends on the occurrence of a condition: the cycle repeats if the condition is true. Loops can also be nested, just like conditional statements.

Loops in Flowcharts & Pseudocode

The table below lists the flowchart blocks used to represent loop statements, as well as the corresponding pseudocode:

Operation Flowchart Pseudocode
While Loop While Loop Flowchart Block While Loop Flowchart Block
loop while A < 5
A = A + 1
end loop
For Loop For Loop Flowchart Block For Loop Flowchart Block
loop I from 1 to 10
A = A + I
end loop
For Loop with Step For Loop with Step Flowchart Block For Loop with Step Flowchart Block
loop I from 1 to 10 step by 2
A = A + I
end loop
For Each Loop For Each Loop Flowchart Block For Each Loop Flowchart Block
loop each I in LIST
A = A + I
end loop

Loops in Python

To see how loops look in Python, let’s recreate them from the flowcharts shown above.

While Loop Flowchart Block While Loop Flowchart Block

while a < 5:
    a = a + 1

For Loop Flowchart Block For Loop Flowchart Block

for i in range(1, 11):
    a = a + i

For Loop with Step Flowchart Block For Loop with Step Flowchart Block

for i in range(1, 11, 2):
    a = a + i

For Each Loop Flowchart Block For Each Loop Flowchart Block

for i in list:
    a = a + i

As we can see in the examples above, we must carefully indent each block of code to help set it apart from the other parts of the program. In addition, each line containing for and while must end in a colon :. Finally, notice that the range() function in Python does not include the second parameter in the output. So, to get the numbers $1$ through $10$, inclusive, we must use range(1, 11) in our code.

Lists

YouTube Video

Post Office Boxes Post Office Boxes^[File:USPS Post office boxes 1.jpg. (2017, May 17). Wikimedia Commons, the free media repository. Retrieved 18:17, November 5, 2018 from https://commons.wikimedia.org/w/index.php?title=File:USPS_Post_office_boxes_1.jpg&oldid=244476438.]

Arrays allow us to store multiple values in the same variable, using an index to determine which value we wish to store or retrieve from the array. We can think of arrays like a set of post office boxes. Each one has the same physical address, the post office, but within the post office we can find an individual box based on its own box number.

Some programming languages, such as Java, use arrays that are statically sized when they are first created, and those arrays cannot be resized later. In addition, many languages that require variables to be declared with a type only allow a single variable type to be stored in an array.

Other languages, such as Python, use lists in place of arrays. List can be resized, and in untyped languages such as Python they can store different data types within the same list.

Arrays in Flowcharts & Pseudocode

The table below lists the flowchart blocks used to represent arrays, as well as the corresponding pseudocode:

Operation Flowchart Pseudocode
Declare Array Declare Array Flowchart Block Declare Array Flowchart Block
ARR = new array[5]
Store Item Store Item in Array Flowchart Block Store Item in Array Flowchart Block
ARR[0] = 5 
Retrieve Item Retrieve Item from Array Flowchart Block Retrieve Item from Array Flowchart Block
X = ARR[0]

Lists in Python

Let’s review the syntax for working with lists in Python.

List Creation

To define a list in Python, we can simply place values inside of a set of square brackets [], separated by commas ,:

arr = [1, 2]
arr2 = [1.2, 3.4]

We can also create an empty list by simply omitting any items inside the square brackets

arr3 = []

Adding Items

Once we’ve created a list in Python, we can add items to the end of the list using the append() method:

arr4 = []
arr4.append(1)
arr4.append(2)
arr4.append(3)

Accessing List Elements

Once the list is created, we can access individual items in the list by placing the index in square brackets [] after the list’s variable name:

x = arr[2]
arr[1] = 5

Multidimensional List

Python lists can also be created with multiple dimensions, simply by appending lists as elements in a base list.

two_dim_arr = []
two_dim_arr.append([1, 2, 3])
two_dim_arr.append([4, 5, 6])

They can also be created through the use of lists as individual elements in a list when it is defined:

another_arr = [[1, 2, 3], [4, 5, 6]]

To access elements in a multidimensional list, simply include additional sets of square brackets containing an index [] for each dimenison:

another_arr = [[1, 2, 3], [4, 5, 6]]
x = another_arr[1, 2]
another_arr[0, 1] = 5

List Operations

There are several operations that can be performed on lists in Python as well:

arr = [1, 2, 3, 4, 5]

# list length
length = len(arr)

# concatenation
arr2 = [6, 7]
arr3 = arr + arr2  # [1, 2, 3, 4, 5, 6, 7]

# slicing
b = arr[2:4]   # [3, 4]

List Loops

Finally, we can use a special form of loop, called a For Each loop, to iterate through items in a list in Python:

arr = [1, 2, 3, 4 5]

for i in arr:
    print(i)

Once important thing to note is that lists accessed within a For Each loop are read only. So, we cannot change the values stored in the list using this loop, but we can access them. If we want to change them, we should use a standard For loop to iterate through the indices of the list:

arr = [1, 2, 3, 4, 5]

for i in range(0, len(arr)):
    arr[i] = arr[i] + 5

References

Variable Roles

Variables in our programs can be used in a variety of different roles. The simplest role for any variable is to store a value that does not change throughout the entire program. Most variables, however, fit into one of several roles throughout the program.

To help us understand these roles, let’s review them in detail here. As we move forward in this course, we’ll see many different data structures that use variables in these ways, so it helps to know each of them early on!

Container

Container Variable Role Flowchart Container Variable Role Flowchart

OPERAND = 1

In this role, the variable is used to hold a value. This value can be changed during the program execution. In the example:

  1. a variable named operand of type Integer is declared
  2. the value 1 is assigned to the variable

Counter

Counter Variable Role Flowchart Counter Variable Role Flowchart

loop COUNTER from 1 to 10
    print COUNTER
end loop

In this role, variables are used to hold a sequence of values known beforehand. In the example, the variable counter holds values from 1 to 10 and these values are conveyed to the user.

Accumulator

Accumulator Variable Role Flowchart Accumulator Variable Role Flowchart

SUM = 0
loop COUNTER from 1 to 10
    SUM = SUM + COUNTER
end loop
print SUM

In this role, the variable is used to hold a value that aggregates, summarizes, and synthesize multiple values by means of an operation such as sum, product, mean, geometric mean, or median. In the example, we calculate the sum of the first ten numbers in the accumulator variable sum.

Recent Value

Recent Value Variable Role Flowchart Recent Value Variable Role Flowchart

ANSWER = 0
print "Input a number"
input ANSWER
print "You input " + ANSWER

In this role, the variable answer contains the last value encountered so far in a data series, such as the last value that the program receives from the user.

Extreme Value

Extreme Value Variable Role Flowchart Extreme Value Variable Role Flowchart

COUNTER = 0
SCORES = new array[10]
input SCORES
MAX = SCORES[0]
loop COUNTER from 0 to (size of SCORES) - 1
    if SCORES[COUNTER] > MAX
        MAX = SCORES[COUNTER]
    end if
end loop
print "Max value: " + MAX

In this role, the variable contains the value that is most appropriate for the purpose of the program, e.g. the minimum or the maximum. The instruction scores[counter] > max checks if the list item under observation is greater than the maximum. If the condition is true the value of the maximum variable is changed.

Follower

Follower Variable Role Flowchart Follower Variable Role Flowchart

COUNTER = 0
SCORES = new array[10]
input SCORES
MAX = SCORES[0]
SECOND = MAX
loop COUNTER from 0 to (size of SCORES) - 1
    if SCORES[COUNTER] > MAX
        SECOND = MAX
        MAX = SCORES[COUNTER]
    else if SCORES[COUNTER] > SECOND
        SECOND = SCORES[COUNTER]
    end if
end loop
print "Max value: " + MAX + " Second max: " + SECOND

A variable, such as second, to which you assign the value of another variable that will be changed immediately after. In the example, the second variable contains the second largest value in a list.

Flag

Flag Variable Role Flowchart Flag Variable Role Flowchart

MISTAKE = false
COUNTER = 0
input COUNTER
if COUNTER < 0
    MISTAKE = true
else
    MISTAKE = false
end if

A flag variable is used to report the occurrence or not of a particular condition, e.g. the occurrence of an error, the first execution, etc..

Temporary

Temporary Variable Role Flowchart Temporary Variable Role Flowchart

TEMP = FIRST
FIRST = SECOND
SECOND = TEMP

A variable used to hold a temporary value. For example, to exchange two variables, you must have a temporary variable temp to store a value before it is replaced.

Index

Index Variable Role Flowchart Index Variable Role Flowchart

SCORES = new array[10]
input SCORES
loop INDEX from 0 to 9
    print SCORES[INDEX]
end loop

A variable used to indicate the position of the current item in a set of elements, such as the current item in an array of elements. The index variable here is a great example.

References

  • Sajaniemi, J. (2005, October). Roles of variables and learning to program. In Proc. 3rd Panhellenic Conf. Didactics of Informatics, Jimoyiannis A (ed) University of Peloponnese, Korinthos, Greece.
  • Hosanee, M., & Rana, M. E. (2018). A Refined Approach for Understanding Role of Variables in Elementary Programming. Jour of Adv Research in Dynamical & Control Systems, 10(11).

Strings

YouTube Video

Strings are another very important data type in programming. A string is simply a set of characters that represent text in our programs. We can then write programs that use and manipulate strings in a variety of ways, allowing us to easily work with textual data.

Strings in Flowcharts & Pseudocode

The table below lists the flowchart blocks used to represent strings, as well as the corresponding pseudocode:

Operation Flowchart Pseudocode
Create String Create String Flowchart Block Create String Flowchart Block
STR = “abc”
Access Character Access Character in String Flowchart Block Access Character in String Flowchart Block
C = STR[0]
String Length String Length Flowchart Block String Length Flowchart Block
X = size of STR

Strings in Python

Let’s review the syntax for working with strings in Python.

String Creation

Strings in Python are declared just like any other variable:

s = "abc123"

Notice that strings are enclosed in double quotations marks ". Since Python does not have a data type for a single character, we can do the same for single character strings as well:

c = "a"

There are several special characters we can include in our strings. Here are a few of the more common ones:

  • \' - Single Quotation Mark (usually not required)
  • \" - Double Quotation Mark
  • \n - New Line
  • \t - Tab

String Parsing

YouTube Video

Most of the time, we will need to be able to parse strings in order to read input from the user. This is easily done using Python. Let’s refer to the skeleton code given in an exercise:

# Load required modules
import sys


def main(argv):

    # create a file reader for terminal input
    reader = sys.stdin

    # read a single integer from the terminal
    x = int(reader.readline())

    # -=-=-=-=- MORE CODE GOES HERE -=-=-=-=- 


# main guard
if __name__ == "__main__":
    main(sys.argv)

This code will initialize a variable called reader to read input from the terminal, or sys.stdin in Python.

Once we have a reader initialized, we can read a line of data from the input as follows:

line = reader.readline()

If we know that line will contain a single item of a different data type, such as an integer, we can also convert that input using the appropriate method:

x = int(reader.readline())

Finally, if we have read an entire string of input consisting of multiple parts, we can use the split method to split the string in to tokens that are separated by a special delimiter. When we do this, we’ll have to use special methods to convert the strings to other primitive data types. Here’s an example:

line = "This 1 is 2.0 true"
parts = line.split(" ")
first = parts[0]
second = int(parts[1])
third = parts[2]
fourth = float(parts[3])
fifth = bool(parts[4])

In this example, we are able to split the first string variable into $5$ parts, each one separated by a space in the original string. Then, we can use methods such as int() to convert each individual string token into the desired data type.

Reading Input in a Loop

When reading an unknown number of lines of input, we can use a loop in Python such as the following example:

for line in reader:
    line = line.strip()
    if not line or len(line) == 0:
        break
    
    # parse the input

This will read input until either a blank line is received (usually via the terminal), or there is no more input available to read (from a file).

String Operations

There are also several operations we can perform on strings in Python:

s1 = "This"
s2 = "That"

# string length
x = len(s1)

# string comparison
# can use standard comparison operators
b1 = s1 == s2
b2 = s1 < s2 

# concatenation
s3 = s1 + " " + s2

Additional methods can be found on the Python Built-In Types: str and Python Common String Operations pages

String Formatting

Strings can also be used to create formatted output in Python through the use of f-strings. Here’s a short example:

sum = 123
avg = 1.23
name = "Student"

print(f"{name}: Your score is {sum} with an average of {avg}.")

When we run this program, the output will be:

Student: Your score is 123 with an average of 1.23.

Each item in the formatted output can also be given additional attributes such as width and precision. More details can be found on the Python Format String Syntax page.

References

Exceptions

YouTube Video

An exception is an error that a program encounters when it is running. While some errors cannot be dealt with directly by the program, many of these exceptions can be caught and handled directly in our programs.

Exceptions in Flowcharts & Pseudocode

There isn’t really a standard way to display exceptions in flowcharts and pseudocode, but we can easily create a system that works well for our needs. Below are the flowchart blocks and pseudocode examples we’ll use in this course to represent exceptions and exception handling:

Operation Flowchart Pseudocode
Throw Exception Throw Exception Flowchart Block Throw Exception Flowchart Block
throw INPUT EXCEPTION
Catch Exception Catch Exception in String Flowchart Block Catch Exception in String Flowchart Block
catch INPUT EXCEPTION
Try-Catch Example Try-Catch Example Flowchart Blocks Try-Catch Example Flowchart Blocks
X = 0
try
input X
if X < 0
throw INPUT EXCEPTION
end if
print X
catch INPUT EXCEPTION
print “Error”
end try

Exceptions in Python

Let’s review the syntax for working with exceptions in Python.

Try-Catch

In Python, we can use a Try-Except statement to detect and handle exceptions in our code:

# Load required modules
import sys

try:
    reader = open(sys.argv[1])
    x = int(reader.readline())
    print(x)

except Exception as e:
    print("Error!")

In this example, the program will try to open a file using the first command-line argument as a file name. There are several exceptions that could occur in this code, such as a ValueError, a IndexError, a FileNotFoundError, and more. They can also be handled individually:

# Load required modules
import sys

try:
    reader = open(sys.argv[1])
    x = int(reader.readline())
    print(x)

except IndexError as e:
    print("Error: Invalid Array Index!")
except FileNotFoundError as e:
    print("Error: File Not Found!")
except ValueError as e:
    print("Error: Input Does Not Match Expected Format!")
except OSError as e:
    print("Error: OS Exception!")

Throw

If desired, we can also raise our own exceptions in Python:

if y == 0:
    raise ValueError("Cannot divide by zero")
else:
    z = x / y
    print(z)

This will cause an exception to be thrown if the value of y is equal to $0.0$.

Finally

We can also add Else and Finally blocks at the end of each Try-Except block. A Finally block will be executed whenever the control exits the Try-Except block, even through the use of a return statement to return from a method. The Else block will be executed if the entire Try-Except block completes without any exceptions being raised:

# Load required modules
import sys

try:
    reader = open(sys.argv[1])
    x = int(reader.readline())
    print(x)

except Exception as e:
    print("Error!")
else:
    print("No Errors!")
finally:
    print("Finally Block")

With Statement

When working with resources such as files in Python, we can also use a With block to ensure that those resources are properly closed when we are done with them. In addition, a With block will automatically catch and suppress any exceptions that result from trying to close the resource after an exception has occurred, preventing us from being bombarded by unavoidable exceptions. Here’s an example:

import sys

try:    
    with open(sys.argv[1]) as reader:
        x = int(reader.readline())
        print(x)

except IndexError as e:
    print("Error: Invalid Array Index!")
except ValueError as e:
    print("ValueError: {}".format(e))
except FileNotFoundError as e:
    print("FileNotFoundError: {}".format(e))

In this example, we are opening a file using the open() method inside of the With statement. That file will automatically be closed once the program leaves the With statement.

References

I/O

One of the major features of a modern computer is the ability to store and retrieve data from the computer’s file system. So, we need to be able to access the file system in our code in order to build useful programs. Thankfully, most modern programming languages include a way to do this.

I/O in Flowcharts & Pseudocode

Most operations working with files in code take the form of method calls. So, we will primarily use the call block to represent operations on files:

Operation Flowchart Pseudocode
Open File Open File Flowchart Block Open File Flowchart Block
S = “file.txt”
FILE = open(S)
Read from File Read from File Flowchart Block Read from File Flowchart Block
S = FILE.read()
Write to File Write to File Flowchart Blocks Write to File Flowchart Blocks
FILE.write(X)

I/O in Python

Let’s review the syntax for working with files in Python.

Reading Files

To open a file in Python, we can simply use the open() method. Here is an example:

import sys

try:
    reader = open(sys.argv[1])
except FileNotFoundError as e:
    print("FileNotFoundError: {}".format(e))
    sys.exit()
except IndexError as e:
    print("IndexError: {}".format(e))
    reader = sys.stdin
  
with reader:
    # -=-=-=-=- MORE CODE GOES HERE -=-=-=-=-

In this example, the program will try to open a file provided as the first command-line argument. If no argument is provided, it will automatically read from standard input instead. However, if an argument is provided, it will try to open it as a file. In addition, we can use a With statement to make sure the file is properly closed once it is open.

Once we have opened the file, we can read the file just like we would any other input:

for line in reader:
    line = line.strip()
    if not line or len(line) == 0:
        break
    # use line variable

Writing Files

To write to a file, we must open it a different way. In Python, we must provide an optional "w" argument to the open() method call to make the file writable:

import sys

try:
    with open(sys.argv[1], "w") as writer:
        writer.write("Hello World")
        writer.write("\n")

except IndexError as e:
    # no arguments provided
    print("IndexError: {}".format(e))
    sys.exit()
except IOError as e:
    # unable to write to the file
    print("IOError: {}".format(e))
    sys.exit()
except Exception as e:
    # unknown exception
    print("Exception: {}".format(e))
    sys.exit()

This example shows to how to open a file for writing using the open() method inside of a With statement. It also lists several of the common exceptions and their cause.

Resources

Documentation

It is important both to easily grasp the design choice and the code structure of a project even long after it has been completed. The documentation process starts by commenting the code. Code comments are usually intended for software developers and aim at clarifying the code by giving details of how it works. They are usually performed using inline or multiple lines comments using the language syntax.

Single Line Comments

As we’ve seen before, we can add single-line comments to our Python programs using a hash symbol # before a line in our source file:

# this is a comment
x = 5

# this is also a comment
b = True

Docstrings

Finally, Python also includes a secondary type of comment that spans multiple lines, specifically for creating documentation. A docstring is usually the first line of text inside of a class or method definition, and is surrounded by three double quotes """ with one set of three on each end.

These comments are specifically designed to provide information about classes and methods in our code. Here’s a quick example using a simple class:

class IntTuple:
  """ Represents a tuple containing two integer values
  
  This class is an adaptation of a class developed for Java
  that mimics the built-in tuples in Python
  
  Attributes
  ----------
  first : int
      the first element in the tuple
  second : int
      the second element in the tuple
  """
  
  def __init__(self, one, two):
    """ Initializes a new IntTuple object
    
    Parameters
    ----------
    one : int
        the first element in the new tuple
    two : int
        the second element in the new tuple
    """
    self.first = one
    self.second = two

Unfortunately, Python does not enforce a particular style for these docstrings, so there are many different formats used in practice. To learn more, we can consult the following references.

References

Style

To make your code easier to read, many textbooks and companies use a style guide that defines some of the formating rules that you should follow in your source code. In Python, these rules are very important, as the structure of your code is defined by the layout. We’ll learn more about that in a later module.

For this book, most of the examples will be presented using the guidelines in the Style Guide for Python. However, by default Codio used to use 2 spaces for an indentation level instead of 4, so that is the format that will be used in some examples in this book.

Google also provides a comprehensive style guide that is recommended reading if you’d like to learn more about how to format your source code.

Review Summary

That’s a quick overview of the basics we’ll need to know before starting the new content in this course. The next module will provide a quick review of object-oriented programming concepts as well as the model-view-controller or MVC architecture, both of which will be used heavily in this course.