6  Discussion 06: Iteration and Conditionals (From Summer 2025)

Slides

6.1 Marble Madness

Tiffany has a bag with three marbles. One marble is orange, and the other two are purple. For each round of a game, she draws from the bag 10 times with replacement. She wins the round by drawing at least one orange marble.

Code
from datascience import *
import numpy as np

6.1.1 (a)

Write a function to simulate one round of Tiffany’s game. The function should return True if she wins and False if she loses.

def one_round():
    bag = ____________________
    one_sim = ____________________
    num_orange = ____________________
    return ____________________
Answer
def one_round():
    bag = make_array('purple', 'purple', 'orange')
    one_sim = np.random.choice(bag, 10)
    num_orange = sum(one_sim == 'orange')
    return num_orange >= 1

Instead of sum, students can also use np.count_nonzero(). They can also use sample_proportions with probabilities (2/3, 1/3).

Working with Probability and Functions
  • Defining a function that simulates one round is like defining a function to calculate a test statistic.

  • Start by defining the bag (population):

    make_array("orange", "purple", "purple")
  • Use == to check which marbles are orange.

  • Use sum or np.count_nonzero to count how many orange marbles are in a sample.

one_round()
True

6.1.2 (b)

Using the function you just defined in part a, finish the following code to help Tiffany simulate 100 rounds of the game and assign the variable win_proportion to the proportion of rounds she wins.

count = 0
for ____________________:
    if ____________________:
        ____________________
win_proportion = ____________________
Answer
count = 0
for i in np.arange(100):
    if one_round():
        count = count + 1
win_proportion = count / 100
win_proportion
0.98
Note that the line “if one_round()” works by incrementing the count variable when one_round() evaluates to True (and will not if one_round() evaluates to False).

6.1.3 (c)

For any one draw, what is the probability that Tiffany draws a purple marble?

Answer P(Draw a purple marble) = \(\frac{2}{3}\)

6.1.4 (d)

For any individual round, what is the probability that Tiffany loses?

Answer Using the multiplication rule:
P(Tiffany loses one round) = P(draw 10 purples) = P(purple)\(^{10}\) = \((\frac{2}{3})^{10}\)

6.1.5 (e)

For any individual round, what is the probability that Tiffany wins?

Answer

Using the complement rule:
P(Tiffany wins one round) = 1 - P(Tiffany loses one round) = 1 - \((\frac{2}{3})^{10}\)

Example: Probability of Tiffany Winning
  • Probability Tiffany loses: she must draw all purple marbles.
    \[ P(\text{all purple}) = \left(\frac{2}{3}\right)^{10} \]
  • Probability Tiffany wins:
    \[ 1 - \left(\frac{2}{3}\right)^{10} \]

When we observe something different from what we expect in real life (i.e., four 3’s in six rolls of a fair die), a natural question to ask is ”Was this unexpected behavior due to random chance, or something else?”

6.2 Chocolate!

6.2.1 (a)

The % operator returns the remainder if you divide by a certain number (e.g., \(11 \% 5 = 1\)). If a number n is odd, what will n % 2 return?

Answer

It will return 1. Note that if a number is even, n%2 will return 0.

n = 11
n % 2
1

6.2.2 (b)

Remember, we can “multiply” a string by a certain number (e.g., 'data8' * 2). What is the result of doing so? Take 'data8' * 2 as an example.

Answer

It will return 'data8data8'. More generally speaking, it will concatenate the string with itself that number of times with no empty space between them.

'data8' * 2
'data8data8'

6.2.3 (c)

What will the following code output? Format your answer in the same way you expect Python to output the result of running the following code.

Understanding If vs Else
  • The computer evaluates conditions in order.
    • If the first if is True, it runs that block and skips the else.
  • You can nest if statements inside other ifs.
    • If the outer if is not satisfied, the inner if is not even checked.

Strings in Python

  • You can multiply or add strings:
    • "hi" * 3"hihihi"
    • "Jelly" + "Belly""JellyBelly"
  • Watch out for spaces when concatenating!

if vs elif vs multiple ifs

  • Multiple ifs: even if one condition is True, Python will still check the others.
  • With elif/else: once one condition is satisfied, the rest are skipped.
for c in np.arange(4):
  if c < 2:
    print("Chocolate?")
    if c % 2 == 0:
      print("Yes sir! With or without nuts?")
  else:
    print("CHOCOLATE" + ("!" * c))
Answer
Code
for c in np.arange(4):
  if c < 2:
    print("Chocolate?")
    if c % 2 == 0:
      print("Yes sir! With or without nuts?")
  else:
    print("CHOCOLATE" + ("!" * c))
Chocolate?
Yes sir! With or without nuts?
Chocolate?
CHOCOLATE!!
CHOCOLATE!!!

6.3 Getting Even

6.3.1 (a)

The count_evens function takes in an array of integers and returns the number of even integers in the array. Use a combination of iteration and conditionals to complete the skeleton code below.

def count_evens(an_array):
  num_evens = 0
  for ____________________:
    if ____________________:
        ____________________
  return ____________________
Counting with Loops and Arrays

Why initialize with num_evens = 0?

  • This variable keeps track of how many even numbers have been seen.

For loops

  • Sometimes we care about the loop variable, sometimes we don’t.
  • Here, we only increment num_evens when the current number is even.
    • Controlled with an if condition.

Using arrays instead of loops

  • Arrays often make counting easier than loops.
  • Ways to count evens in an array:
    • sum(condition)
    • np.count_nonzero(condition)
    • len(array) - number_of_odds
  • Many approaches lead to the same answer.
Answer
def count_evens(an_array):
  num_evens = 0
  for num in an_array:
    if num % 2 == 0:
        num_evens = num_evens + 1
  return num_evens
arr = make_array(1, 2, 3, 4, 5, 6, 7)
count_evens(arr)
3

6.3.2 (b)

Now, let’s see how we can write the same function using array operations instead of iteration.

def count_evens(an_array):
  remainder_array = ____________________
  return ____________________
Answer
def count_evens(an_array):
  remainder_array = an_array % 2
  return np.count_nonzero(remainder_array == 0)
arr = make_array(1, 2, 3, 4, 5, 6, 7)
count_evens(arr)
3

Alternate Solution:

def count_evens(an_array):
  remainder_array = an_array % 2
  return len(remainder_array) - sum(remainder_array)
arr = make_array(1, 2, 3, 4, 5, 6, 7)
count_evens(arr)
3