CodeSchool FlyingThroughPython Small
CodeSchool FlyingThroughPython Small
Loops
Functions
Brush up on the basics in
Try Python!
Files
Modules
The Spam Van
At the end of this course, we want to create a basic sales system for our circus food truck —
the Spam Van.
o u i n
e e y
n't s
a v e KS !
H O N
Y
e e r i o !
p, C h p l y
Pip Pi s h i n g , s i m
S m a G !
A S H I N
S M
y !
e e k
C h
… But first, we will start with a list of British slang to inspire our
menu.
Level 1
Slanguage
Section 1 – Lists
A List Is a Container of Things
Lists in Python are containers that can store anything
[1, 2, 3, …]
you want.
# list of strings
words = ['cheerio', 'cheers', 'watcha', 'hiya']
slang = ['cheerio', 'pip pip', 'smashing'] Can create the list with british = []
print(slang) elements in it already,
or empty
['smashing', 'yonks']
Level 1
Slanguage
Section 2 – Dictionaries
Maintaining Two Lists
What if we also wanted a list to keep track of the American definitions of our British slang list?
If we do anything to one of our lists, we have to duplicate the operation in the other list.
print(slang)
print(translation)
key value
Great for our slang translator —
'cheerio' 'goodbye'
we can look up the definition of a word with the word!
'knackered' 'tired'
'goodbye'
Dictionaries Can Hold Anything
Dictionaries, like lists, can hold anything you want: numbers, strings, a mix of both, and other
objects.
Dictionary of anything
slang = {}
print(slang)
slang['smashing'] = 'awesome'
print(slang['smashing'])
awesome
Removing Dictionary Items
You can delete an item from a dictionary by looking up its key.
slang['bloody']
KeyError: 'bloody'
If exists… if result:
print(result)
Other wise else:
print('Key doesn't exist')
print(sentence)
print(translation)
Slanguage
Section 3 – Comparing and Combining
Lists and Dictionaries
Comparing Lists
How do we check if two lists are equal?
my_list = [1, 2, 3, 4]
your_list = [4, 3, 2, 1]
his_list = [1, 2, 3, 4]
One list?
A List of Lists
You can have a container of containers — Menus is a list of menus, and each menu is a list of foods.
list of lists
A good start! Now we just need to get the second item in this list.
Getting an Item From a Two-dimensional List
You can use two indexes to get an individual item.
Loopty Loops
Section 1 – For Loops and range()
The Spam Van
At the end of this course, we want to create a basic sales system for our circus food truck —
the Spam Van.
# Average price
total = 0
prices = [2.50, 3.50, 4.50]
# Average price
total = 0
prices = [2.50, 3.50, 4.50]
avg is 3.5
Generating Raffle Tickets
We also want to do something fun for our customers — with each purchase, they get a raffle
ticket, and then we draw 10 random ticket numbers at the end of the day and give out prizes.
import random
r1 = random.random() Gives us a random number from [0.0, 1.0)
print(r1)
0.80945
range(10)
698
689
328
113 We don’t have to use i in our loop,
707 but we can if we want to…
958
440
297
189
899
Getting More Specific With range()
We’ve held our circus in Orlando, Florida, every other year since 2005 until now — 2016.
How would we list the years?
start stop step
for i in range(2005, 2016, 2): We can also call range() with more
print(i) parameters: start, stop, and step.
2005 Add 2
2007
2009
2011
2013
2015 Stop before
2016
Level 2
Loopty Loops
Section 2 – The Spam Van Menu
The Spam Van
At the end of this course, we want to create a basic sales system for our circus food truck —
the Spam Van.
… Let’s start creating the menu with for loops The Spam Van
Menu
Create Our Monty Python Restaurant Menu
For each British slang word, let’s create a menu item made with Spam.
menu = []
menu = ['Knackered Spam', 'Pip pip Spam', 'Squidgy Spam', 'Smashing Spam']
Could we print out each item in our dictionary in a loop like a list?
Loopty Loops
Section 3 – While Loops
Interface for Ordering Menu Items
We want to let customers order and add as many menu items as they want. A for loop wouldn’t
be good for this because we don’t know how many times to loop…
x Loop Output
1st loop 1 x is 1
2nd loop 2 x is 2
3rd loop 3 loop is done running
Let’s Create Our Interface for Ordering From a Menu
We’ll use a while loop to let customers order and add as many menu items as they want.
orders = []
order = input("What would you like to order? (Q to Quit)")
orders = []
order = input("What would you like to order? (Q to Quit)")
orders = []
order = input("What would you like to order? (Q to Quit)")
print(orders)
Using Continue for Special Cases in the Loop
We have a problem — we ran out of Cheeky Spam! We’ll need to let customers know…
orders = []
order = input("What would you like to order? (Q to Quit)")
while (True):
if order == 'Cheeky Spam': If the order is Cheeky Spam,
print('Sorry, we're all out of that!') skip the rest of the code in the loop one time,
continue go to the top, and start running again.
if order.upper() == 'Q':
break
print(orders)
Infinite Loops Are Bad
Oops, we accidentally
created an infinite loop!
…
while (True):
# See if the customer wants to order anything else Move the ordering
order = input("Can I take your order? (Q to Quit)") to the top of the loop.
print(orders)
Ordering Interface Demo
Level 3
Functions in Flight
Section 1 – Introduction to Functions
Problem: We’re Repeating a Lot of Code
And we also want to
We’ve got this code that And this code that gets the
write code to calculate
gets the average price average daily customers
average daily sales…
# Average price # Average daily customers
total = 0 total = 0
prices = [2.50, 3, 4.50, 5] customers = [29, 21, 55, 5
10, 14, 12]
for price in prices:
total = total + price for cust in customers:
total = total + cust
average = total/len(prices)
average = total/len(customers)
Wouldn’t it be great to just have one piece of code that can average anything we ask it to?
Functions Perform Specific Tasks
Functions are like mini programs that allow us to perform a specific task.
1 What is the
function name?
Name:
The name of the function is
how we’ll run it later.
Parameters:
Any variables
we need the
def average(prices): function to use
...
Step Three: Return Data From the Function
def average(prices):
...
return avg
Indented:
The code inside of the
function is indented.
Return value:
Functions may or may not return values —
this function returns the value of a
variable called avg.
Return value
Calling the average() Function
Functions don’t run until you call them.
Notice how this general average function can average the numbers in any list!
For example, we can use it here…
The variable name of our list
daily_sales = [10,14,8] doesn’t have to match what it’s
result = average(daily_sales) called in the function.
How Our Function Executes Code
This is our file with our function defined, followed by our main program where we use our function.
avg = total/len(numbers)
return avg
print(result)
3.75
Level 3
Functions in Flight
Section 2 – main()
main() and Calling main()
A best practice is to organize our main program code into a function called… main().
Before After
def average(numbers): def average(numbers):
total = 0 total = 0
for num in numbers: for num in list:
total = total + num total = total + num
def average(numbers):
* The average() total = 0
function will only for num in list:
run when it gets total = total + num
called.
avg = total/len(numbers)
Since these are
return avg
functions, they don’t
get run until they're
def main(): called.
2 Then runs all of the prices = [29, 21, 55, 10]
result =* average(prices)
code in main()
print(result)
main()
1 All of the execution
starts here!
Understanding Local Scope
def average(numbers):
total = 0 Local scope
for num in list:
total = total + num The variables declared in
the average function only
exist within the function.
avg = total/len(numbers)
return avg Their scope is local
to this function.
def main():
prices = [29, 21, 55, 10]
result = average(prices)
print(total) If we try to access
print(result) total in main(),
we get this error…
main()
avg = total/len(numbers)
return avg
def main():
prices = [29, 21, 55, 10]
If we try to access
result = average(prices)
print(order_goal) order_goal in main(),
NO errors…
print(result)
avg = total/len(numbers)
return avg
def main():
prices = [29, 21, 55, 10]
result = average(prices) At this point, order_goal
print(order_goal) hasn’t been declared yet!
print(result) So we'll get an error here…
Functions in Flight
Section 3 – Spam Van Functions
When to Create Functions?
Functions should be used for any chunk of code that has a specific purpose. For instance, here
are all of the things we want to implement in our Food Truck Order System:
def function(parameters…):
parameters:
we need the menu to
def print_menu(menu): be able to print it
for name, price in menu.items():
print(name, ': $', format(price, '.2f'), sep='')
Function
def get_order(menu):
definition Parameters
orders = []
We need the
Indented order = input("What would you like to order? (Q to Quit)")
menu to add
the item to
while (order.upper() != 'Q'):
the order.
# find the order
found = menu.get(order)
if found:
orders.append(order)
else:
print("Menu item doesn't exist")
The code to get
order = input("Anything else? (Q to Quit)") an order that we
already wrote
Return return orders
value
How the main() Function Executes
def get_order(menu):
…
def print_menu(menu):
…
def main():
menu = {'Knackered Spam': 0.50, 'Pip pip Spam': 1.50, …}
print_menu(menu)
order = get_order(menu)
print("You ordered:",order)
main()
3 Calculating the Total Bill
Finally, we want to calculate the customer’s total bill.
menu
orders
cheeky spam 1.0
cheeky spam cheerio spam 2.0 Could have added this
line… :-/
Parameters
def bill_total(orders, menu): We need the list of orders and
total = 0 the menu to look up the price.
return total
bill_total() After the Second Order
First loop:
order: 'cheeky spam'
orders menu
total = 0 + 1.0 = 1.0
cheeky spam 1.0
cheeky spam order: 'pip pip spam'
cheerio spam 2.0
pip pip spam total = 1.0 + 3.0 = 4.0
pip pip spam 3.0
knackered spam
knackered spam 4.0 Add the price to the total
return total
bill_total() After the Third Order
First loop:
order: 'cheeky spam'
orders menu
total = 0 + 1.0 = 1.0
cheeky spam 1.0
cheeky spam order: 'pip pip spam'
cheerio spam 2.0
pip pip spam total = 1.0 + 3.0 = 4.0
pip pip spam 3.0
knackered spam
knackered spam 4.0 order: 'knackered spam'
total = 4.0 + 4.0 = 8.0
Take each order Look up its price in the menu return total
return total
Putting It All Together
spam_van.py
def print_menu(menu):
…
def get_order(menu):
…
def total_bill(orders, menu):
…
def main():
menu = {'Knackered Spam': 0.50, 'Pip pip Spam': 1.50, …}
print_menu(menu)
orders = get_order(menu)
total = bill_total(orders, menu)
print("You ordered:", order,
"Your total is: $", format(total,'.2f'), sep='')
main()
Demo of the Spam Van
Level 4
s a le s .t x t
3 Close sales_log.close()
One single order comes in as a dictionary of menu items and their price.
s a le s .tx t
Customer 1 order = {'Cheeky Spam': 1.0, 'Chips Spam': 4.0}
Cheeky Spam 1.00
Yonks Spam 4.00
total = 5.00
def main():
order = {'Cheeky Spam': 1.0, 'Yonks Spam': 4.0}
write_sales_log(order)
file.close()
def main():
order = {'Cheeky Spam': 1.0, 'Yonks Spam': 4.0}
write_sales_log(order ) We over write the file…
order = {'Cheerio Spam': 1.0, 'Smashing Spam': 3.0} Instead, we want to append.
write_sales_log(order)
Appending Orders to Our File
def write_sales_log(order):
file = open('sales.txt', 'a' ) 'a' for append s a le s .tx t
Cheeky Spam 1.00
total = 0 Yonks Spam 4.00
for item, price in order.items(): total = 5.00
file.write(item + ' ' + format(price, '.2f') + '\n') Cheerio Spam 1.00
total += price Smashing Spam 3.00
total = 4.00
file.write('total = ' + format(total, '.2f') + '\n')
file.close()
def main():
order = {'Cheeky Spam': 1.0, 'Yonks Spam': 4.0}
write_sales_log(order )
order = {'Cheerio Spam': 1.0, 'Smashing Spam': 3.0}
write_sales_log(order)
Adding a Newline Between Orders
def write_sales_log(order):
file = open('sales.txt', 'a' )
s a le s .tx t
total = 0 Cheeky Spam 1.00
for item, price in order.items(): Yonks Spam 4.00
file.write(item + ' ' + format(price, '.2f') + '\n') total = 5.00
total += price Cheerio Spam 1.00
Smashing Spam 3.00
file.write('total = ' + format(total, '.2f') + '\n\n') total = 4.00
file.close()
def main():
order = {'Cheeky Spam': 1.0, 'Yonks Spam': 4.0}
write_sales_log(order )
order = {'Cheerio Spam': 1.0, 'Smashing Spam': 3.0}
write_sales_log(order)
Level 4
Today's
dollar menu!
l l a r _me n u .t x t
do
cheeky spam
cheerio spam
pip pip spam ['Cheeky Spam', 'Cheerio Spam', 'Pip Pip Spam']
Reading the Entire Contents of a File
file_name.read() will return a string containing the entire contents of the file.
file name mode
l l a r _m e n u .t x t
do
1 open dollar_spam = open('dollar_menu.txt', 'r')
cheeky spam 'r' for read
cheerio spam 2 read print(dollar_spam.read())
pip pip spam
3 close dollar_spam.close()
cheeky spam
cheerio spam
pip pip spam
Reading an Individual Line From a File
file_name.readline() will return a string for the next single line in the file.
l l a r _m e n u .t x t
do def read_dollar_menu():
dollar_spam = open('dollar_menu.txt', 'r')
cheeky spam print('1st line:', dollar_spam.readline())
cheerio spam readline() will read print('2nd line:', dollar_spam.readline())
pip pip spam until a newline '\n' dollar_spam.close()
l l a r _m e n u .t x t def read_dollar_menu():
do
dollar_spam = open('dollar_menu.txt', 'r')
cheeky spam
for line in dollar_spam: Now, instead of
cheerio spam
print(line) printing each line,
pip pip spam
let’s add them to a list.
dollar_spam.close()
Cheerio Spam
Knackered Spam
Cheeky Spam
Reading the Dollar Menu Into a List
We can add each line item to a list inside of our for loop.
def read_dollar_menu():
l l a r _m e n u .t x t dollar_spam = open('dollar_menu.txt', 'r')
do
def read_dollar_menu():
_ m aern_u
m .texntu .t x t dollar_spam = open('dollar_menu.txt', 'r')
do l l adro l l
print(dollar_menu)
dollar_spam.close()
try:
price = float(price)
print('Price =', price)
except ValueError: We can also look for a
print('Not a number!') specific type of error.
The user enters a number so there’s no error. Program prints the exception,
telling the user what the problem was,
then continues.
Storing the Exception’s Error Message
We can also save the exception’s error message in a variable for printing.
try:
price = float(price)
print('Price =', price)
except ValueError as err: Create a variable 'e rr'
print(err) to hold the error message.
Headquarters
Menu
To do this, we need
the Python requests module.
Introducing Modules
Modules are code libraries that contain functions we can call from our code. They make our lives
easier by implementing the hard stuff for us.
Collecting requests
downloading …100%
Installing collected packages: requests
Successfully installed requests-2.8.1
print(first_item['name'], first_item['price'])
print(second_item['name'], second_item['price'])
Instead of hard-coding this menu, let’s get it from our HTTP request.
Getting Today’s Menu
Requesting and printing today’s menu.
print(menu_list)
import requests
my_request = requests.get('http://go.codeschool.com/spamvanmenu')
menu_list = my_request.json()
print("Today's Menu:")
for item in menu_list:
print(item['name'], item['desc'], item['price'])
Today's Menu:
Omelet Yummy 3.00
Burrito Breakfast Burrito 5.75
Waffles Belgian waffles with syrup 4.50
Formatting the Menu
Requesting and printing today’s menu.
import requests
my_request = requests.get('http://go.codeschool.com/spamvanmenu')
menu_list = my_request.json()
print("Today's Menu:")
for item in menu_list:
print(item['name'], ': ', item['desc'].title(), ', $',
item['price'], sep='' )
Today's Menu:
Omelet: Yummy, $3.00
Burrito: Breakfast Burrito, $5.75
Waffles: Belgian waffles with syrup, $4.50
Demo
Level 5
Script
same As long as all of these files are in the same directory, we can import
directory them into spam_van.py by writing import module_name.
Figuring Out What Goes in the Orders Module
spam_van.py orders.py
def print_menu(menu):
We want to move …
these definitions def get_order(menu):
into a separate …
orders.py file. def total_bill(orders, menu):
…
Module
Need to figure out
how to use orders
def main(): functionality in
Our main menu = {'Cheerio Spam': 0.50,…} here
functionality stays print_menu(menu) spam_van.py
in our spam_van.py orders = get_order(menu)
script. total = bill_total(orders, menu)
print('You ordered:', order, 'Total:', total)
main()
Script
The Result of Splitting Orders Into a Module
orders.py
def print_menu(menu):
…
def get_order(menu):
…
def total_bill(orders, menu):
…
spam_van.py
def main():
menu = {'Cheerio Spam': 0.50,…}
print_menu(menu)
orders = get_order(menu)
total = bill_total(orders, menu)
print('You ordered:', order, 'Total:', total)
def main():
menu = {'Cheerio Spam': 0.50,…}
print_menu(menu)
orders = get_order(menu)
total = bill_total(orders, menu)
Wait — this is print('You ordered:', order, 'Total:', total)
still generating main()
an error.
NameError: name 'print_menu' is not defined
Using the Module Name to Access the Functions
orders.py
def print_menu(menu):
…
def get_order(menu):
…
def total_bill(orders, menu):
…
spam_van.py
We need to add import orders
the module name def main():
orders. menu = {'Cheerio Spam': 0.50,…}
before our orders.print_menu(menu)
function calls orders = orders.get_order(menu)
total = orders.bill_total(orders, menu)
print('You ordered:', order, 'Total:', total)
main()
Now our program
will run!
Demo: The App Running