Topic Name Description
Course Introduction Course Syllabus
1.1: Introduction to Python 3 Introducing Python

Python is an ideal language for learning to program. Watch this video to see just how useful Python can be. After this, we will introduce an integrated development environment (IDE) and begin programming. The IDE will make it simple to quickly visualize and experience the results of a set of Python programming instructions.

1.2: Accessing the Repl.it IDE The Repl.it IDE

In this course, we will use the Repl.it IDE. This web-based IDE requires no installation, which means that you can begin programming in Python immediately. We will use this IDE throughout the course. On the page, you should see two windows arranged side-by-side in columns. In this unit, we will focus on the rightmost window. This window has a command line prompt, which is indicated by the >. We can type basic Python commands using this command prompt. As we progress through the course, we will start to use the middle and left windows.

You will need to have JavaScript enabled in your browser to use this IDE.

1.3: Python 3 Data Types: int and float Compare and Contrast int vs. float
Programming languages must distinguish between different types of data. Since we want to introduce simple Python computations, it makes sense to discuss numerical data. The goal of this section is to introduce two fundamental numerical data types: int and float. The int data type refers to integer data. Numbers not containing digits to the right of the decimal point such as - 10 , 0, and 357 are integers. The float data type refers to floating-point data. Numbers containing digits to the right of the decimal point such as 1.3, -3.14, and 300.345567 are floating-point numbers.

After you complete this section, you should be able to explain the difference between int and float. There are deeper reasons (beyond the scope of this course) why you might distinguish between these data types; those have to do with how they are represented within a computer system. Our goal for this section is simply to be able to visually identify integer and floating-point numbers. On this page, you will see more examples of int and float.

The int data type refers to integer numerical data. In the rightmost window of the Repl.it IDE, use your mouse to click to the right of the > command prompt. Next, type the integer 2 and press the "enter" key on your keyboard. You should see the IDE echo the value back to the screen. Try this a few times with other examples to be sure you understand the int data type.

The float data type refers to floating-point numerical data. In the rightmost window of the Repl.it IDE, use your mouse to click to the right of the > command prompt. Next, type the floating-point number 2.57 and press the "enter" key on your keyboard. You should see the IDE echo the value back to the screen. Try this a few times with other examples that have been provided to be sure you understand the float data type.

It is of the utmost importance that you understand the value 2 is of type int, while 2.0 is of type float. On paper, this might not seem like a big difference, but the decimal point is how a computer tells the difference between these two data types.

Scientific Notation for Floating Point Numbers

Another way of typing floating-point data is to use scientific notation. For instance, the number 0.0012 can also be entered as 1.2e-3. In this example, "e-3" means "10 to raised to the minus three power" and this value is multiplied by 1.2; hence, 1.2e-3 is equivalent to 0.0012. Try typing 0.0012 into the Repl.it command line, then try entering 1.2e-3. You should see that Python views both entries as the same value. Scientific notation is very useful when the exponents are very positive or very negative. In data science, exponents in numbers such as -5.63e127 or 2.134589e-63 would not be uncommon. Rather than writing out numbers of this kind in their full form, scientific notation offers a more compact, readable form for presenting float data. If you need to review scientific notation, watch this video.

1.4: Variable Assignment Variables and Assignment Statements

Computers must be able to remember and store data. This can be accomplished by creating a variable to house a given value. The assignment operator = is used to associate a variable name with a given value. For example, type the command:

a=3.45

in the command line window. This command assigns the value 3.45 to the variable named a. Next, type the command:

a

in the command window and hit the enter key. You should see the value contained in the variable a echoed to the screen. This variable will remember the value 3.45 until it is assigned a different value. To see this, type these two commands:

a=7.32

and then

a

You should see the new value contained in the variable a echoed to the screen. The new value has "overwritten" the old value. We must be careful since once an old value has been overwritten, it is no longer remembered. The new value is now what is being remembered.

Although we will not discuss arithmetic operations in detail until the next unit, you can at least be equipped with the syntax for basic operations: + (addition), - (subtraction), * (multiplication), / (division)

For example, entering these command sequentially into the command line window:

a=7.32
b=a+5
b

would result in 12.32 being echoed to the screen (just as you would expect from a calculator). The syntax for multiplication works similarly. For example:

a=7
b=a*5
b

would result in 35 being echoed to the screen because the variable b has been assigned the value a*5 where, at the time of execution, the variable a contains a value of 7.

After you read, you should be able to execute simple assignment commands using integer and float values in the command window of the Repl.it IDE. Try typing some more of the examples from this web page to convince yourself that a variable has been assigned a specific value.

Reserved Words and Variable Naming Conventions

Python has its own set of reserved words that, in general, should not be chosen as variable names. As we dive deeper into the course, it will become clearer how to apply these reserved words. For now, just be aware that your variable name choices should avoid the words on this list. Otherwise, though, you can choose any variable name you like. It is important to think about how variable names should be chosen in practical applications. To help others understand your work, you should choose variable names that fit their applications. For example:

account_balance=2034.12

might reflect the balance contained in a bank account. You will build the skill of sensibly choosing variable names naturally as you work through more programming examples.

1.5: Basic Python Output Using the print Function Using Variables in Python

The "print" function is a Python instruction that will output variable values and results to the computer screen. This instruction will allow us to automatically output data results to the screen when running a program. This section reviews what we've covered so far and introduces examples of the print function. Try executing these instructions in the command line window to make sure you understand how to use the print function:

z=1.45
print(z)

Notice how the print function outputs the value of the variable z to the screen.

It is possible to use the print command in a slightly more sophisticated way. Type this set of commands in the command window:

temperature=40
print('Temperature outside = ', temperature)

Observe, it is possible to "dress up" the screen output by adding some extra descriptive text. We will see more examples of this later on as we introduce and develop expertise with the string data type. But, as a preview of using the print function with text, try typing this command:

print('Hello world!')

Congratulations! You have now executed what is probably the most-used example in just about every introductory programming course.

Read this page to see more examples of using the print function. Try typing some of those examples in the Repl.it IDE to be sure you are comfortable with the print function. Consider executing these instructions one after the other (that is, sequentially):

var1=22
var1=-35
var1=308

What value will the variable var1 contain after these instructions are executed? You can check your answer by using the print function.

1.6: More Python 3 Data Types: str The Basics of Strings

Our introduction would not be complete without discussing how to work with text and character data. In this section, you will learn about the string data type and assigning a variable of type "str". String data is text or character data. To assign a variable of type str, the text string must be placed in quotes:

string_example='This is the text string'

To see that this variable assignment has taken place, type the command:

print(string_example)

and you should see the text string echoed to the screen. To assign a variable of type str, you can use either single or double quotes, but single quotes are often the convention of choice. As we dive deeper into the course, many interesting operations and computations using the string data type will be presented. Read this page to learn more about the string variable type. Use the Repl.it IDE to practice some of the string commands.

Values, Types, Variable Names, and Keywords

Read these examples of using the 'print' and 'type' functions. You can also try to use them in the Repl.it command line.

Unit 1 Review and Assessment Unit 1 Review

In this video, course designer Eric Sakk walks through the major topics we covered in Unit 1. As you watch, work through the exercises to try them out yourself.

2.1: Arithmetic Operators: +, -, *, /, **, %, and // Practice With Arithmetic Operators

Practice these programming examples to internalize these concepts.

2.2: Operator Precedence and Using Parentheses PEMDAS

Execute these two instructions in the Repl.it command line window:

8**(1/3)
8**1/3

You should recognize the first instruction from the previous section. Observe that these instructions yield two totally different answers. The reason is that there is an order in which operators are evaluated. The "order of operations" and "operator precedence" define how arithmetic calculations are to be evaluated. As expected from basic arithmetic, exponentiation takes place before multiplication and division which take place before addition and subtraction. In addition, operations are generally read from left to right.

As an example, consider the expression 8**1/3 as shown above. In this case, exponentiation taking precedence over division means that 8**1 is computed first to obtain a value of 8 and then that result is divided by 3. Hence, the final computed result is 8/3 = 2.6666...67. Notice that, when parentheses are added around the exponent to form 8**(1/3), the exponent evaluates to 1/3 and the cube root of 8 is computed. The term inside the parentheses has higher precedence and takes place before exponentiating. This should be a refresher about the order arithmetic expressions are evaluated in.

Practice With Operator Precedence

Now, we will consider order precedence when operations are phrased within the Python programming language. Before running this set of instructions in the run window, try to predict the value each variable will contain.

a=3
b=4
c=1
d=5
e=3
f=a+b-c*d+e/d
g=a+b-c*(d+e)/d
h=a+(b-c)*d+e/d
i=(a+b-c)*d+e/d


It is important to note that // and % are considered division operations and, because of that, have precedence equal to * and /. Try to predict the value of each variable in these commands:

v=2
w=3
x=4
y=19
z=23
a=v**v//x%x+y%w*z//x
b=v**(v//x)%x+y%(w*z)//x


Again, you should use insert some print commands to verify your answer.

A useful guiding principle when writing code is: if the order precedence is not clear to you by looking at the expression, use parentheses to make things obvious, since parentheses always take the highest precedence.

2.3: Relational and Logical Operators The bool Data Type

The bool data type is necessary for the evaluation of logical data (which is inherently different from the numerical or string data types introduced so far). "bool" stands for Boolean data which can only take on one of two possible values: True or False. You should recall from the previous unit that True and False are reserved words within the Python language. Try executing these commands in the Repl.it run window:

a=True
print(a)
print(type(a))
b=False
print(b)
print(type(b))

You should see that True and False appear in your program as blue text indicating that they are reserved Python words. Furthermore, the data type should be identified as bool. Let's investigate how this data type can be used.

Relational operators are those that compare values in order to determine their relationship. Here is a shortlist of very useful relational operators:

• == Equals
• != Not Equals
• > Greater Than
• < Less Than
• <= Less Than or Equal To
• >= Greater Than or Equal To

Copy and paste these commands into the Repl.it run window:

a=2
b=3
print(a==b)
print(a!=b)
print(a>=b)
print(a>=a)
print(a<=a)
print(a>b)
print(a < b) 

It should be clear why these are called relational operators. Also, note that the only possible answers when using these operators are either True or False.

Be EXTREMELY careful to NEVER confuse the assignment operator (=) with the relational equals (==) operator. They serve two totally different purposes. Copy and paste and run this set of commands:

a=2
b=5
a=b
print(a)
a=2
b=5
print(a==b)

The assignment operator assigns the numerical value contained in the variable b to the variable a. The relational operator compares the variables a and b for equality which evaluates to the bool data type False.

Finally, there are logical operators that allow us to form combinations of logical expressions. Watch the video for a description of relational and logical operators. Afterwards, you should understand these definitions for logical operators given two boolean variables x and y:

• not x: Logical complement: if x is True, not x is False. If x is False, not x is True
• x and y: Can only be True if both x and y are True, otherwise evaluates to False
• x or y: Can only be False if both x and y are False, otherwise evaluates to True

These operators will be incredibly important in the next unit. For now, we just need to practice using them in order to get used to the syntax.

Practice with Relational and Logical Operators

Try these exercises for more practice with relational and logical operators.

2.4: Operator Precedence Revisited Operators and Expressions

Unit 2 Review and Assessment Unit 2 Review

In this video, course designer Eric Sakk walks through the major topics we covered in Unit 2. As you watch, work through the exercises to try them out yourself.

3.1: Reading Data from the Keyboard The Input Command

The input command is necessary when we want to obtain input from a keyboard. So far, variables have been initialized or assigned values within a given Python script, with commands such as:

a=3
b=27
c=a+b

It is often the case that a program requires keyboard input from the user to perform its function. This is exactly what the 'input' command is for. This instruction can output a message, and the program will wait for the user to input a value. Try running this command in the Repl.it run window:

city=input('Enter the name of the city where you are located: ')
print(city)

You should be aware that the input function returns data of type str (that is, string data). If numerical data is required, an extra step must be taken to perform a type conversion using either the int or float commands. Copy and paste this set of commands into the run window and then run code using an input value of 34 when prompted for user input:

temperature_str=input('Enter the temperature: ')
print(temperature_str)
print(type(temperature_str))
print()
temperature_int=int(input('Enter the temperature: '))
print(temperature_int)
print(type(temperature_int))
print()
temperature_float=float(input('Enter the temperature: '))
print(temperature_float)
print(type(temperature_float))
print()

The variable names have been chosen to emphasize and distinguish between their data types. The input command offers the convenience of creating user-defined values within a program. At the same time, it is important to make sure the input value's data type matches the intended use of the variable.

3.2: Using Conditional Statements if, else, and elif Statements

Read this for more on conditional statements.

3.3: Loop and Iterations Using "while" Loops

Loops are necessary when we need to perform a set of operations several times. The first type of loop we will discuss is called the while loop. The while loop checks a logical condition like the if statement. If the condition is true, the code inside the while loop will execute until the condition being checked becomes false. Run this code in Repl.it:

avalue= int(input('Please enter the number 10: '))
while (avalue != 10):
print('Your input value is not equal to 10')
avalue= int(input('Enter the number 10: '))
print('Thank you')
print('You entered a value of 10')

This while loop checks to see if the value input was equal to 10. If not, the while loop will continue to execute the indented code until a value of 10 is input. The syntax rules are similar to those of the if statements:

• The logical expression following the "while" must end with a colon (:)
• The code to be executed if the logical condition is satisfied must be indented.
• Indentation is how Python knows you have a group of commands inside the while statement Indentation can be accomplished in Repl.it using the "tab" key. In the Repl.it editor, this is equivalent to typing two spaces. Some Python editors prefer four spaces for indentation.

Make sure you run the examples provided in Repl.it. When we execute the code within a loop over and over again, the process is known as iteration.

Using "for" Loops

The for loop is useful when we know how many times a loop is to be executed. Rather than basing the number of iterations on a logical condition, the for loop controls the number of times a loop will iterate by counting or stepping through a series of values. Run this snippet of code in Repl.it:

for i in range(5):
print(i)

The range(5) command creates a series of five values from 0 to 4 for the variable i to cycle through. The statement for i in range(5) effectively means use the variable i to count through five values starting at 0 and stopping at 4 (Python, by design, begins counting with the value 0). Also, once again, pay close attention to the placement of the colon (:) at the end of the for statement as well as the indentation. The syntax rules should look very familiar at this point. They are exactly the same as for if statements and while loops.

Consider this next snippet of code:

n=8
sumval=0;
for i in range(n):
sumval = sumval+i
print('Adding ', i,'to the previous sum = ',sumval)

This loop counts from 0 to n-1, where n has been set to a value of 8. An initial sum is set to zero and then successive values of the variable i are added to the sum each time an iteration of the loop takes place. In other words, the loop counter variable i can be used within the loop as it is being updated. As will we see, the loop variable is often used as part of some computation within the loop. Here is an example of how powerful Python can be when using a for loop to cycle through a series of values.

strval='forever'
e_count=0
for letter in strval:
if letter =='e':
e_count = e_count + 1
print('The letter e occurred ', e_count, 'times')

Notice how the "if" statement is "nested" (and, therefore, indented) within the "for" loop. The variable letter cycles through each character in the string strval, which has been initialized to the string forever. If an "e" is found while iterating through each character, the count variable is incremented. When the loop is finished, the number of occurrences is output to the screen.

It is also possible to nest loops within loops. We will discuss more of these types of loops as we go deeper into the course. For now, run this code in Repl.it:

m=4
n=3
for i in range(m):
for j in range(n):
print('i=',i,' j=',j)

This is called a nested "for" loop because the inner "for" loop depending on the variable j is nested within the outer "for" loop, which depends on the variable i. This should be clear from the indentation of the inner loop with respect to the outer loop. For each iteration of the variable i, the variable j cycles through all of its possible values which depend upon range(m). In order for ito be updated to its next value, the inner loop must iterate through all of its values. Make sure you can relate the program output shown the screen to how the nested loop iterates through its values.

After you watch the video and test the examples in Repl.it, revisit the file in the "while" loop section and read through the section on "for" loops. Make sure to practice the for loop examples in Repl.it.

"break", "continue", and "pass" Statements

Sometimes it is necessary to exit a loop abruptly when a certain condition is met. The "break" statement is sometimes useful for such an application. Consider this code:

strval='forever'
for letter in strval:
if letter =='e':
break
print('The letter e has been found')

In this case, the break statement terminates the loop if the character  e is found in the strval string.

On the other hand, encountering a given condition within a loop may require skipping over a set of commands and effectively "fast-forward" to the next iteration. The "continue" statement is useful for these applications.

Finally, the "pass" statement within a loop is a null statement that does nothing. It is sometimes useful when placed in a program where code is intended but has not yet been written. Read this page and practice the examples.

3.4: Further Study More Useful Videos

Here are some supplementary videos that you can review if you'd like a bit more practice the concepts in this unit.

Unit 3 Review and Assessment Unit 3 Review

In this video, course designer Eric Sakk walks through the major topics we covered in Unit 3. As you watch, work through the exercises to try them out yourself.

4.1: Python Lists Creating Lists

A list is a data structure capable of storing different types of data. Run this set of commands in Repl.it:

a=2
b=3
alist_examp=[1,3.4,'asdf',96, True, 9.6,'zxcv',False, 2>5,a+b]
print(alist_examp)
print(type(alist_examp))
print('This list contains ', len(alist_examp), ' elements')

You should see the list output to the screen as well as the data type of the variable  alist_examp. Notice that the list contains bool, int, str, and float data. It also contains the result of relational and arithmetic operations. Any valid data type in Python can be placed within a list.

The data contained within the list are called elements. The list you printed contains 10 elements. You can figure this out by counting them by hand. There is also a command called len that will give you this information, which you can see in the example. len is a very useful command.

Pay very close attention to the syntax used to build the list. The left square bracket/right square bracket is known as a "container". Elements must be separated by a comma when building the list.

Pay very close attention to this example. Add this code on the line after print('This list contains ', len(alist_examp), ' elements').

tmp=alist_examp
print(tmp)
print(alist_examp)
tmp[3]='vbnm'
print(tmp)
print(alist_examp)

Notice that changing the value in the variable tmp also changed the value in the variable alist_examp. Initially, this appears to go against what we have learned about the assignment operation (=). For reasons that will be discussed in a later unit, when it comes to lists, Python views both variables as occupying the same space in memory. They are different names that refer to the same data. How then can we truly assign the list to a new variable that occupies a different place in memory and can be modified independently of the variable  alist_examp? This set of commands will accomplish this:

tmp=alist_examp.copy()
print(tmp)
print(alist_examp)
tmp[3]='vbnm'
print(tmp)
print(alist_examp)

This example introduces some new syntax that will soon become second nature. The command "alist_examp.copy()" is your first introduction to object-oriented syntax. The "copy()" portion of this command is what is known as a method. It is connected to the variable alist_exmp using the period or 'dot notation'. This command makes a true hard copy of the variable alist_examp so that modifications of tmp do not affect alist_examp.

Every variable type in Python is what is known as an "object". You will learn an immense amount about objects as we delve deeper into the course. The main point to realize is that there are several methods available for use with lists. The copy method we just introduced is one of them. Some other important ones worth mentioning at this point are pop, append, remove, and insert. Pay attention to the sections that describe these methods in detail.

Indexing

Read this for more on indexing.

Slicing

It is often the case that a program requires referencing a group of elements within a list (instead of a single element using a single value of the index). This can be accomplished by slicing. Consider running this example:

x=[101,-45,34,-300,8,9,-3,22,5]
print()
print(x)
print(x[0:9])

The colon operator can be used to index multiple elements with the list. The index on the left side of the colon (:) is the starting index. By Python's indexing convention, the value on the right side of the colon (:) indexes that value minus one (be careful with the right index). Since the variable x has 9 elements indexed from 0 to 8, x[0:9] references all indices from 0 to 8. Here are some more examples you should try:

print()
print(x[3:4])
print(x[3:5])
print(x[3:6])
print(x[3:7])
print(x[3:8])
print(x[3:9])

Again, you should be careful when using the right index since Python will sequence up to that value minus one. For the sake of convenience, there are also shorthand slicing techniques that do not require specifying the start or ending index when it assumed the complete rest of the list is being referenced:

print()
print(x[3:])
print(x[:4])

In addition to specifying the start and stop indices, you can also specify the "step". Here is an example that will count by twos from element 3 to element 7 (every other element starting at index 3). The step size is given by the index value after the second colon.

print()
print(x[3:8:2])

Finally, Python allows for negative indices where, by convention, the index -1 implies starting from the end of the list.

print()
print(x[-1])
print(x[-1:-3:-1])
print(x[-1:-len(x)-1:-1])

In these examples, the step size of -1 means to count backwards in steps of -1.

This video reviews many of the list concepts we have discussed so far. At 6:11, it discusses and elaborates on the rules for slicing in Python. Be sure to follow along and practice the examples in Repl.it.

List Methods

Practice these examples using Repl.it to become more familiar with some methods commonly applied to lists. As you go through these examples, you should begin to see how powerful Python can be as a programming language.

List Comprehension

Python offers many opportunities for creating efficient programming structures. When it comes to writing loops, 'list comprehension' allows for very compact code. Using lists, it is possible to pack quite a bit of power using just one line. This is an optional topic that requires understanding how to write loops using lists. Practice the examples to expand your ability to write loops.

4.2: Strings Revisited Going Deeper with Strings

Read this for more on strings.

String Methods

There are a host of methods available for processing string objects. Here are a few examples. At this point it is sensible to introduce the comment character, #. The comment character allows you to put comments into your code for the purpose of documentation. While comments are not considered executable code, they are extremely useful for making your code readable and understandable.

#explore changing to uppercase and lowercase
a='good'
c=a.upper()
d=c.lower()
print(c)
print(d)

#join a list of strings together with a space in between the strings
b='morning'
e=' '.join([a,b,'today'])
print(e)

#find a string within a string
#find method returns the first index where string was found
x='a picture is worth a thousand words'
x1=x.find('picture')
print(x1)
x2=x.find('worth')
print(x2)
x3=x.find('words')
print(x3)

#split up a string into a list of smaller strings
#use the ' ' space character as the boundary (delimiter) to split up the string
y=x.split(' ')
print(y)
print(type(y))

#try the replace method ...
z=x.replace('thousand', 'million')
print(x)
print(z)

Take some time to explore your own versions of these examples.

4.3: Data Visualization Application The matplotlib Library

In this section, you will have a chance to exercise your understanding of lists and indexing and apply your knowledge to plotting data. You will also learn how to import libraries into Python. A library in Python generally contains several methods that can be used to perform a specific set of functions. The matplotlib library contains a host of methods useful for plotting data. Try running this snippet of code in Repl.it:

import matplotlib.pyplot as plt
x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y=[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
plt.plot(x,y)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Test Plot')
plt.show()
plt.savefig('plot1.png')

The import command instructs Python to import the matplotlib library. The extra qualifier as pltis added so that the name of the plotting object can be shortened to plt. This set of commands plots the data contained in the x list against the data contained in the y list. The methods xlabel, ylabel, and title are useful for adding annotation to the plot. For completeness, the show method is given so that users understand that this command is useful for rendering the plot in many different Python IDEs. However, Repl.it is a web-based IDE, and the savefig command will be more appropriate and useful for the rendering of data plots. The leftmost Repl.it window is where you can find the plot file 'plot1.png'. Click on that file to view the plot generated by this code. To return to your Python code, click on 'main.py' in the leftmost window. We will discuss the uploading and downloading of files as we delve into the course more deeply. For now, realize that, for each new plot you would like to generate, you can use the savefig method with a different filename in single quotes (such as plot2.png, plot3.png, and so on).

Make sure to mirror and practice the examples provided in the video tutorial in Repl.it.

Unit 4 Review and Assessment Unit 4 Review

In this video, course designer Eric Sakk walks through the major topics we covered in Unit 4. As you watch, work through the exercises to try them out yourself.

5.1: The Basics of Functions Creating Functions

Read this for more on functions.

5.2: Some Useful Modules Trigonometry Review

Before delving into some Python libraries dealing with applied mathematics, visit this optional site to review trigonometry if you need a refresher.

Random Numbers

Programming also involves simulating random experiments such as flipping coins or rolling dice. If you need to review these topics, visit this optional site for a refresher.

The "math" Module

We have already seen using the import command for importing the matplotlib library and the numpy package. Much of Python's power rests in the vast collection of packages, libraries, and modules available for just about any application you could think of. The math module contains a host of mathematically oriented methods typical of what a programmer would need to perform basic calculations. Consider executing this set of instructions:

import math
a=math.exp(1)
print(a)
b=math.pi
print(b)
x=100
print(math.log(x,10))
print(math.log10(x))
y=math.pi/2
print(math.cos(y))
print(math.sin(y))
y=8
z=1/3
print(math.pow(y,z))

Notice once again the object-oriented dot notation for calling a method. Just about any function that can be calculated on a sophisticated calculator can be performed using the math module. For the sake of simplifying the code, if you know exactly what methods are needed from a given library, you can select a subset using the from keyword. Consider the code from earlier rewritten using the from keyword:

from math import exp, pi, log, log10, cos, sin, pow
a=exp(1)
print(a)
b=pi
print(b)
x=100
print(log(x,10))
print(log10(x))
y=pi/2
print(cos(y))
print(sin(y))
y=8
z=1/3
print(pow(y,z))

Now all the math method calls look exactly like function calls. Sometimes it is more convenient to use the reduced representation.

5.3: Application Cryptographic Application

While this example is not how we would perform encryption in practice, it is highly instructive for reviewing concepts covered so far regarding user-defined functions. Implement this example in Repl.it in order to solidify your working knowledge of Python.

Unit 5 Review and Assessment Unit 5 Review

In this video, course designer Eric Sakk walks through the major topics we covered in Unit 5. As you watch, work through the exercises to try them out yourself.

6.1: Immutable Collections Tuples and Sets

We have introduced the concepts of mutable and immutable objects in Python. Recall that lists are mutable while strings are immutable. This section introduces two more immutable data types useful for holding collections of objects: tuples and sets.

In short, tuples are immutable lists. Similar to strings, they cannot be changed once they have been assigned. Everything that you have learned so far about indexing and slicing also applies to tuples. The syntax for forming a tuple uses parentheses (instead of square brackets for forming a list):

a=[23.7, 45, 78]
b='asdfasdf'
c=(4,9,a,b,'zxcv')
print(c)
print(type(c))

Notice that we can put any object we please into the tuple defined as the variable c. The output after running this code looks almost exactly like a list. However, because of the immutability of c, attempting to modify an element with an instruction such as c[1]=99will result in an error. One obvious use for tuples for holding data that must be write-protected. We will see other uses when we encounter dictionaries.

Sets are another immutable data type that holds a unique collection of objects. Sets can be used to perform typical set operations such as union, intersection, set differences, and so on. Duplicates values are not possible within a set. Left and right squirrely brackets are used to assign sets.

a={3,4,5,6,7,9}
print(a)
print(type(a))
b={3,3,3,4,4,4,5,5,6,7,8}
print(b)
print(type(b))

You should observe that both b and c contain the same set of objects. The next set of commands should demonstrate Python's ability to perform set operations.

a={3,4,5}
b={4,5,6,7,8,9}
c=a.intersection(b)
print(c)
d=a.union(b)
print(d)
e=8
print(e in b)
print(e in a)
f=b.difference(a)
print(f)

This code introduces fundamental operations such as set membership (using the in keyword) and a suite of set method calls for computing the union, intersection, and so on.

6.2: Mutable Collections Dictionaries
Read this for more on dictionaries.
Dictionaries and Loops
One major application of dictionaries is to be able to efficiently sequence through a set of values. Read this section to practice writing loops using dictionaries.
Dictionaries and Tuples
Another application of tuples is to use them as keys in dictionaries. Follow and practice the examples presented in this section in order to understand how tuples can be used with dictionaries.
6.3: A Comprehensive Review of Data Structures Getting Started with Data

We have introduced several basic Python data structures: lists, strings, sets, tuples and dictionaries. Take some time to review, compare and contrast these constructs for handling various kinds of collections.

Unit 6 Review and Assessment Unit 6 Review

In this video, course designer Eric Sakk walks through the major topics we covered in Unit 6. As you watch, work through the exercises to try them out yourself.

7.1: File Input and Output More on File Input and Output

File input and output (or File I/O) is the ability to read data from and write data to files stored in a location such as a directory or a folder. The ability to handle files is actually a pretty deep subject that requires some measure of interaction with the computer operating system. Fortunately, for high-level languages such as Python, the nuts and bolts of file I/O are absorbed into a relatively simple set of methods. There are three major steps to referencing a file:

1. Open the file:
This lets the operating system know the name and location of the file being referenced and how the file is to be used (such as read or write)
2. Perform operations on the file data (such as read, write, or append):
Now that the operating system has opened the file, it is ready to be used for the purpose specified in step 1
3. Close the file:
After the desired set of operations has been completed, the operating system must be informed that access to the file is no longer necessary.

Here is an example of the three steps you can try in Repl.it:

fhandle = open('examp.txt','w')
fhandle.write('This is a write example. ')
fhandle.write('Text will be sequentially written until a newline control character occurs. \n')
fhandle.write('Then a new line will begin with \n')
fhandle.write('and another new line, etc \n')
fhandle.close()

The syntax for implementing the above step is fairly straightforward:

1. The "open" command creates and opens a file "examp.txt" where "w" means that data will be written to the file. If we were to read data, we would use an "r" instead (the "r" is actually optional where, if omitted, a file read will be assumed). In short, the first argument to the "open" command is the file name, and the second argument indicates the operation to be performed. An object (named "fhandle" in this example) is created that allows access to a host of methods that will be practiced in this unit.
In Repl.it, the file location will be in the leftmost column under the "main.py" reference. Since Repl.it is web-based, this column effectively acts like your local directory from which files can be downloaded or uploaded. You should notice that when the "open" command executes, the file "examp.txt" is created. The file is still empty, but it is now ready to be written to.
2. Since the file was opened with the parameter "w", data will be written to the file. This operation can be accomplished using the "write" method.
3. Finally, the "close" method closes the file. After writing the data to the file, you should be able to click on the filename in the left window and see the text that was written in step 2.

Try adding the following code to the above script:

f2 = open('examp.txt','r')
f2.close()

You now have the ability to create a file, as well as read data from and write data to a file. The files source.txt, source2.txt, and source3.txt are provided here. You should upload them into the leftmost window in Repl.it for your code to reference them for a file read. You can then practice the examples on this page.

Syntax and Usage
Now that you're familiar with file input and output, read this for more on syntax and usage.
7.2: Visualizing Data from a File Visualizing Data from a File

The next project will require a couple of steps to set up. First, download these files. Then, Start a new Repl.it session and either upload or 'drag and drop' these three files into the leftmost window. The "csv" stands for comma-separated values. This is a common data file type that is readable by programs such as Excel. We do not need to grab the other data files as we will challenge the Repl.it graphics capability with these three files.

Once you can see the data files listed in the Repl.it leftmost window, feel free to copy the code in the example provided into the Repl.it run window and run the code. This example is very instructive as it ties together the reading of multiple data files and the use of numpy combined with matplotlib introduced earlier in the course.

After the code runs, you should see a graph appear in the rightmost window. On the graphic, click on the resize box in the upper left-hand corner to resize the figure. Make sure you see plots similar to those given in the example.

Data Visualization from a Data File

Unit 7 Review and Assessment Unit 7 Review

In this video, course designer Eric Sakk walks through the major topics we covered in Unit 7. As you watch, work through the exercises to try them out yourself.

8.1: The "re" Module Syntax and Usage

A regular expression (or "regex") is a character sequence used to search for patterns within strings. You've already seen examples of pattern searching when we looked at strings. Regular expressions have their own syntax, which enables more general and flexible constructs to search with.

The "re" module in Python is the tool that will be used to build regular expressions in this unit. Practice these examples to familiarize yourself with some common methods. You will also practice building more general regular expression patterns using the table of special characters.

Delving Deeper

The subject of regular expressions is quite deep, and it takes an immense amount of practice to get used to the special character syntax. Furthermore, the re module contains a vast set of methods available for performing searches using regular expressions. Upon completing the examples in this section, you should have a much deeper appreciation for how powerful regular expressions can be.

8.2: Processing File Data Processing File Data

Now, we will practice regular expressions and file handling. First, download this text file. After you download this file, upload it into the leftmost window in Repl.it to ensure file reads will be able to access the data.

Processing File Data

Unit 8 Review and Assessment Unit 8 Review

In this video, course designer Eric Sakk walks through the major topics we covered in Unit 8. As you watch, work through the exercises to try them out yourself.

9.1: Catching and Handling Errors Stuff Happens

When writing software, as you may have experienced already, errors can occur. As we gain experience, we will learn to anticipate what kinds of errors can occur during program execution. For example, when performing a division calculation num/den between two variables "num" and "den", it is possible for the variable den to contain a value of zero. If this happens, a "division by zero" error should be generated to avoid a catastrophic calculation. Exceptions are a way of catching and handling potential errors so that a program will not crash and stop executing in an abrupt, untimely fashion.

The video provided in this subsection is essential for new programmers because the types of errors that can occur must be identified, discussed, and understood. The discussion on handling errors will be used as a springboard for understanding the rest of this unit.

Example: Try and Except

The "try" and "except" commands are the gateway for handling errors. "try" allows you to try to execute your code, and "except" identifies the type of error to be handled. Python contains many built-in exceptions that can be raised using the "except" command. For example,

• ValueError: raised if an operation or function receives an argument that has an inappropriate value
• NameError: raised if a variable name that does not exist is referenced

Example: ZeroDivisionError

This example shows how to handle a division by zero error by raising the built-in ZeroDivisionError exception. Make sure to practice executing this code in Repl.it.

Example: Else and Finally

Well-structured code attempts to identify everything that can go wrong as well as everything that can go right. The "else" and "finally" commands, while optional, are important components of professionally written code. The "else" command can be used as part of a "try-except" block to execute code if no errors in the set of errors being tested have occurred. The "finally" section of code will always run, but it helps to programmatically delineate such code from a software organization perspective to distinguish it from code that is being checked for errors.

Exceptions Lesson

Now that the motivation and some syntax for exceptions has been presented, we can delve a bit deeper into the structure of writing programs containing exceptions. The following lesson is designed to help put into context the rudiments just presented. In addition, one more important component of exception handling is the 'raise' statement which is useful for raising an exception if, for example, it occurs inside an exception handler.

More Examples

This set of examples reviews the try, except, and raise commands. Make sure to practice them. All too often in introductory programming courses, the practice of handling errors, if taught at all, is brought up as an afterthought or some ancillary programming feature. Nothing can be further from the truth. To become a professional programmer, testing, debugging, and creating bulletproof software lies at the heart of software design. This is why alpha and beta versions exist. You can set yourself apart by refining your expertise in exception handling.

9.2: Handling a File Error Handling a File Error

As already pointed out in the exceptions lesson, Python contains a vast set of built-in exceptions. One important class has to do with file handling. The example presented in the lesson will help to review file handling methods and put them in the context of handling exceptions.

Unit 9 Review and Assessment Unit 9 Review

In this video, course designer Eric Sakk walks through the major topics we covered in Unit 9. As you watch, work through the exercises to try them out yourself.

10.1: Overview of Object-Oriented Programming Structured Programming and Procedural Programming

We have been learning, accessing, and applying methods available in Python (it would be impossible to teach Python without doing so). Although the syntax and use of these methods are inherently object-oriented, we have been using them in the context of procedural program design and in the form of structured programs. Recall that procedural programs use functions as a way of breaking a program down into a set of procedures to solve a problem. Read this page to learn why we have been arranging our programs the way we have.

Procedural Programming versus Object-Oriented Programming

It is important to understand how object-oriented programs differ from procedural programs. The main goal of object-oriented programming is to allow the problem being solved to dictate the class design. For instance, a house is organized as a function of its rooms: living room, kitchen, bedroom, and so on. Each room is organized as a function of its furniture and its use. Each room could define a new class containing attributes that define the furniture and methods that define their use. The process of breaking a problem down into a set of classes each with its own set of attributes and methods is called data abstraction. This process is in stark contrast to procedural programming. Read this page to see how these approaches differ.

10.2: Object-Oriented Programming (OOP) Basic Terminology

Creating Classes and Methods

Read this for more on creating classes and methods.

Magic Methods

Python is packed with a vast set of magic methods. Before delving deeper into class constructions, it is a good idea to gain some more perspective on this subject.

Going Deeper

This video demonstrates class construction with a balanced mix of magic methods and user-defined methods. You may need to refer back to the Basic Terminology section to understand how the __add__ and __str__ magic methods are being used.

10.3: Derived Classes Inheritance

Read this for more on inheritance.

Going Deeper

The inheritance examples we've looked at so far have been short so that we can get the basic points across. Consider this example to practice working with a larger-scale object-oriented program.

10.4: Applying Object-Oriented Programming An Example of OOP and Inheritance
This is an excellent example of boolean operations like AND, OR, and NOT. Following and implementing this example in Repl.it will help you review the OOP concepts in this unit.
Unit 10 Review and Assessment Unit 10 Review

In this video, course designer Eric Sakk walks through the major topics we covered in Unit 10. As you watch, work through the exercises to try them out yourself.

Course Summary and Review Course Summary and Review

In this video, course designer Eric Sakk walks through the major topics we covered throughout this course. As you prepare for the final exam, watch this video to make sure you understand the major topics this course has covered.

Study Guide CS105 Study Guide
Course Feedback Survey Course Feedback Survey