Coding Lab 2: Functions, Conditionals & Collections#

Welcome to the second coding lab!

CodingLab labs are meant to be interactive - so find another person to work together with on this notebook if you’re able.

CodingLabs are also meant to be exploratory. There are broad questions in the notebook that you should explore, and try to answer - but you are also very much encouraged to explore other related ideas as you go!

If you have a question about how something works / what something does - try it out, and see what happens!

Part 0: Asserts#

You will notice, through the coding labs and assignments, code that looks something like assert True, in which the assert statement is used. The goal, in your coding labs and assignments is for assert statements to “pass silently”…meaning give no output.

Using assert essentially means to assert that the following code is True.

Or, slightly more formally, assert that the following code evaluates as True.

If the asserted code does not evaluate as True, it raises an error - meaning it interrupts the code execution because something went wrong.

This can be used as a way to test that code does what you expect it to do, and is therefore part of how we will test your code programmatically.

Because the use of assert will be common in course materials, let’s take a moment to explore how it works and what happens when we use it.

In the cell below: declare a variable called boolean that has type boolean, and passes the assert in the next cell:

### BEGIN SOLUTION
boolean = True
### END SOLUTION
# Check that there is variable called `boolean` that is a boolean
assert type(boolean) == bool
# Check that the variable called `boolean` passes the assert
assert boolean

Assert Explorations#

Now, explore using assert.

What happens if you assert a True comparison, like 6 < 10? a False comparison, like 6 > 10?

What happens if you assert an integer? or a string?

What happens if you assert None?

Find at least one integer that raises an assertion error.

### BEGIN SOLUTION
# specific asserts will vary 
# Asserting True comparison will pass silently
assert 6 < 10

# Asserting False compariosn will raise assertion error
assert 6 > 10 

# Asserting an integer asserts as True
assert 12

# Asserting a string asserts as True
assert 'hello'

# Asserting None asserts as False
assert None

# The integer 0 asserts as False (it gets interpreted as False)
assert 0

### END SOLUTION

Part 1: Functions#

Functions are a way to organize code into a procedure that we can repeat and use whenever we want.

Function Questions#

Write a function#

Write a function mult_two that takes one input, multiplies it by two and returns the result

### BEGIN SOLUTION
def mult_two(input_number):

    answer = input_number * 2
    return answer
### END SOLUTION
# Check that you can use the function
mult_two(2)
# Check this function returns the correct outputs
assert mult_two(2) == 4
assert mult_two(3) == 6

Write a function that takes two inputs, adds them together, and returns the result#

Call this function add_two.

def add_two(_FILL_IN_INPUTS_):
    
### BEGIN SOLUTION
def add_two(num1, num2):

    answer = num1 + num2
    return answer
### END SOLUTION
# Check that you can use the function
add_two(2, 2)
# Check this function returns the correct number
assert add_two(2, 2) == 4
assert add_two(3, 2) == 5

Write a function with a conditional inside it#

You can decide what this function does.

It could, for example, take in a boolean and print out a status if the given boolean is True.

### BEGIN SOLUTION
def check_bool(input_bool):
    
    if input_bool == True:
        out = 'Status is True'
    else:
        out = 'Status is not True'
    
    return out
### END SOLUTION
# you can test out your function down here...

Part 2: Conditionals#

Conditionals a form of control flow for executing certain code if a specific condition is met.

Conditional Questions#

In this part, we will re-visit some questions about conditionals, and start combining them together with collections.

Make sure you can use if/elif/else statements to control which code blocks are run.

Controlling Output With Conditionals I#

Using the code below, keep updating the variable value to make sure you can make the conditional return each of the possibilities.

# ToDo: Update value to control what gets executed
value = 10

# This code provided
if type(value) == int:
    if value < 10:
        result = 'small value'
    if value >= 10:
        result = 'big value'
else:
    result = 'false value'
print(result)

Controlling Output With Conditionals II#

In the cell below, first write something into each result assignment string below. For example, it could be something like: “B1 is False & B2 is True”).

Then make sure you can change values of b1 & b2 to make the program execute each option.

Note: You can edit the code provided directly without adding any additional code. The raise NotImplementedError is there to visually let you know that we want you to do something in the cell.

# ToDo: Update strings stored in result to control what gets executed
b1 = False
b2 = False

# Next, try this out
if b1 and not b2:
    result = ''
elif not b1 and b2:
    result = ''
elif b1 and b2:
    result = ''
else:
    result = ''
    
### BEGIN SOLUTION
# specific strings could vary
if b1 and not b2:
    result = 'b1 true; b2 false'
elif not b1 and b2:
    result = 'b1 false; b2 true'
elif b1 and b2:
    result = 'both true'
else:
    result = 'both false'

### END SOLUTION
print(result)

Conditional Challenges#

The following are more challenging questions relating to conditional statements. If they seem too tricky for now, just skip ahead to the next section.

Conditional Challenge #1#

Write a conditional that prints “Found it” if a given val_2 is a multiple of 10, otherwise prints “Nope.”

### BEGIN SOLUTION
# Set a test value for `val_2`
val_2 = 100

if val_2 % 10 == 0:
    print('Found it')
else:
    print('Nope')
### END SOLUTION

Conditional Challenge #2#

Input: assumes a variable val_1, that can be either a string or an integer

Output: based on the conditions, this code block will assign a variable called output to be a boolean

Use conditions to check whether val_1 is a string or an integer object:

  • If it is a string, check whether it’s length is greater then 8

    • If so, set the value output to True

  • If it is an integer, compare whether it is less than 100

    • If so, set the value output to True

  • Else, set output to False

### BEGIN SOLUTION
# Set a test value for `val_1`
val_1 = 'string'

if type(val_1) == str and len(val_1) > 8:
    output = True
elif type(val_1) == int and val_1 < 100:
    output = True
else:
    output = False

# Check the output
print(output)
### END SOLUTION
assert type(output) == bool

Operator Explorations#

For each of the following questions, start by writing out a guess of what you think it might do.

Then, test out each one by writing out some code.

Finally, once you have answered the question, using some code, add a comment in the markdown here with the answer.

Questions:

  • Can you include multiple conditions in an if statement?

    • If think so, write an if statement that tests multiple conditions.

  • What happens if you put an if statement inside an if statement? When would such a statement run?

    • To explore this, write an if statement that has an embedded if statement in it.

### BEGIN SOLUTION
v1 = True
v2 = False

# Option 1
# Yes, you can include multiple conditions in an if statement
if v1 == True and v2 == False:
    print('YES!')

# Option 2
# Yes, you can have an if statement within an if statement
#   The embedded if will end up running if both conditions of both if's are True   
if v1 == True:
    if v2 == False:
        print('Also YES!')
### END SOLUTION

Part 3: Collections#

Collections are Python variable types than can store a ‘collection’ of items.

Here we’ll practice defining collections and indexing.

Collection Questions#

Create a list, a tuple, and a dictionary. Fill them with with any values you want.

Call them my_list, my_tuple, and my_dictionary.

### BEGIN SOLUTION
# specific values will differ
my_list = [1, 2, 3]
my_tuple = ('a', 'b', 'c')
my_dictionary = {'First' : 'Shannon',
                 'Last' : 'Ellis'}
### END SOLUTION

Use the following cells to check the types of the variables you write are as expected

type(my_list)
type(my_tuple)
type(my_dictionary)

On an assignment, you’d likely see the same concept tested with the following assert statements

assert type(my_list) == list
assert type(my_tuple) == tuple
assert type(my_dictionary) == dict

Declaring Collections#

Note that there can be more than one way to declare collections.

As well as declaring them with ‘[]’ and ‘()’, we can use the list & tuple constructors, as shown below.

# Run me! - This creates another list & tuple, using the list & tuple constructors
some_list = list([1, 2, 3, 4, 5])
some_tuple = tuple(["peanut", "butter", "and", "jelly"])
some_dict = dict([('First', 'Shannon'), ('Last', 'Ellis')])

print("'some_list' contains: \t", some_list)
print("'some_tuple' contains: \t", some_tuple)
print("'some_dict' contains: \t", some_dict)

Compare the types of these variables to your equivalent variables to confirm.

In the cell below, start with the code provided here:

# Fill in `_WRITE_IN_TYPE_HERE` with the type you expect each variable to be
assert type(some_list) == _WRITE_IN_TYPE_HERE_
assert type(some_tuple) == _WRITE_IN_TYPE_HERE_
assert type(some_dict) == _WRITE_IN_TYPE_HERE_

…but edit the code write in the type of the objects that you expect them to be, and make sure the asserts pass.

### BEGIN SOLUTION
assert type(some_list) == list
assert type(some_tuple) == tuple
assert type(some_dict) == dict
### END SOLUTION

Indexing#

Given the following list (my_lst, defined below), do the following operations:

  • Get the length of the list (assign this to a variable lst_len)

  • Get the 1st element of the list (call the selection ind1)

  • Get the last element of the list (call the selection ind2)

  • Get the second to the fourth element of the list (call the selection ind3)

  • Get from the fifth element, to the end of the list (call the selection ind4)

  • Get every second element of the list, starting at the first element (call the selection ind5)

  • Get every second element of the list, starting at the second element (call the selection ind6)

A reminder: this is a coding lab, so the goal is to explore with guidance. Being “right” matters less than understanding. That said, when we say “second to fourth element” we’re referring to the position in the list, not the index, so a list of [‘a’, ‘b’, ‘c’, ‘d’], the “second to fourth element would be [‘b’, ‘c’, ‘d’].

my_lst = ['a', True, 12, 'tomato', False, None, 23, 'python', [], 5.5]
### BEGIN SOLUTION
lst_len = len(my_lst)
ind1 = my_lst[0]
ind2 = my_lst[-1]
ind3 = my_lst[1:4]
ind4 = my_lst[4:]
ind5 = my_lst[0::2]
ind6 = my_lst[1::2]
### END SOLUTION

The End!#

This is the end of this Coding Lab!

Be sure you’ve made a concerted effort to complete all the tasks specified in this lab. Then, go ahead and submit on datahub!