# Lecture 11 – Conditional Statements and Iteration¶

## DSC 10, Fall 2022¶

### Announcements¶

• Homework 3 is due tomorrow at 11:59PM.
• Lab 4 is due on Saturday, 10/22 at 11:59PM.
• The Midterm Project will be released Wednesday!
• Partners are not required, but strongly encouraged.
• Before or after discussion today, we'll host a mixer to help you find a partner! See this post on EdStem for details.
• You must use the pair programming model when working with a partner.
• If you have a conflict with your assigned discussion, email TA Dasha (dveraksa@ucsd.edu) to request to attend another.
• Look at the Grade Report on Gradescope to see your scores on all assignments, discussion attendance, and number of used slip days so far.

### Agenda¶

• Booleans.
• Conditional statements (i.e. if-statements).
• Iteration (i.e. for-loops).

Note:

• We've finished introducing new DataFrame manipulation techniques.
• Today we'll cover some foundational programming tools, which will be very relevant as we start to cover more ideas in statistics (next week).

## Booleans¶

### Recap: Booleans¶

• bool is a data type in Python, just like int, float, and str.
• It stands for "Boolean", named after George Boole, an early mathematician.
• There are only two possible Boolean values: True or False.
• Yes or no.
• On or off.
• 1 or 0.
• Comparisons result in Boolean values.

### Boolean operators; not¶

There are three operators that allow us to perform arithmetic with Booleans – not, and, and or.

not flips True ↔️ False.

### The and operator¶

The and operator is placed between two bools. It is True if both are True; otherwise, it's False.

### The or operator¶

The or operator is placed between two bools. It is True if at least one is True; otherwise, it's False.

### Order of operations¶

• By default, the order of operations is not, and, or. See the precedence of all operators in Python here.
• As usual, use (parentheses) to make expressions more clear.

### Booleans can be tricky!¶

For instance, not (a and b) is different than not a and not b! If you're curious, read more about De Morgan's Laws.

### Note: & and | vs. and and or¶

• Use the & and | operators between two Series. Arithmetic will be done element-wise (separately for each row).
• This is relevant when writing DataFrame queries, e.g. df[(df.get('capstone') == 'finished') & (df.get('units') >= 180)].
• Use the and and or operators between two individual Booleans.
• e.g. capstone == 'finished' and units >= 180.

### Concept Check ✅ – Answer at cc.dsc10.com¶

Suppose we define a = True and b = True. What does the following expression evaluate to?

not (((not a) and b) or ((not b) or a))


A. True

B. False

C. Could be either one

### Aside: the in operator¶

Sometimes, we'll want to check if a particular element is in a list/array, or a particular substring is in a string. The in operator can do this for us:

## Conditionals¶

### if-statements¶

• Often, we'll want to run a block of code only if a particular conditional expression is True.
• The syntax for this is as follows (don't forget the colon!):
if <condition>:
<body>

• Indentation matters!

### else¶

else: Do something else if the specified condition is False.

### elif¶

• What if we want to check more than one condition? Use elif.
• elif: if the specified condition is False, check the next condition.
• If that condition is False, check the next condition, and so on, until we see a True condition.
• After seeing a True condition, it evaluates the indented code and stops.
• If none of the conditions are True, the else body is run.

What if we use if instead of elif?

### Example: Percentage to letter grade¶

Below, complete the implementation of the function, grade_converter, which takes in a percentage grade (grade) and returns the corresponding letter grade, according to this table:

Letter Range
A [90, 100]
B [80, 90)
C [70, 80)
D [60, 70)
F [0, 60)

Your function should work on these examples:

>>> grade_converter(84)
'B'

'D'


### Activity¶

def mystery(a, b):
if (a + b > 4) and (b > 0):
return 'bear'
elif (a * b >= 4) or (b < 0):
return 'triton'
else:
return 'bruin'


Without running code:

1. What does mystery(2, 2) return?
2. Find inputs so that calling mystery will produce 'bruin'.

## Iteration¶

### for-loops¶

• Loops allow us to repeat the execution of code. There are two types of loops in Python; the for-loop is one of them.
• The syntax of a for-loop is as follows:
for <element> in <sequence>:
<for body>

• Read this as: "for each element of this sequence, repeat this code."
• Note: lists, arrays, and strings are all examples of sequences.
• Like with if-statements, indentation matters!

### Example: Squares¶

The line print(num, 'squared is', num ** 2) is run four times:

• On the first iteration, num is 4.
• On the second iteration, num is 2.
• On the third iteration, num is 1.
• On the fourth iteration, num is 3.

This happens, even though there is no num = anywhere.

### Activity¶

Using the array colleges, write a for-loop that prints:

Revelle College
John Muir College
Thurgood Marshall College
Earl Warren College
Eleanor Roosevelt College
Sixth College
Seventh College

for college in colleges:
print(college + ' College')


### Ranges¶

• Recall, each element of a list/array has a numerical position.
• The position of the first element is 0, the position of the second element is 1, etc.
• We can write a for-loop that accesses each element in an array by using its position.
• np.arange will come in handy.

### Example: Goldilocks and the Three Bears¶

We don't have to use the loop variable!

### Randomization and iteration¶

• In the next few lectures, we'll learn how to simulate random events, like flipping a coin.
• Often, we will:
1. Run an experiment, e.g. "flip 10 coins."
2. Keep track of some result, e.g. "number of heads."
3. Repeat steps 1 and 2 many, many times using a for-loop.

### Storing the results¶

• To store our results, we'll typically use an int or an array.
• If using an int, we define an int variable (usually to 0) before the loop, then use + to add to it inside the loop.
• If using an array, we create an array (usually empty) before the loop, then use np.append to add to it inside the loop.

### np.append¶

• This function takes two inputs:
• an array
• an element to add on to the end of the array
• It returns a new array. It does not modify the input array.
• We typically use it like this to extend an array by one element: name_of_array = np.append(name_of_array, element_to_add)
• Remember to store the result!

### Example: Coin flipping¶

The function flip(n) flips n fair coins and returns the number of heads it saw. (Don't worry about how it works for now.)

Let's repeat the act of flipping 10 coins, 10000 times.

• Each time, we'll use the flip function to flip 10 coins and compute the number of heads we saw.
• We'll store these numbers in an array, heads_array.
• Every time we use our flip function to flip 10 coins, we'll add an element to the end of heads_array.

Now, heads_array contains 10000 numbers, each corresponding to the number of heads in 10 simulated coin flips.

### for-loops in DSC 10¶

• Almost every for-loop in DSC 10 will use the accumulator pattern.

• This means we initialize a variable, and repeatedly add on to it within a loop.
• Do not use for-loops to perform mathematical operations on every element of an array or Series.

• Instead use DataFrame manipulations and built-in array or Series methods.
• Helpful video 🎥: For Loops (and when not to use them) in DSC 10.

### Working with strings¶

String are sequences, so we can iterate over them, too!

### Example: Vowel count¶

Below, complete the implementation of the function vowel_count, which returns the number of vowels in the input string s (including repeats). Example behavior is shown below.

>>> vowel_count('king triton')
3

>>> vowel_count('i go to uc san diego')
8


## Summary, next time¶

### Summary¶

• if-statements allow us to run pieces of code depending on whether certain conditions are True.
• for-loops are used to repeat the execution of code for every element of a sequence.
• Lists, arrays, and strings are examples of sequences.

### Next time¶

• Probability.
• A math lesson – no code!