HW5, practice material from the “Whirlwind Tour of Python”

The material covered in lectures 8 and 9 will primarily be practiced as you work on your individual project.

Thus, this homework is a little different from the others. It is based on sections 8-13 of https://jakevdp.github.io/WhirlwindTourOfPython/index.html. Knowing this material will help you with Python programming in general, and your project in particular.

The question numbers start with 8 so that the numbers align with the section of the book. Thus, it points to which section to read if you do not already know how to answer the question.

8. Control Flow Statements

i. Write your own working if-elif-else statement

In [ ]:

ii. What does the break statement do?

iii. Write your own for loop that includes a break statement, that causes some output to be different than if the break were not included. Verify that output.

In [ ]:

iv. What does the continue statement do?

v. Write your own while loop that includes a continue statement. Check that the statement did what was expected.

In [ ]:

9. Defining Functions

Define a function (which has not been used in an example in class or in the Whirlwind book) that has at least one required and one optional parameter, and then call it.

Suggestion: Write this answer with the next question in mind. In the next question you’ll need some code that sometimes works, and sometimes has an error. If this is true of what you write here, you can use the same function and then update it to catch the error when you answer the next question.

In [ ]:

10. Errors and Exceptions

Write a function that sometimes will work and sometimes will not (this can be your answer to the previous problem). Add a try-catch (try…except) clause so you get a nice, clean error message instead of a runtime error.

In [ ]:

11. Iterators

  1. Write a function using the enumerate iterator.
In [ ]:

  1. Write a function using the zip iterator.
In [ ]:

12. List Comprehensions

Is the following a valid line of Python code? If so, what is the output? If not, fix what is wrong and then list the output. ~~[val for val in range(20) if val % 3 = 0]~~

In [ ]:

13. Generators and Generator Expressions

What is the difference between the following two snippets of code?

P = (n ** 2 for n in range(12))
for val in P:
    print(val, end=' ')
Q = [n ** 2 for n in range(12)]
for val in Q:
    print(val, end=' ')