Running Python programs
Python and PyCharm
Here are the functions we wrote last time:
def add_shipping(subtotal: int) -> int: """add shipping amount to subtotal""" if subtotal <= 50: return subtotal + 10 elif subtotal > 50 and subtotal <= 100: return subtotal + 20 else: return subtotal + 30 dairy = ["milk", "cheese", "yogurt"] def is_vegan(food: str) -> bool: """determine whether food is vegan""" return food not in dairy def number_size(n: int) -> str: """approximate size of a number""" if n > 1000: return "big" return "small"
Today we saw how to interact with Python programs using PyCharm, the development environment we use for the course. We saw:
- The console, which is the Python equivalent of the Pyret Interaction Window
- PyCharm’s debugger, which let us step through programs and see how the program directory changed
Loops
Let’s say we wanted to modify our is_vegan
function to return False
on
inputs like "greek yogurt"
or "cheddar cheese"
, where a dairy product is
part of a food. We could write such a function like this:
def is_vegan(food: str) -> bool: """determine whether food is vegan""" if "milk" in food: return False if "cheese" in food: return False if "yogurt" in food: return False return True
There are a couple of things to notice here:
- Booleans are spelled with capital letters in Python:
True
andFalse
str1 in str2
returnsTrue
if the second string contains the first string (likestring-contains
in Pyret)
This function will work, but it’s a little unsatisfying–we’re no longer using our list of dairy items! We can rewrite it to use the list using a for-loop:
dairy = ["milk", "cheese", "yogurt"] def is_vegan(food: str) -> bool: """determine whether food is vegan""" for ingredient in dairy: if ingredient in food: return False return True
Python’s for-loops let us loop over a list and do a computation at every
element; we’ll use them instead of the recursive list functions we would have
written in Pyret. This for-loop executes its body (if ingredient...
) once for
every element of the dairy
list. Each time, it adds the name ingredient
to
the program dictionary with each subsequent value of the list. So first
ingredient
is "milk"
, then "cheese"
, then "yogurt"
.
In class, we stepped through the execution of this for-loop in the debugger–see the lecture capture for details.