Class Notes Week 4


Week 4 Topics

Monday Wednesday Friday


Boolean flags

We’ve seen many boolean expression above. Just as we can save the result of a mathematical expression as a variable, we can save the result of boolean expressions as variables e.g.,

voter = age >= 18

The value of voter is either True or False depending on whether age is greater than or equal to 18. A common use of boolean variables is for boolean flags, which resemble the accumulator pattern.

Exercise: Contains an a

In contains_a.py, write a program that determines if a user-inputted word contains the letter a. This is in the week 3 directory:

$ cd cs21/inclass/w03-boolean
$ atom contains_a.py

For this particular problem, there is a useful Python operator called in that returns a boolean value:

value in sequence

For example:

if "a" in word:
  print("Found an a!")
else:
  print("There was no a in word")

This is definitely simpler. But it is important to recognize that Python is actually using the answer we wrote together (boolean flag) to actually answer the if statement above!

Indefinite Loops

We’ll motivate this module with the program badTax.py, which calculates a user’s total after getting the base price and the tax rate:

$ cd ~/cs21/w04-functions/
$ python3 badTax.py
Enter item price: 100
Enter tax rate %: 5.5
The total bill is $105.50

What if the user enters a negative tax rate? We could repeat the question, but how many tries does the user get?

Definite loops (aka for loops) have a pre-defined number of iterations - it is very predictable to know how it will run. In some circumstances, though, we need to ask repetitive questions without knowing how many times we’ll need to answer. In these cases, we need an indefinite loop which is known as a while loop. A while loop is essentially an if statement that gets repeated until the answer is False.

Random library

While getting input from the user is a useful feature of a program, many programs require some sort of randomness. For example, if you playing a game of cards (e.g., poker, solitaire), you want the computer to simulate drawing a random card from a deck. We may also want to flip a coin (heads or tails) or roll a die (1, 2, 3, 4, 5, or 6). Python has a useful set of methods that use randomness (pseudo-randomness, technically) in the random library (https://docs.python.org/3/library/random.html).

Some useful methods include:

Here are some example uses of each method:

>>> import random
>>> random.random()
0.05551979375126459
>>> random.random()
0.9110641790767136
>>> random.randrange(1,11)
5
>>> random.randrange(1,11)
10
>>> random.choice("Swarthmore")
'a'
>>> random.choice("Swarthmore")
'r'
>>> random.choice(["heads","tails"])
'tails'

Exercise: Coin flips

We will accomplish two tasks in coinflip.py:

$ cd ~/cs21/inclass/w04-functions
$ atom coinFlip.py
numHeads = 0 #accumulator variable
for i in range(100):
  if random.choice(["heads","tails"]) == "heads":
    numHeads += 1
print("There were %d heads in 100 flips" % numHeads)

Functions

Functions are defined blocks of code that can be called from other programs or other functions in the same program. They have the advantage of being reusable and also reducing errors by simplifying our code.
We have used several functions already (print, input) and will learn how to define our own.

In jello.py, we see a program that prints out the lyrics to a song for young kids. Notice the errors and the tediousness of repeating code and having to fix code in multiple locations if we did something wrong. In jello_func.py we will look at a modular solution of this program that demonstrates some advantages of using functions.

Example: Birthday math

The program birthday.py asks for a users birthday and converts into decimal form that perfectly represents the birthday. For example, if you are born on June 13, 2014 it will produce the integer (not string) 61304.

The program birthdayFunc.py does the same thing, but using functions. With your neighbor, answer the following:

Exercise: Counting Letters

In countLetters.py, create a function that takes in the user word and chosen letter and returns the number of times the letter appears in the word. For example, the letter ‘l’ appears three times in the word ‘lollipop’. Here is an example run:

$ python3 countLetters.py
Enter word: lollipop
Enter letter: l

There are 3 l's in lollipop

Stack Diagrams

In important strategy for understanding our programs is to carefully trace each line of code and notate the state of the program. We have done this informally to this point, but we need to be more formal with functions to be precise about what our program is doing. We will utilize a tool called a stack diagram or stack trace. Here is the general procedure for how a function is run when it is called:

  1. Pause the execution of the current function.
  2. Create a stack frame for the called function
  3. The value of each argument is copied to the corresponding parameter.
  4. Execute called function step-by-step until the return
  5. Send back the return value
  6. Pop the called function off stack
  7. Continue executing calling function that is now back on top of stack

Let us trace through this example program to understand how a stack diagram can be useful:

def addNumbers(num1,num2):
  sum = num1 + num2
  print("In addNumbers:")
  print(num1)
  print(num2)
  print(sum)

  #Show the stack diagram as it exists at this point
  return sum

def main():

  x = 5
  y = 9

  result = addNumbers(x,y)
  print("In main:")
  print(result)
  print(sum) #Gives an error. Why?

Answer the following questions:

Exercise: Stack diagram

Now, try doing a stack diagram yourself. Show the stack diagram as it would appear at the point in the program noted below. In addition, show the output of the complete program.

def absval(x,y):
  if x > y:
    aval = x-y
  else:
    aval = y-x

  # draw stack to this point!
  # as it would look just before return...

  return aval

def main():
  a = 10
  b = 35
  result = absval(a,b)
  print("abs(%d-%d) = %d" % (a,b,result))

main()