Day 4: Pre-class Assignment: Boolean logic, if statements, and an introduction to functions#

✅ Put your name here

#

Goals for Today’s Pre-Class Assignment#

By the end of this assignment, you should be able to:

  • Use if/else statements with true/false (boolean) conditional statements in Python.

  • Write simple functions in Python

Assignment instructions#

Watch any videos below, read all included and linked to content, and complete any assigned programming problems. Please get started early, and come to office hours if you have any questions and make use of Slack!

This assignment is due by 7:59 p.m. the day before class, and should be uploaded into the “Pre-class assignments” submission folder for Day 4. Submission instructions can be found at the end of the notebook.


Part 1. Making decisions in Python#

Sometimes when we’re writing a program, we run into a situation where the right next step is contigent on whether or not a particular condition is true or not. If it is true, we might want to do one thing, but if it is not true, we might want to do something else entirely. This is sometimes referred to as “branching”. Basically, conditional statements, where something is evaluated to be True or False, allow Python to make decisions about how to move forward. When it comes to making decisions in Python, there are two ideas that you need to understand:

  1. The main command in Python is the if statement; or, more generally, the if-then-else construct

  2. Boolean logic (the conditional True/False statement) allows you to perform tests that return True or False, which you then use to move foward.

Taken together, these two features of a programming language are essential for getting our codes to carry out complex tasks. These statments generally play a key role in data science as we often need the computer to sift through large data sets depending on what we wish to analyze.

You should also pause for a moment to reflect on that fact that you’re already been exposed to Boolean logic statement when you’ve written while loops. Basically, the while loops tells Python to keep doing the same thing until the conditional statement becomes False.

Now, to learn more about boolean logic and if statements, watch the video below.

(If the YouTube video doesn’t work, you can access a back-up version on MediaSpace)

# Don't forget to watch the video in full-screen mode!
from IPython.display import YouTubeVideo  
YouTubeVideo("cozbOliNwSs",width=640,height=360)  # Boolean logic and if statements

Part 2. Practice with if statements#

Now that you’ve learned a bit about if statements in Python, let’s get some practice with those conditional statements!

Remember, if statements can be used for situations when we only want certain code to execute when a particular thing happens to be true.

For example, the following code loops over a range of values but only actually prints the value if the value is greater than 5. Try running the code!

# loop over the values
for i in range(11):
    # If the value is great than 5, print it
    if i > 5:
        print(i)

Note that if statements can be used with any conditional statement that returns a True or False. For example, we can also do something like checking to see if a number is evenly divisible by 2. For this, we can use the “modulus” operator, which is a represented by a % sign in Python. When you use the % sign, Python divides the first number by the second number and returns the remainder. Try running the following code. Make sure you understand what the code is doing!

# loop over the values
for i in range(11):
    # If the value is divisible by 2, print it
    if i%2 == 0:
        print(i)

Using and and or:#

We can also perform if statements using multiple conditions. Let’s say we want all the numbers in the range from 0 to 10 that are greater than 5 and divisible by 2. How might we do that? Review and run the code below. Make sure you understand what’s happening.

for i in range(11):
    # If the value is greater than 5 and divisible by two, print it
    # Notice that the word "and" is bold and in green, this means it serves a special purpose in Python
    if i > 5 and i%2 == 0:
        print(i)

Now, what if we replace that and statement with an or statement? Try running the code!

for i in range(11):
    # If the value is greater than five or divisible by 2, print it
    # Notice that the word "or" is also bold and in green
    if i > 5 or i%2==0:
        print(i)

Question: How is the or statement different than the and statement?

Put your answer here

Task: Define x to be a list of the numbers 1 through 10. Create loop that goes through all the numbers in x and, if that number is even, use a print statment to print “This number is even:” followed by the number. Put your solution in the code cell below.

# Put your code here

Part 3. More complex if statements#

Sometimes just using several simple if statements in our code isn’t enough to make sure the program does what it is supposed to do. Other times even more complicated if statements that use and or or to combine multiple conditional statements aren’t sufficent either, so what do we do then?

You may often discover that you need to solve a problem that requires the code to do one thing if a particular condition is true and something else if that condition is not true. This is where the else command comes into play. Basically, the program knows to execute a certain piece of code when the if statement is true and a different piece of code for all other cases.

We can actually build even more complicated code by using the elif or “else-if” statement, which is basically a second if statement that is only executed if the first if statement was not satisfied. We can even tag an else on the end of all of that as well. Below is a diagram that helps illustrate the flow of an if-elif-else statement.

If_Flow

Now, watch the following video to get a sense for how all of these statements work together. The video starts out with some simple examples and then builds a progressively more complex bit of code that uses a combination of an if statement, a few elif statements, and a final else statement.

(If the YouTube video doesn’t work, you can access a back-up version on MediaSpace)

# Don't forget to watch the video in full-screen mode!
from IPython.display import YouTubeVideo  
YouTubeVideo("8_wSb927nH0",width=640,height=360)  # Complex if statements

Question: Let’s say that you were recently promoted to manager at work. While you’re excited about all of the extra money that comes with the new position, you’ve started to realize that there’s a bunch of extra responsbility associated with the job as well. One of those responsibilities is to create the work schedule based on all of the preferences of your new minions. You’re thinking that you might be able to use a bit of Python to figure out which hours each person should work. Your employees have made the following requests:

  • Luke would like to work in the morning

  • Ningyu would like to work in the evening

  • Nate didn’t submit his request

  • Justin would like to work in the evening

  • Katrina would like to work in the evening

  • Jacob would like to work in the morning

Create a for loop that loops through the list of employee names (provided below) prints their name and prints out the following statements based on their preferences:

  • If the employee requested mornings, print “You have to work from 9am-12pm.”

  • If the employee requested evenings, print “You have to work from 6-9pm.”

  • If the employee failed to submit a request, print “You have to work from 12-6pm.”

You can use any combination of if, elif, and else statements to get the job done.

employees = ['Luke', 'Ningyu', 'Nate', 'Justin', 'Katrina', 'Jacob']

# Put your code below this comment

Part 4. Introduction to functions#

The last bit of this assignment is designed to get you start thinking about an extremely useful tool in Python, the Python function construct!

Functions in Python are really handy when you have a bit of code that serves a specific purpose and you want to be able to use that bit of code over and over again without having to copy and paste it repeatedly. It also means that if you need to change how that code works, you can change the code inside the function and you don’t have to change that code in several different places. Functions can also make your code much easier to read because you can compartmentalize your code into separate functions and then just call those function in the main body of your code.

4.1 What are functions and why would we use them?#

Watch the following video for an overview of what functions are and why they can be extremely useful!

Note: The following three videos were originally made for CMSE 201, but the content applies to this course as well! Also, if you feel confident with the material covered in the videos, you may wish to watch them “sped up”. You can do this by clicking on the gear icon (Settings) and changing the playback speed.

# Don't forget to watch the video in full-screen mode!
from IPython.display import YouTubeVideo
YouTubeVideo("kY3yMXUu5qY",width=640,height=360) # Intro to Functions!

Question: In your own words, explain what a function is and why it is a very useful tool in programming?

Put your answer here!

Question: What are the three main things that functions provide?

Put your answer here!

4.2 How do we write functions in Python?#

Watch the following video, to learn how functions are written in Python.

# Don't forget to watch the video in full-screen mode!
from IPython.display import YouTubeVideo
YouTubeVideo("HWzDv1UHLZo",width=640,height=360) # How do we write functions?

Question: What are the four main pieces that make up a function in Python?

Put your answer here!

Question: What is the critical term needed to initially define a function?

Put your answer here!

Question: How do you ensure that the results are your function are output in a way that will allow you to store the results in a new variable?

Put your answer here!

4.3 Practice with writing functions#

Watch the following video to review how you can write functions in Python. Pay attention to the different ways that you can output information from functions and input variables into functions.

# Don't forget to watch the video in full-screen mode!
from IPython.display import YouTubeVideo
YouTubeVideo("EXO3WYqlA6A",width=640,height=360) # Practice writing functions

Question: Create a Python function that takes three numbers as inputs and prints the average of those three numbers. Call your function “compute_average”. Test your function to make sure it works!

# Put your code here

Question: Write a function that takes an \(a\), \(b\), and \(c\) value and returns the value of \(2a^2 - 4b + c\). Test your function to make sure it works!

# Put your code here

For more information on defining functions in python, check out this link:

Important: One of the things you should remember is that when you want a function to return a values (rather than just print it), the return command needs to go at the end of the function. The moment a function comes across a return statement, it will exit the function and ignore any code that comes later in the function. The exception to this is when a function has mutiple return statements that are called only when certain conditions are true.


Assignment wrap-up#

Please fill out the form that appears when you run the code below. You must completely fill this out in order to receive credit for the assignment!

from IPython.display import HTML
HTML(
"""
<iframe 
	src="https://cmse.msu.edu/cmse801-pc-survey" 
	width="800" 
	height="800px" 
	frameborder="0" 
	marginheight="0" 
	marginwidth="0">
	Loading...
</iframe>
"""
)

Congratulations, you’re done!#

Submit this assignment by uploading it to the course Desire2Learn web page. Go to the “Pre-class assignments” folder, find the appropriate dropbox link, and upload it there.

See you in class!

© Copyright 2018, Michigan State University Board of Trustees