Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
YStrano
GitHub Repository: YStrano/DataScience_GA
Path: blob/master/lessons/lesson_02/code/python-foundations/python-controlflow.ipynb
1904 views
Kernel: Python 3

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 and while 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 and while loops.

  • Error handling with try and except.

  • 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.

import numpy as np

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.

if 1 == 1: print('The integer 1 is equal to the integer 1.') print('Is the next indented line run, too?')
if 'one' == 'two': print("The string 'one' is equal to the string 'two'.") print('---') print('These two lines are not indented, so they are always run next.')

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.

<one or more indented lines>``` When the `if` statement is run, the expression is evaluated to `True` or `False` by applying the built-in `bool()` function to it. If the expression evaluates to `True`, the code block is run; otherwise, it is skipped. #### `if` ... `else` In many cases, you may want to run some code if the expression evaluates to `True` and some different code if it evaluates to `False`. This is done using `else`. Note how it is at the same indentation level as the `if` statement, followed by a colon, followed by a code block. Let's see it in action.
if 50 < 30: print("50 < 30.") else: print("50 >= 30.") print("The else code block was run instead of the first block.") print('---') print('These two lines are not indented, so they are always run next.')

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.

health = 55 if health > 70: print('You are in great health!') elif health > 40: print('Your health is average.') print('Exercise and eat healthily!') else: print('Your health is low.') print('Please see a doctor now.') print('---') print('These two lines are not indented, so they are always run next.')

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.

weight = float(eval(input("How many pounds does your suitcase weigh?")))
# A:

2) Write an if… else statement for multiple conditions.

Print out these recommendations based on the weather conditions:

  1. The temperature is higher than 60 degrees and it is raining: Bring an umbrella.

  2. The temperature is lower than or equal to 60 degrees and it is raining: Bring an umbrella and a jacket.

  3. The temperature is higher than 60 degrees and the sun is shining: Wear a T-shirt.

  4. The temperature is lower than or equal to 60 degrees and the sun is shining: Bring a jacket.

temperature = float(eval(input('What is the temperature? '))) weather = input('What is the weather (rain or shine)? ')
# A:

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:

# For each individual object in the list # perform task_A on said object. # Once task_A has been completed, move to next object in the list.

Let's say we wanted to print each of the names in the list, as well as "is Awesome!"

names = ['Alex', 'Brian', 'Catherine'] for name in names: print(name + ' 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.

# A: for i in range(1,16): print(i)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

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:

9 % 5 == 4

Or, in other words, the remainder of dividing 9 by 5 is 4.

# A: for i in range(1,16): if i%2 ==0: print(i)
2 4 6 8 10 12 14

5) Iterate from 1 to 30 using the following instructions:

  1. If a number is divisible by 3, print "fizz."

  2. If a number is divisible by 5, print "buzz."

  3. If a number is both divisible by 3 and by 5, print "fizzbuzz."

  4. Otherwise, print just the number.

# A: for i in range(1,31): three = i%3==0 five = i%5==0 three_and_five = three and five if three_and_five: print('fizzbuzz') continue ## what does this do? if three: print('fizz') if five: print('buzz')
fizz buzz fizz fizz buzz fizz fizzbuzz fizz buzz fizz fizz buzz fizz fizzbuzz

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.

animals = ['duck', 'rat', 'boar', 'slug', 'mammoth', 'gazelle']
# A:

7) Iterate through the animals list. Capitalize the first letter and append the modified animals to a new list.

# A:

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.

# A:
---
<a id='functions'></a> # `try` / `except`
---

Sometimes, code throws a runtime error. For example, division by zero or using a keyword as a variable name.

1 / 0
print('a' - 'b')

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.

try: 1 / 0 print('not executed due to the exception') except: print('Divide by zero!') print('Program keeps executing!')

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.

try: print('a' - 'b') except: pass print('Program keeps executing!')

We can also catch specific exceptions and use try/except in more ways, but we'll keep it brief for this introduction!

---
<a id='functions'></a> # Functions
---

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:

# Define the function name and the requirements it needs. # Perform actions. # Optional: Return output.

Let's create a function that takes two numbers as arguments and returns their sum, difference, and product.

def arithmetic(num1, num2): print(num1 + num2) print(num1 - num2) print(num1 * num2) arithmetic(3,5)

Once we define the function, it will exist until we reset our kernel, close our notebook, or overwrite it.

arithmetic(4,10)

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.

# A:

10) Write a function to calculate the area of a triangle using a height and width.

Test it out.

# A:
---
<a id='while_loops'></a> # `while` Loops
---

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:

# A threshold or criteria point is set. # As long as the threshold or criteria point isn't met, # perform a task. # Check threshold/criteria point. # If threshold/criteria point is met or exceeded, # break loop. # If not, repeat.

An example of an infinite while loop:

x = 0 while x < 10: print x

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.

x = 0 while x < 10: print x x = x+1

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.

sentence = "A MAN KNOCKED ON MY DOOR AND ASKED FOR A SMALL DONATION TOWARDS THE LOCAL SWIMMING POOL SO I GAVE HIM A GLASS OF WATER"
# A:

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.

corrupted = ['!1', '23.1', '23.4.5', '??12', '.12', '12-12', '-11.1', '0-1', '*12.1', '1000']
# A:

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.

with open('../assets/datasets/coffee-preferences.csv','r') as f: lines = f.readlines()

Iterate through lines and print them out.

# A:
# A:

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.

# A:

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.

# A:

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.

# A:

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.

# A:

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.

# A:

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?

# A:

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:

average_rating = float(sum(ratings_list))/len(ratings_list)

Print your dictionary to see the average brand ratings.

# A:

9) Create a list containing only the people's names.

# A:

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.

import random # Choose a random person from the list of people: # random.choice(people)

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:

  1. Takes a list (your list of names) as an argument.

  2. Selects a name using random.choice(people) three separate times.

  3. Returns True if the name was the same all three times; otherwise returns False.

# A:

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.

# A:

Lesson Summary

Let's review what we learned today. We:

  • Reviewed Python control flow and conditional programming.

  • Implemented for and while 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?

....

Additional Resources