Module 3 - Python Programming Fundamentals
Module 3 - Python Programming Fundamentals
LOOPS
In this video we will cover Loops, in particular “for loops” and “while loops.”
We will use many visual examples in this video. See the labs for examples with
data.
Before we talk about loops, let’s go over the range function.
The range function outputs an ordered sequence as a list “i”.
If the input is a positive integer, the output is a sequence; the sequence contains
the same
number of elements as the input, but starts at zero.
For example, if the input is 3 the output is the sequence 0,1,2.
If the range function has two inputs where the first input is larger than the
second
input, the output is a sequence that starts at the first input.
Then the sequence iterates up to, but not including the second number.
For the input 10 and 15, we get the following sequence. See the labs for more
capabilities
of the range function. Please note: if you use Python 3 the range
function will not generate a list explicitly like in Python 2.
In this section, we will cover “for loops”. We will focus on lists, but many of the
procedures
can be used on tuples. Loops perform a task over and over.
Consider the group of colored squares. Let's say we would like to replace each
colored
square with a white square. Let's give each square a number to make things
a little easier and refer to all the group of squares as squares.
If we wanted to tell someone to replace square 0 with a white square, we would say,
“=Replace
square 0 with a white square” or we can say, “For square 0 in squares, square 0=
white square.” Similarly, for the next square, we can say,
“For square 1 in squares, square 1 = white square.”
For the next square, we can say, “For square 2 in squares, square 2= white square.”
We repeat the process for each square. The only thing that changes is the index of
the square we are referring to. If we are going to perform a similar task
in Python, we cannot use actual squares. So let's use a list to represent the
boxes.
Each element in the list is a string representing the color.
We want to change the name of the color in each element to white.
Each element in the list has the following index.
This is the syntax to perform a loop in Python. Notice the indent.
The range function generates a list. The code will simply repeat everything in
the indent 5 times. If you were to change the value to 6, it would
do it 6 times, however, the value of “i” is incremented by one each time.
In this segment we change the i-th element of the list to the string white.
The value of “i” is set to zero. Each iteration of the loop starts at the beginning
of the indent. We then run everything in the indent.
The first element in the list is set to white. We then go to the start of the
indent.
We progress down each line. When we reach the line to change the value
of the list, we set the value of index 1 to white.
The value of “i” increases by one. We repeat the process for index 2.
The process continues for the next index until we have reached the final element.
We can also iterate through a list or tuple directly in Python, we do not even need
to
use indexes. Here is the list squares. Each iteration of
the list we pass one element of the list squares to the variable square.
Let's display the value of the variable square on this section.
For the first iteration, the value of square is red.
We then start the second iteration. For the second iteration, the value of square
is yellow.
We then start the third iteration. For the final iteration, the value of square is
green.
A useful function for iterating data is enumerate. It can be used to obtain the
index and the
element in the list. Let's use the box analogy, with the numbers
representing the index of each square. This is the syntax to iterate through a list
to provide the index of each element. We use the list squares and use the names
of the colors to represent the colored squares. The argument of the function
enumerate is
the list, in this case, squares. The variable "i" is the index, and the variable
square is the corresponding element in the list.
Let's use the left part of the screen to display the different values of the
variable square,
and "i" for the various iterations of the loop. For the first iteration, the value
of the
variable is red, corresponding to the zeroth index, and the value for “i” is zero.
For the second iteration, the value of the variable square is yellow and the value
of
"i" corresponds to its index, i.e., 1. We repeat the process for the last index.
“While loops” are similar to “for loops”, but instead of executing a statement a
set
number of times, a while loop will only run if a condition is met.
Let’s say we would like to copy all the orange squares from the list squares to the
list new squares, but we would like to stop if we encounter a non-orange square.
We don't know the value of the squares beforehand. We would simply continue the
process while
the square is orange, or see if the square equals orange; if not, we would stop.
For the first example, we would check if the square was orange.
It satisfies the condition, so we would copy the square.
We repeat the process for the second square. The condition is met, so we copy the
square.
In the next iteration, we encounter a purple square.
The condition is not met so we stop the process. This is essentially what a “while
loop”
does. Let's use the figure on the left to represent
the code. We will use a list with the names of the color
to represent the different squares. We create an empty list of “New Squares.”
In reality, the list is of indeterminate size. We start the index at zero.
The “while” statement will repeatedly execute the statements within the indent
until
the condition inside the bracket is false. We append the value of the first element
of
the list squares to the list "New Squares." We increase the value of “i” by one.
We append the value of the second element of the list squares to the list "New
Squares.“
We increment the value of “i”. Now the value in the array “Squares” is
purple. Therefore, the condition for the “while”
statement is false and we exit the loop. Check out the labs for more examples of
loop,
many with real data.
FUNCTIONS
In this video we will cover functions. You will learn how to use some of Python’s
built-in
functions as well as how to build your own functions.
Functions take some input then produce some output or change.
The function is just a piece of code you can reuse.
You can implement your own function, but in many cases, you use other people’s
functions.
In this case, you just have to know how the function works and in some cases how to
import
the functions. Let the orange and yellow squares represent
similar blocks of code. We can run the code using some input and get
an output. If we define a function to do the task we
just have to call the function. Let the small squares represent the lines
of code used to call the function. We can replace these long lines of code by
just calling the function a few times. Now we can just call the function; our code
is much shorter. The code performs the same task.
You can think of the process like this: when we call the function f1, we pass an
input
to the function. These values are passed to all those lines of code you wrote.
This returns a value; you can use the value. For example, you can input this value
to a
new function f2. When we call this new function f2, the value
is passed to another set of lines of code. The function returns a value.
The process is repeated passing the values to the function you call.
You can save these functions and reuse them, or use other people’s functions.
Python has many built-in functions; you don't have to know how those functions work
internally,
but simply what task those functions perform. The function len takes in an input of
type
sequence, such as a string or list, or type collection, such as a dictionary or
set, and
returns the length of that sequence or collection. Consider the following list.
The len function takes this list as an argument, and we assign the result to the
variable L.
The function determines there are 8 items in the list, then returns the length of
the
list, in this case, 8. The function sum takes in an iterable like
a tuple or list and returns the total of all the elements.
Consider the following list. We pass the list into the sum function and
assign the result to the variable S. The function determines the total of all the
elements, then returns it, in this case, the value is 70.
There are two ways to sort a list. The first is using the function sorted.
We can also use the list method sort. Methods are similar to functions.
Let's use this as an example to illustrate the difference.
The function sorted Returns a new sorted list or tuple.
Consider the list album ratings. We can apply the function sorted to the list
album ratings and get a new list sorted album rating.
The result is a new sorted list. If we look at the list album ratings, nothing
has changed. Generally, functions take an input, in this
case, a list. They produce a new output, in this instance, a sorted list.
If we use the method sort, the list album ratings will change and no new list will
be
created. Let's use this diagram to help illustrate
the process. In this case, the rectangle represents the
list album ratings. When we apply the method sort to the list,
the list album rating changes. Unlike the previous case, we see that the
list album rating has changed. In this case, no new list is created.
Now that we have gone over how to use functions in Python, let’s see how to build
our own
functions. We will now get you started on building your
own functions in python. This is an example of a function in python
that returns its input value + 1. To define a function, we start with the keyword
def. The name of the function should be descriptive
of what it does. We have the function formal parameter "A"
in parentheses. Followed by a colon.
We have a code block with an indent, for this case, we add 1 to "A" and assign it
to B.
We return or output the value for b. After we define the function, we can call
it. The function will add 1 to 5 and return a
6. We can call the function again; this time
assign it to the variable "c" The value for 'c' is 11.
Let's explore this further. Let's go over an example when you call a function.
It should be noted that this is a simplified model of Python, and Python does not
work
like this under the hood. We call the function giving it an input, 5.
It helps to think of the value of 5 as being passed to the function.
Now the sequences of commands are run, the value of "A" is 5.
"B" would be assigned a value of 6. We then return the value of b, in this case,
as b was assigned a value of 6, the function returns a 6.
If we call the function again, the process starts from scratch; we pass in an 8.
The subsequent operations are performed. Everything that happened in the last call
will happen again with a different value of "A"
The function returns a value, in this case, 9.
Again, this is just a helpful analogy. Let’s try and make this function more
complex.
It's customary to document the function on the first few lines; this tells anyone
who
uses the function what it does. This documentation is surrounded in triple
quotes. You can use the help command on the function
to display the documentation as follows. This will printout the function name and
the
documentation. We will not include the documentation in the
rest of the examples. A function can have multiple parameters.
The function mult multiplies two numbers; in other words, it finds their product.
If we pass the integers 2 and 3, the result is a new integer.
If we pass the integer 10 and the float 3.14, the result is a float 31.4.
If we pass in the integer two and the string “Michael Jackson,” the string Michael
Jackson is repeated two times. This is because the multiplication symbol
can also mean repeat a sequence. If you accidentally multiply an integer and
a String instead of two integers, you won’t get an error.
Instead, you will get a String, and your program will progress, potentially failing
later because
you have a String where you expected an integer. This property will make coding
simpler, but
you must test your code more thoroughly. In many cases a function does not have a
return
statement. In these cases, Python will return the special
“None” object. Practically speaking, if your function has
no return statement, you can treat it as if the function returns nothing at all.
The function MJ simply prints the name 'Michael Jackson’.
We call the function. The function prints “Michael Jackson.”
Let's define the function “No work” that performs no task.
Python doesn’t allow a function to have an empty body, so we can use the keyword
pass,
which doesn’t do anything, but satisfies the requirement of a non-empty body.
If we call the function and print it out, the function returns a None.
In the background, if the return statement is not called, Python will automatically
return
a None. It is helpful to view the function No Work
with the following return statement. Usually, functions perform more than one task.
This function prints a statement then returns a value.
Let's use this table to represent the different values as the function is called.
We call the function with an input of 2. We find the value of b.
The function prints the statement with the values of a and b.
Finally, the function returns the value of b, in this case, 3.
We can use loops in functions. This function prints out the values and indexes
of a loop or tuple. We call the function with the list album ratings
as an input. Let's display the list on the right with its
corresponding index. Stuff is used as an input to the function
enumerate. This operation will pass the index to i and
the value in the list to “s”. The function would begin to iterate through
the loop. The function will print the first index and
the first value in the list. We continue iterating through the loop.
The values of i and s are updated. The print statement is reached.
Similarly, the next values of the list and index are printed.
The process is repeated. The values of i and s are updated.
We continue iterating until the final values in the list are printed out.
Variadic parameters allow us to input a variable number of elements.
Consider the following function; the function has an asterisk on the parameter
names.
When we call the function, three parameters are packed into the tuple names.
We then iterate through the loop; the values are printed out accordingly.
If we call the same function with only two parameters as inputs, the variable names
only
contain two elements. The result is only two values are printed
out. The scope of a variable is the part of the
program where that variable is accessible. Variables that are defined outside of
any
function are said to be within the global scope, meaning they can be accessed
anywhere
after they are defined. Here we have a function that adds the string
DC to the parameter x. When we reach the part where the value of
x is set to AC, this is within the global scope, meaning x is accessible anywhere
after
it is defined. A variable defined in the global scope is
called a global variable. When we call the function, we enter a new
scope or the scope of AddDC. We pass as an argument to the AddDC function,
in this case, AC. Within the scope of the function, the value
of x is set to ACDC. The function returns the value and is assigned
to z. Within the global scope, the value z is set
to ACDC After the value is returned, the scope of
the function is deleted. Local variables only exist within the scope
of a function. Consider the function thriller; the local
variable Date is set to 1982. When we call the function, we create a new
scope. Within that scope of the function, the value
of the date is set to 1982. The value of date does not exist within the
global scope. Variables inside the global scope can have
the same name as variables in the local scope with no conflict.
Consider the function thriller; the local variable Date is set to 1982.
The global variable date is set to 2017. When we call the function, we create a new
scope. Within that scope, the value of the date is
set to 1982. If we call the function, it returns the value
of Date in the local scope, in this case, 1982.
(click6) When we print in the global scope, we use the global variable value.
The global value of the variable is 2017. Therefore, the value is set to 2017.
If a variable is not defined within a function, Python will check the global scope.
Consider the function "AC-DC“. The function has the variable rating, with no value
assigned.
If we define the variable rating in the global scope, then call the function,
Python will
see there is no value for the variable Rating. As a result, python will leave the
scope and
check if the variable Ratings exists in the global scope. It will use this value of
Ratings
in the global scope within the scope of "AC-DC“. In the function, will print out a
9.
The value of z in the global scope will be 10, as we added one.
The value of rating will be unchanged within the global scope.
Consider the function Pink Floyd. If we define the variable Claimed Sales with
the keyword global, the variable will be a global variable.
We call the function Pink Floyd. The variable claimed sales is set to the string
“45 million” in the global scope. When we print the variable, we get a value
of “45 million.” There is a lot more you can do with functions.
Check out the lab for more examples.