Path: blob/master/lessons/lesson_02/code/python-foundations/python-controlflow.ipynb
1904 views
Introduction to Python: Part Two
Authors: Kiefer Katovich (San Francisco), Dave Yerrington (San Francisco), Joseph Nelson (Washington, D.C.), Sam Stack (Washington, D.C.)
Learning Objectives
Part Two: Python Iterations, Control Flow, and Functions
After this lesson, you will be able to:
Understand
Python
control flow and conditional programming.Implement
for
andwhile
loops to iterate through data structures.Apply
if… else
conditional statements.Create functions to perform repetitive actions.
Demonstrate error handling using
try, except
statements.Combine control flow and conditional statements to solve the classic "FizzBuzz" code challenge.
Use
Python
control flow and functions to help us parse, clean, edit, and analyze the Coffee Preferences data set.
Part 2: Python Iterations, Control Flow, and Functions
We've gone over how data can exist within the Python language. Now, let's look at the core ways of interacting with it.
if… elif… else
statements.for
andwhile
loops.Error handling with
try
andexcept
.Functions.
First, let's bring in one of the many available Python libraries to help us with some of the statements we'll be creating.
NumPy is one of the core data science libraries you will use. It already contains many functions for many useful mathematical operations, so we don't have to build them ourselves.
All you need to do to import a library is execute import <library name>
. In our situation, we import NumPy and assign it to the value np
, which allows us to use np
as a shorthand.
Why would we do this? For convenience. In this case, np
is a commonly used shorthand that will not cause confusion.
if… else
Statements
In Python, indentation matters! This is especially true when we look at the control structures in this lesson. In each case, a block of indented code is only sometimes run. There will always be a condition in the line preceding the indented block that determines whether the indented code is run or skipped.
if
Statement
The simplest example of a control structure is the if
statement.
Notice that, in Python, the line before every indented block must end with a colon (:
). In fact, it turns out that the if
statement has a very specific syntax.
if
... elif
... else
Sometimes, you might want to run one specific code block out of several. For example, perhaps we provide the user with three choices and want something different to happen with each one.
elif
stands for else if
. It belongs on a line between the initial if
statement and an (optional) else
.
This code works by evaluating each condition in order. If a condition evaluates to True
, the rest are skipped.
Let's walk through the code. First, we let health = 55
. We move to the next line at the same indentation level — the if
. We evaluate health > 70
to be False
, so its code block is skipped. Next, the interpreter moves to the next line at the same outer indentation level, which happens to be the elif
. It evaluates its expression, health > 40
, to be True
, so its code block is run. Now, because a code block was run, the rest of the if
statement is skipped.
1) Write an if… else
statement to check whether or not the suitcase weighs more than 50 pounds.
Print a message indicating whether or not the suitcase weighs more than 50 pounds.
2) Write an if… else
statement for multiple conditions.
Print out these recommendations based on the weather conditions:
The temperature is higher than 60 degrees and it is raining: Bring an umbrella.
The temperature is lower than or equal to 60 degrees and it is raining: Bring an umbrella and a jacket.
The temperature is higher than 60 degrees and the sun is shining: Wear a T-shirt.
The temperature is lower than or equal to 60 degrees and the sun is shining: Bring a jacket.
for
Loops
One of the primary purposes of using a programming language is to automate repetitive tasks. One such means in Python is the for
loop.
The for
loop allows you to perform a task repeatedly on every element within an object, such as every name in a list.
Let's see how the pseudocode works:
Let's say we wanted to print each of the names in the list, as well as "is Awesome!"
This process of cycling through a list item by item is known as "iteration."
3) Write a for
loop that iterates from number 1 to number 15.
On each iteration, print out the number.
4) Iterate from 1 to 15, printing whether the number is odd or even.
Hint: The modulus operator, %
, can be used to take the remainder. For example:
Or, in other words, the remainder of dividing 9 by 5 is 4.
Remember this example. FizzBuzz is a common coding challenge. It is relatively easy to solve, but those who ask are always looking for more creative ways to solve or optimize it.
6) Iterate through the following list of animals and print each one in all caps.
7) Iterate through the animals list. Capitalize the first letter and append the modified animals to a new list.
8) Iterate through the animals. Print out the animal name and the number of vowels in the name.
Hint: You may need to create a variable of vowels for comparison.
---
---
Sometimes, code throws a runtime error. For example, division by zero or using a keyword as a variable name.
These errors are called exceptions. Exceptions are serious errors that are thrown when the computer cannot continue because the expression cannot be evaluated properly. For example:
Using the addition operator to add a string and a non-string.
Using an undefined name.
Opening a file that does not exist.
Luckily, our program does not have to be this fragile. By wrapping a code block with try
, we can "catch" exceptions. If an exception occurs, instead of exiting, the computer immediately executes the matching except
block and continues the program.
Sometimes, you might want to do nothing in the event of an exception. However, an indented code block is still required! So, you can use the keyword pass
.
We can also catch specific exceptions and use try/except in more ways, but we'll keep it brief for this introduction!
---
---
Similar to the way we can use for
loops as a means of performing repetitive tasks on a series of objects, we can also create functions to perform repetitive tasks. Within a function, we can write a large block of action and then call the function whenever we want to use it.
Let's make some pseudocode:
Let's create a function that takes two numbers as arguments and returns their sum, difference, and product.
Once we define the function, it will exist until we reset our kernel, close our notebook, or overwrite it.
9) Write a function that takes a word as an argument and returns the number of vowels in the word.
Try it out on three words.
10) Write a function to calculate the area of a triangle using a height and width.
Test it out.
---
---
while
loops are a different means of performing repetitive tasks/iteration. The function of a for
loop is to perform tasks over a finite list. The function of a while
loop is to perform a repetitive task until a specific threshold or criteria point is met. Keep in mind that this can be relatively dangerous, as it is easy to create a loop that never meets your criteria and runs forever.
We say "list," but we're not just talking about a Python list data type. We're including any data type where information can be iterated through.
Let's look at some pseudocode:
An example of an infinite while
loop:
Because the value assigned to x
never changes and always remains less than 10, this loop will print "x
" infinitely until you force-kill the kernel.
We can fix this infinity loop by including a incrementation for x
within it.
11) Use while
loops and strings.
Iterate over the following sentence repeatedly, counting the number of vowels in the sentence until you have tallied one million. Print out the number of iterations it took to reach that amount.
12) Try to convert elements in a list to floats.
Create a new list with the converted numbers. If something cannot be converted, skip it and append nothing to the new list.
Hint: Use error-handling methods.
Practice Control Flow on the Coffee Preference Data Set
1) Load Coffee Preference data from file and print.
The code to load in the data is provided below.
The with open(..., 'r') as f:
opens up a file in "read" mode (rather than "write") and assigns this opened file to f
.
We can then use the built-in .readlines()
function to split the CSV file on newlines and assign it to the variable lines
.
Iterate through lines
and print them out.
Print out just the lines
object by typing "lines" in a cell and hitting enter
.
2) Remove the remaining newline '\n'
characters with a for
loop.
Iterate through the lines of the data and remove the unwanted newline characters.
.replace('\n', '') is a built-in string function that will take the substring you want to replace as its first argument and the string you want to replace it with as its second.
3) Split the lines into "header" and "data" variables.
The header is the first string in the list of strings. It contains our data's column names.
4) Split the header and data strings on commas.
To split a string on the comma character, use the built-in .split(',')
function.
Split the header on commas, then print it. You can see that the original string is now a list containing items that were originally separated by commas.
5) Remove the "Timestamp" column.
We aren't interested in the "Timestamp" column in our data, so remove it from the header and data list.
Removing "Timestamp" from the header can be done with list functions or with slicing. To remove the header column from the data, use a for
loop.
Print out the new data object with the timestamps removed.
6) Convert numeric columns to floats and empty fields to None
.
Iterate through the data and construct a new data list of lists that contains the numeric ratings converted from strings to floats and the empty fields (which are empty strings, '') replaced with the None
object.
Use a nested for
loop (a for
loop within another for
loop) to get the job done. You will likely need to use if… else
conditional statements as well.
Print out the new data object to make sure you've succeeded.
7) Count the None
values per person and put the counts in a dictionary.
Use a for
loop to count the number of None
values per person. Create a dictionary with the names of the people as keys and the counts of None
as values.
Who rated the most coffee brands? Who rated the least?
8) Calculate average rating per coffee brand.
Excluding None
values, calculate the average rating per brand of coffee.
The final output should be a dictionary with the coffee brand names as keys and their average rating as the values.
Remember that the average can be calculated as the sum of the ratings over the number of ratings:
Print your dictionary to see the average brand ratings.
9) Create a list containing only the people's names.
11) Picking a name at random. What are the odds of choosing the same name three times in a row?
Now, we'll use a while
loop to "brute force" the odds of choosing the same name three times in a row randomly from the list of names.
"Brute force" is a term used quite frequently in programming to refer to a computationally inefficient way of solving a problem. It's brute force in this situation because we can use statistics to solve this much more efficiently than if we actually played out an entire scenario.
Below, we've imported the random
package, which has the essential function for this code: random.choice()
. The function takes a list as an argument and returns one of the elements of that list at random.
Write a function to choose a person from the list randomly three times and check if they are all the same.
Define a function that has the following properties:
Takes a list (your list of names) as an argument.
Selects a name using
random.choice(people)
three separate times.Returns
True
if the name was the same all three times; otherwise returnsFalse
.
12) Construct a while
loop to run the choosing function until it returns True
.
Run the function until you draw the same person three times using a while
loop. Keep track of how many tries it took and print out the number of tries after it runs.
Lesson Summary
Let's review what we learned today. We:
Reviewed
Python
control flow and conditional programming.Implemented
for
andwhile
loops to iterate through data structures.Applied
if… else
conditional statements.Created functions to perform repetitive actions.
Demonstrated error handling using
try, except
statements.Combined control flow and conditional statements to solve the classic "FizzBuzz" code challenge.
Used
Python
control flow and functions to help us parse, clean, edit, and analyze the Coffee Preferences data set.
Additional Questions?
....