This notebook is an exercise in the Python course. You can reference the tutorial at this link.


Try It Yourself

With all you've learned, you can start writing much more interesting programs. See if you can solve the problems below.

As always, run the setup code below before working on the questions.

Exercises

1.

Have you ever felt debugging involved a bit of luck? The following program has a bug. Try to identify the bug and fix it.

Try to identify the bug and fix it in the cell below:

2.

a.

Look at the Python expression below. What do you think we'll get when we run it? When you've made your prediction, uncomment the code and run the cell to see if you were right.

b

R and Python have some libraries (like numpy and pandas) compare each element of the list to 2 (i.e. do an 'element-wise' comparison) and give us a list of booleans like [False, False, True, True].

Implement a function that reproduces this behaviour, returning a list of booleans corresponding to whether the corresponding element is greater than n.

3.

Complete the body of the function below according to its docstring.

4. 🌶️

Next to the Blackjack table, the Python Challenge Casino has a slot machine. You can get a result from the slot machine by calling play_slot_machine(). The number it returns is your winnings in dollars. Usually it returns 0. But sometimes you'll get lucky and get a big payday. Try running it below:

By the way, did we mention that each play costs $1? Don't worry, we'll send you the bill later.

On average, how much money can you expect to gain (or lose) every time you play the machine? The casino keeps it a secret, but you can estimate the average value of each pull using a technique called the Monte Carlo method. To estimate the average outcome, we simulate the scenario many times, and return the average result.

Complete the following function to calculate the average value per play of the slot machine.

When you think you know the expected value per spin, run the code cell below to view the solution and get credit for answering the question.

Keep Going

Many programmers report that dictionaries are their favorite data structure. You'll get to learn about them (as well as strings) in the next lesson.


Have questions or comments? Visit the Learn Discussion forum to chat with other Learners.