In [1]:
#There are several types of data sets in python:
# tuple, list, array, set, matrix
#tuples are immutable objects - that is, they can't be modified once they are created
measures = ('c', 'tsp', 'tbsp', 'oz') #Notice I used parentheses
try:
measures[0]='stick'
except TypeError:
print('Tuple values cannot be updated')
In [2]:
#Lists are tuples that can be updated
ingredients = ['flour', 'sugar', 'butter'] #Notice I used brackets
ingredients[1] = 'brown sugar'
#It's also easy to add data to tuples with the append function
ingredients.append('chocolate chips')
print(ingredients)
#Repeitions is also easy to do with lists
print(ingredients*2)
In [3]:
#Arrays are numpy objects, mainly for arithmetic, but strings can also be used
import numpy as np
amounts1 = np.array([1.75, .5, 0, 11, 0, 0, 1, 0])
amounts2 = np.array([1, 1, 1, 1, 1, 1, 1, 1])
amounts = amounts1+amounts2
print(amounts) #array operations are element-by-element
print(amounts*2) #Multiplying now is no longer repetition
In [4]:
#Sets are the most efficient data types in python, by they are limited
#Sets can only have unique values and are always unsorted
'''
Operation | Equivalent | Result
s.issubset(t) s <= t test whether every element in s is in t
s.issuperset(t) s >= t test whether every element in t is in s
s.union(t) s | t new set with elements from both s and t
s.intersection(t) s & t new set with elements common to s and t
s.difference(t) s - t new set with elements in s but not in t
s.symmetric_difference(t) s ^ t new set with elements in either s or t but not both
'''
my_list = list(range(1000000))
my_set = set(range(1000000))
%timeit 50005 in my_list
%timeit 50005 in my_set
In [16]:
#Dictionaries are useful for organizing data, but they don't have as good of an
#interacting experience
my_dict = {} #Notice how I use braces (sets also use braces)
my_dict['key1'] = []
my_dict['key2'] = {}
my_dict['key2']['key2a'] = 'Hello'
my_dict['key2']['key2b'] = 'World!'
print(my_dict.keys())
print(my_dict['key2']['key2a']+' '+my_dict['key2']['key2b'])
In [5]:
#Loops in Python are notoriously slow, as an example let's time a simple calculation
import time #python's timing module
import numpy as np
import random
%timeit np.sin(np.repeat(amounts,3e5))
start = time.time()
for amount in np.repeat(amounts,3e5):
np.sin(amount)
end = time.time()
print(end-start)
In [6]:
#There are two main types of loops - while and for. Related to these are if/else statements. Let's go over all of those...
#if/else - checking for conditionals
if 'baking soda' not in ingredients:
ingredients.append('baking soda')
elif 'vanilla' not in ingredients:
ingredients.append('vanilla')
else:
print('All ingredients included')
print(ingredients)
In [7]:
#We're still missing some ingredients
ingredients+=['vanilla','eggs','salt']
print(ingredients)
In [8]:
#for loops - Python is indexed based, so closing loops is not necessary
#There are three ways to break a for loop:
# pass - do nothing
# continue - proceed to the next iteration of the loop
# break - move out of loop altogether
for ingredient in ingredients: #Indexing is not required
if 4<len(ingredient)<7:
pass
print('Ingredient is: '+ingredient)
elif 7<len(ingredient)<=11:
print('Moving to next ingredient')
continue
else:
print('Not the eggs!')
break
In [9]:
from ipywidgets import FloatProgress
from IPython.display import display
progress_bar = FloatProgress(min=0, max=100)
display(progress_bar)
#Never use while loops because they are frequently just traps to get stuck in
baking_time = 0
while baking_time<100:
progress_bar.value+=1
baking_time+=1
time.sleep(.01)
print('Cookies are ready!!!')
In [22]:
def function(arg1,arg2,arg3=5.0,):
'''
Doc string goes here
'''
add = arg1+arg2
sub = arg2-arg3
return add,sub
add1,sub1 = function(3.0,2.0)
add2,sub2 = function(3.0,2.0,1.0)
print(add1,sub1)
print('\n')
print(add2,sub2)
In [11]:
def print_recipe(ingredients, amounts, measures=None):
'''
This is a function to print a chocolate chip cookie recipe.
Inputs:
- ingredients: a list of the necessary ingredients
- amounts: an array of the amount of each ingredient
- measures: the list of measures for each amount
Output:
- No outputs. A recipe is printed to the screen.
'''
recipe=''
recipe+='Chocolate Chip Cookies\n\n'
recipe+='{:2.1f} {} {}\n'.format(amounts[2],measures[0],ingredients[2])
recipe+='{:2.1f} {} {}\n'.format(amounts[1],measures[0],ingredients[1])
recipe+='{:2.1f} {}\n'.format(amounts[-2],ingredients[-2])
recipe+='{:2.1f} {} {}\n'.format(amounts[-3],measures[1],ingredients[-3])
recipe+='{:2.2f} {} {}\n'.format(amounts[0],measures[0],ingredients[0])
recipe+='{:2.1f} {} {}\n'.format(amounts[4],measures[1],ingredients[4])
recipe+='{:2.1f} {} {}\n'.format(amounts[-1],measures[1],ingredients[-1])
recipe+='{:2.1f} {} {}\n'.format(amounts[3],measures[-1],ingredients[3])
recipe+='\n'
recipe+='Cream together the butter and brown sugar until light and fluffy.\n'
recipe+='Add eggs one at a time, mixing until combined after each.\n'
recipe+='Add in vanilla extract. Mix until combined.\n'
recipe+='In a separate bowl combine dry ingredients.\n'
recipe+='Add dry ingredients to wet ingredients in three batches. Mix after each.\n'
recipe+='Stir in chocolate chips.\n'
recipe+='Scoop using a 1oz cookie scoop onto ungreased cookie sheets.\n'
recipe+='Bake at 375F for 8-10 minutes until golden brown.\n'
recipe+='Serve warm with milk.'
print(recipe)
return #You can return arguments here
print_recipe(ingredients,amounts,measures)
In [ ]: