1 of 16

Lecture 13

Conditionals and Iteration

DATA 8

Spring 2020

2 of 16

Weekly Goals

  • Monday
    • No class

  • Wednesday
    • Table review
    • Table examples
  • Today
    • Booleans, conditionals, and iteration
    • Simulation

3 of 16

Announcements

4 of 16

Comparison and Booleans

5 of 16

Comparison Operators

The result of a comparison expression is a bool value

x = 2 y = 3

x > 1 x > y y >= 3

x == y x != 2 2 < x < 5

Assignment statements

Comparison expressions

6 of 16

Aggregating Comparisons

Summing an array or list of bool values will count the True values only.

1 + 0 + 1 == 2

True + False + True == 2

sum([1 , 0 , 1 ]) == 2

sum([True, False, True]) == 2

(Demo)

7 of 16

Control Statements

8 of 16

Control Statements

These statements control the sequence of computations that are performed in a program

  • The keywords if and for begin control statements

  • The purpose of if is to define functions that choose different behavior based on their arguments

(Demo)

9 of 16

Random Selection

10 of 16

Random Selection

np.random.choice

  • Selects uniformly at random
  • with replacement
  • from an array,
  • a specified number of times

np.random.choice(some_array, sample_size)

(Demo)

11 of 16

Appending Arrays

12 of 16

A Longer Array

  • np.append(array_1, value)
    • new array with value appended to array_1
    • value has to be of the same type as elements of array_1
  • np.append(array_1, array_2)
    • new array with array_2 appended to array_1
    • array_2 elements must have the same type as array_1 elements

(Demo)

13 of 16

Iteration

14 of 16

for Statements

  • for is a keyword that begins a control statement

  • The purpose of for is to perform a computation for every element in a list or array

(Demo)

15 of 16

Optional: Advanced where

16 of 16

A Closer Look at where

t.where(array_of_bool_values)

returns a table

with only the rows of t for which

the corresponding bool is True.

(Demo)