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.
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:
For this particular problem, there is a useful Python operator called in
that returns a boolean value:
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!
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
.
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:
random()
- returns a random float in the range [0,1) (i.e., 0 upto but not including 1)choice(sequence)
- returns a random item in a sequence (a list or string)randrange(x,y)
- returns a random integer from [x,y). If you want to include y
, you can add 1 or use randint(x,y)
to get [x,y].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'
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 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.
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:
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
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:
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:
x
, y
, result
, num1
, num2
, and sum
?main()
give a syntax error?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()