Python Foundations For Data Analysis
Python Foundations For Data Analysis
This is a project-based course for students looking for a practical, hands-on, and highly
engaging approach to learning Python essentials for data analysis
Quizzes & Assignments to test and reinforce key concepts, with step-by-step solutions
Interactive demos to keep you engaged and apply your skills throughout the course
Introduce the Python analytics ecosystem and key reasons why it’s the
1 Why Python? programming language of choice for many data analysts
3 Data Types Introduce native Python data types, common use cases, type conversion
methods, and key concepts like iteration and mutability
Learn how to name and store values in memory using variables, as well as
4 Variables how to overwrite, delete and track them
Learn how to work with numeric data, and use numeric functions to
5 Numeric Data perform a range of arithmetic operations
Learn how to manipulate text via indexing and slicing, calculate string lengths,
6 Strings apply various string methods, and print f-strings to include variables
Learn how to create, modify, and nest lists, tuples, and ranges, all of which
8 Sequence Data Types allow you to store many values within a single variable
Understand the logic behind For and While loops and learn how to refine
9 Loops loop logic and handle common errors
Address the limitations of working with lists and explore common scenarios
10 Dictionaries & Sets for using dictionaries and sets in their place
Import the openpyxl package and manipulate data from an Excel worksheet
12 Manipulating Excel Sheets using the Python skills you’ve learned throughout the course
You’ve just been hired as a Data Analytics Intern for Maven Ski Shop, the world’s
THE
#1 store for skis, snowboards, and winter gear. The team is beginning to use
SITUATION Python for data analysis, and needs your help getting up to speed.
• Students looking to learn the most • Students looking to learn Python for
popular open-source analytics tool Software or Web Development
• Anyone who wants to understand the • Anyone who would rather copy and
core fundamentals of the Python paste code or run packages without
language and syntax building the foundational skills
Unlike most analytics With powerful libraries Become part of a large Python can automate Python skills are valuable
tools or self-service and frameworks, Python and active Python user complex tasks and and highly sought after,
Business Intelligence can add value at every community, where you workflows out of the box, and are becoming
platforms, Python is open stage of the analytics can share resources, get without complicated increasingly popular among
source, free to use, and workflow, from data prep help, offer support, and integrations or custom analytics and Business
built for scale and analysis to machine connect with other users plug-ins Intelligence professionals
learning and visualization
When it comes to data analytics, each tool has unique strengths and weaknesses; while Python shouldn’t be the only tool in your stack, it can
add tremendous value when combined with other tools like Excel, SQL, Power BI & Tableau
Mastering base Python will give Pandas helps us structure our Matplotlib and Seaborn can Scikit learn is among the most
you a solid foundational data into dataset formats similar create a wide array of visually popular tools for building and
understanding of the language, to that which you’d see in SQL appealing, static visualizations testing machine learning models
which is essential for using or Excel. It also provides us with
packages and libraries effectively an arsenal of analytical functions Plotly can be used to create Statsmodels provides a suite of
that help us manipulate data and interactive visualizations and tools for model building and
calculate the metrics we need to dynamic dashboards statistical analysis
understand our data
TensorFlow is the industry
standard for developing deep
learning models
Data Analysts often use Python due Data Engineers commonly use Python
to its cost effectiveness, or in to automate complex ETL processes or
collaboration with data science teams interact with APIs.
Analysts are typically well-versed in DBAs often use Pandas to manipulate
base Python, Pandas, and at least one data before storing it in a database or
visualization library data warehouse.
19% of data analyst jobs require 72% of data engineer jobs require
Python skills (25% in California) Python skills
Data Visualization Specialists may use Data Scientists are most likely to use
Python to design custom visuals that the ‘full stack’ of Python data tools.
standard templates can’t support. They leverage packages like Pandas,
They often utilize integrations with Scikit learn, Statsmodels & TensorFlow
tools like Power BI or Tableau. to build and deploy ML models.
33% of data viz roles mention Python 71% of data science and machine
as a required or desired skill learning jobs require Python skills
In this section we’ll install Anaconda and introduce Jupyter Notebooks, a user-friendly
coding environment where we’ll write our first Python program
Installation &
Setup 4) Follow the installation steps
(default settings are OK)
Notebook
Interface
Comments &
2) Click X on the Anaconda Nucleus pop-up
Markdown
(no need to launch)
The Print
Function
Google Colab
Installation &
Setup 4) Follow the installation steps
(default settings are OK)
Notebook
Interface
Comments &
2) Click X on the Anaconda Nucleus pop-up
Markdown
(no need to launch)
The Print
Function
Google Colab
Installation & 1) Launch Anaconda Navigator 2) Find Jupyter Notebook and click
Setup
Notebook
Interface
Comments &
Markdown
The Print
Function
Google Colab
Helpful
Resources
1) Once inside the Jupyter interface, create a folder to store your notebooks for the course
Installation &
Setup
Notebook
Interface
Comments &
Markdown NOTE: You can rename your folder by clicking “Rename” in the top left corner
The Print 2) Open your new coursework folder and launch your first Jupyter notebook!
Function
Google Colab
Helpful
Resources
NOTE: You can rename your notebook by clicking on the title at the top of the screen
NOTE: When you launch a Jupyter notebook, a terminal window may pop up
Installation & as well; this is called a notebook server, and it powers the notebook interface
Setup
Notebook
Interface
Comments &
Markdown
The Print
Function
If you close the server window,
your notebooks will not run!
Installation &
Menu Bar Toolbar Mode Indicator
Setup Options to manipulate the way Buttons for the most-used Displays whether you are in Edit
the notebook functions actions within the notebook Mode or Command Mode
Notebook
Interface
Comments &
Markdown
The Print
Function
Google Colab
Code Cell
Input field where you will write and
Helpful edit new code to be executed
Resources
Notebook
Interface
Comments &
Markdown
The Print
Function
Google Colab
Helpful
Resources
Access options for Interact with the Manage interactive View or edit keyboard
Installation & running the cells in your instance of Python that elements, or ‘widgets’ in shortcuts and access
Setup notebook runs your code your notebook Python reference pages
Notebook
Interface
Comments &
Markdown
The Print
Function
Google Colab
Helpful
Resources
Notebook Save & Checkpoint Move cells up/down Interrupt the kernel Open the command palette
Interface
S I I CTRL SHIFT F
Comments &
Markdown
The Print
Function Insert cell below Cut, Copy & Paste Run cell & select below Restart kernel, rerun Change cell type
B X cut SHIFT ENTER 0 0 Y code
Google Colab C copy M markdown
V paste R raw
Helpful
Resources
Shortcuts may differ depending on which mode you are in
EDIT MODE is for editing content within cells, and is indicated by green highlights and a pen icon
Installation &
Setup
Notebook
Interface
Comments &
Markdown
The Print
COMMAND MODE is for editing the notebook, and is indicated by blue highlights and no icon
Function
Google Colab
Helpful
Resources
The code cell is where you’ll write and execute Python code
Installation &
Setup
Notebook
Interface
In edit mode, the cell will
be highlighted green and
a pencil icon will appear
Comments &
Markdown
The Print
Function
Google Colab
The code cell is where you’ll write and execute Python code
Installation &
Setup
Notebook
Interface Click back into the cell (or use the up arrow)
and press SHIFT + ENTER to rerun the code
Comments &
Markdown
The Print
Note that our output hasn’t changed, but the
Function
number in the brackets increased from 1 to 2.
This is a cell execution counter, which indicates
how many cells you’ve run in the current session.
Google Colab
If the cell is still processing, you’ll see In[*]
Helpful
Resources The cell counter will continue to
increment as you run additional cells
Comments are lines of code that start with ‘#’ and do not run
Installation & • They are great for explaining portions of code for others who may use or review it
Setup
• They can also serve as reminders for yourself when you revisit your code in the future
Notebook
Interface
Think about your audience when
commenting your code (you may not
Comments & need to explain basic arithmetic to an
Markdown
experienced Python programmer)
The Print
Function
Be conscious of over-commenting,
which can actually make your code
Google Colab
even more difficult to read
Helpful
Resources
Comments should explain individual cells or lines of code, NOT your entire workflow – we have better tools for that!
Markdown cells let you write structured text passages to explain your
Installation & workflow, provide additional context, and help users navigate the notebook
Setup
The Print
Function
Google Colab
Notebook
Interface
Comments &
Markdown
The Print
Function
Google Colab
Helpful
Resources
Notebook
Interface
Comments &
Markdown
The Print
Function
Google Colab
Helpful
Resources
Besides print(), Python has many built-in functions along with tools
Helpful
for creating our own custom functions (more on that later!)
Resources
The Print
Function Colab is very similar to Jupyter Notebooks
(they even share the same file extension); the
main difference is that you are connecting to
Google Drive rather than your machine, so
Google Colab files will be stored in Google’s cloud
Helpful
Resources
Google Colab
Code cells are where you write and execute Python code
• Make sure that you know how to run, add, move, and remove cells, as well as how to restart your kernel
or stop the code from executing
In this section we’ll introduce Python data types, review their properties, and cover how
to identify and convert between them
Mutability
Python has a series of built-in data types with different properties and use cases
Data Types These can be grouped into the following categories:
The Type
Function Numeric Text Boolean None
Type Conversion
Iterables
Type Conversion
Text Mapping
Represents sequences of characters, usually text Maps keys to values for efficient information retrieval
• String(str) – 'snowboard' • Dictionary(dict) – {'snowboard': 24,
Iterables 'skis': 17}
Boolean Set
Mutability Represents True and False values Represents a collection of unique, non-duplicate values
• Boolean(bool) – True, False • Set(set) – {'snowboard', 'skis’}
• Frozen Set(frozenset) – {'snowboard’, 'skis’}
None
Represents the absence of a value
• NoneType – None
The type() function will return the data type of the object passed to it
Data Types
The Type
Function
Type Conversion
Iterables
Mutability
PRO TIP: Use type() if you are getting a TypeError or unexpected behavior when passing data through
a function to make sure the data type is correct; it’s not uncommon for values to be stored incorrectly
Iterables Using int attempts to convert the list into an integer data
type, but returns a TypeError instead
This operation isn’t valid because the list has multiple
Mutability values, while an integer can only be one value
Iterables are data types that can be iterated, or looped through, allowing you to
move from one value to the next
Data Types
Type Conversion
Sequence Mapping Set Text
Iterables
The Type
Function
• Lists • Integers
Iterables Note that all simple data
• Dictionaries • Floats types are immutable
• Sets • Strings
Mutability • Booleans
• Tuples
• Frozenset
Iterables are data types with values that you can loop through
• Text strings are iterable despite containing a single value, as you can iterate through its characters
In this section we’ll introduce the concept of variables, including how to properly name,
overwrite, delete, and keep track of them
Naming Conventions Tracking Variables • Learn the rules & best practices for naming variables
Variables are containers used to label and store values for future reference
• They can store any Python data type (and even calls to functions!)
Variable
Assignment
Overwriting &
Deleting
variable_name = value Make sure you add the
space on both sides of
the equal sign!
Naming
Conventions
Variables are containers used to label and store values for future reference
• They can store any Python data type (and even calls to functions!)
Variable
Assignment
Variables are containers used to label and store values for future reference
• They can store any Python data type (and even calls to functions!)
Variable
Assignment
Note that assigning the print() function to a variable here doesn’t necessarily improve our program over
simply calling print() outside of it, but it’s worth knowing even a function call can be assigned to a variable
Results Preview
NEW MESSAGE
February 3, 2022
tax_code.ipynb
ASSIGNMENT: VARIABLE ASSIGNMENT
Solution Code
NEW MESSAGE
February 3, 2022
tax_code.ipynb
OVERWRITING VARIABLES
Tracking price 7 6 5
Variables
Tracking price 7 6 5
Variables
Tracking price 7 6 5
Variables
The del keyword will permanently remove variables and other objects
Variable
Python stores the value of 5 in
Assignment
memory when it is assigned to price
Then del removes it from memory
Overwriting & When we try to print price, we get an
Deleting Error, as the variable no longer exists
Memory
Naming
Conventions
Tracking price 5
Variables NameError occurs when we reference a
variable or object name that isn’t defined
PRO TIP: Deleting objects is generally unnecessary, and mostly used for large objects (like datasets
with 10k+ rows); in most cases, reassign the variables instead and Python will get rid of the old value!
Variable
Assignment Variable names can: Variable names cannot:
Overwriting &
Deleting
• Contain letters (case sensitive!) • Begin with a number
• Contain numbers • Contain spaces or other special
Naming • Contain underscores characters (*, &, ^, -, etc.)
Conventions • Be reserved Python keywords
• Begin with a letter or underscore
like del or list
Tracking
Variables
PRO TIP: “Snake case” is the recommended naming style for Python variables, which is
all lowercase with words separated by underscores (first_second_third, new_price, etc.)
Variable
Assignment Valid variable names: Invalid variable names
Overwriting &
Deleting
• price_list_2019 • 2019_price_list (starts with a number)
• _price_list_2019 • price_list-2019 (has special characters)
Naming • PRICE_LIST_2019 • 2019 price list (has spaces)
Conventions
• pl2019 • list (reserved Python keyword)
Tracking
Variables
PRO TIP: Give your variables intuitive names to make understanding your code
easier – instead of PL19, consider something like price_list_2019 or prices_2019
Variable
Assignment
Overwriting &
Deleting
Results Preview
NEW MESSAGE
February 3, 2022
price_lists.ipynb
ASSIGNMENT: FIXING VARIABLES
Solution Code
NEW MESSAGE
February 3, 2022
price_lists.ipynb
KEY TAKEAWAYS
Variables are containers used to store values from any data type
• These values are stored in memory and can be referenced repeatedly in your code
In this section we’ll cover numeric data types, including how to convert between them,
perform arithmetic operations, and apply numeric functions
Numeric Data
Types
1. Integers (int) – whole numbers without decimal points
• Examples: 3, 42, -14
Numeric Type
Conversion
2. Floats (float) – real numbers with decimal points
Arithmetic
Operators • Examples: 3.14, -1.20134, 0.088
Numeric
Functions 3. Complex (complex) – numbers with real and imaginary portions
• Examples: 3 + 2j, 2.4 - 1j, -2j
Never worked with complex numbers before? Don’t worry! They are rarely used in data
analytics
Use “<data type>(object)” to convert any number into a numeric data type
Numeric Data You can convert floats into integers: And even strings into floats (or integers):
Types
Numeric Type
Conversion
Arithmetic
Operators
Numeric Data
Types – Subtraction Subtracts one value from another 5 - 3 = 2
Numeric Type
Conversion * Multiplication Multiplies two values 5 * 3 = 15
Arithmetic
Operators / Division Divides one value by another 5 / 3 = 1.6666666667
Finally, multiplication
Results Preview
NEW MESSAGE
February 4, 2022
Hi there!
Can you help calculate the following numbers?
• Gross profit from selling a snowboard
• Gross margin from selling a snowboard
• Price needed for a gross margin of 70%
• Sales tax on a snowboard sale
• Amount of money if the gross profit from
selling 5 snowboards is invested for one year
There are more details in the file attached.
financial_calculations.ipynb
Solution Code
NEW MESSAGE
February 4, 2022
Hi there!
Can you help calculate the following numbers?
• Gross profit from selling a snowboard
• Gross margin from selling a snowboard
• Price needed for a gross margin of 70%
• Sales tax on a snowboard sale
• Amount of money if the gross profit from
selling 5 snowboards is invested for one year
There are more details in the file attached.
financial_calculations.ipynb
Single number:
Arithmetic
Operators Multiple numbers:
Numeric Type This rounds the number to This will always return a
Conversion 2 decimal places positive number
Arithmetic
Operators
If number of digits isn’t
supplied, it will round to
Numeric the nearest integer
Functions
The sum(), min(), and min() functions perform sum, minimum, and maximum
calculations on iterable data types that only contain numeric values
Numeric Data
Types
Arithmetic
Operators
This returns the smallest value from the list
Numeric
Functions
Results Preview
NEW MESSAGE
February 4, 2022
Hi there!
Could you quickly run these numbers for me?
• What is the highest priced item we sell?
• What is the lowest priced item we sell?
• How much would it cost for a customer to
purchase two of every item, rounded to the
nearest dollar?
Thanks in advance! (the price list is attached)
customer_questions.ipynb
Solution Code
NEW MESSAGE
February 4, 2022
Hi there!
Could you quickly run these numbers for me?
• What is the highest priced item we sell?
• What is the lowest priced item we sell?
• How much would it cost for a customer to
purchase two of every item, rounded to the
nearest dollar?
Thanks in advance! (the price list is attached)
customer_questions.ipynb
Data analysts typically work with integer & float numeric data types
• Complex numbers are the third numeric data type, but it’s unlikely you’ll ever use them
Python has built-in functions that work with specifically with numbers
• Round, abs, sum, min, and max help perform simple operations that you’d otherwise have to code yourself
In this section we’ll review the fundamentals of strings, a date type used to store text,
and cover functions and methods to manipulate them
String Arithmetic
Single Convert
quotes to string
Indexing & Slicing
Double
The quotes indicate
quotes this is a string
String Methods
Triple
F-Strings quotes
String Arithmetic
String Methods
F-Strings
You can repeat strings using *
Repeating strings is not
very common in practice
Strings, along with sequence data types, can be navigated via their index
String Basics • Python is 0-indexed, which means that the first item in a sequence has an index of 0, not 1
0 I
1
Indexing & Slicing 2 h
String[index] returns a specified character:
3 o
• String[0] returns the first character 4 p
String Methods • String[1] returns the second character …
22 t
• String[2] returns the third character
23 !
F-Strings
Indexing is a critical concept to master for data analysis, and while the
0-index can be confusing at first, with practice it will be second nature
Strings, along with sequence data types, can be navigated via their index
String Basics • Python is 0-indexed, which means that the first item in a sequence has an index of 0, not 1
Results Preview
NEW MESSAGE
February 5, 2022
Hi there!
I need your help deciphering a hidden message. Our
previous intern created a complex password storage
procedure.
I’ve determined one of his passwords is ‘Maven’ ,
but what I’m interested in is the index of the letters
used to spell ‘Maven’ in the attached text messages,
as this will help unlock new passwords.
Thanks in advance!
suspicious_texts.ipynb
Solution Code
NEW MESSAGE
February 5, 2022
Hi there!
I need your help deciphering a hidden message. Our
previous intern created a complex password storage
procedure.
I’ve determined one of his passwords is ‘Maven’ ,
but what I’m interested in is the index of the letters
used to spell ‘Maven’ in the attached text messages,
as this will help unlock new passwords.
Thanks in advance!
suspicious_texts.ipynb
String Arithmetic
[start:stop:step size]
F-Strings
String Basics
String Arithmetic
String Basics
String Arithmetic
String Basics
String Arithmetic
String Basics
String Arithmetic
String Basics
String Arithmetic
String Basics
String Arithmetic
String Basics
String Arithmetic
String Basics
String Arithmetic
String Basics
String Arithmetic
Results Preview
NEW MESSAGE
February 5, 2022
Hi there!
I need help drafting some copy.
We have a long customer testimonial and I want to
view several options for a good testimonial quote.
The full details are in the file attached.
Looking forward to working with you on this!
marketing_copy.ipynb
Solution Code
NEW MESSAGE
February 5, 2022
Hi there!
I need help drafting some copy.
We have a long customer testimonial and I want to
view several options for a good testimonial quote.
The full details are in the file attached.
Looking forward to working with you on this!
marketing_copy.ipynb
F-Strings
Results Preview
NEW MESSAGE
February 5, 2022
suspicious2.ipynb
Solution Code
NEW MESSAGE
February 5, 2022
suspicious2.ipynb
Methods are functions that only apply to a specific data type or object
String Basics • We call them by following the object with a period then the method name
String Arithmetic
String Methods
F-Strings
If you try to apply a string method to an
integer, you will receive an AttributeError
String Methods
Substitutes a given string of characters with another .replace(string to replace, replacement)
F-Strings
Splits a list based on a given separator (space by default) .split(optional string)
For a list of string methods, visit: https://docs.python.org/3/library/stdtypes.html#string-methods *Copyright Maven Analytics, LLC
FIND
The .find() method searches for a specified value within a string and returns the
index of its first instance
String Basics
String Arithmetic
• .find(string)
String Methods
The .upper() and .lower() methods return a given string with all its characters in
uppercase or lowercase respectively
String Basics
String Arithmetic
String Methods
F-Strings
The .strip() method removes leading and trailing spaces (by default), or any
other specified character, from a string
String Basics
• .lstrip() removes all leading spaces, and .rstrip() removes all trailing spaces
String Arithmetic
String Methods
String Arithmetic
F-Strings
• .split(optional string)
String Methods
The .join() method combines individual list elements into a single string,
separated by a given delimiter
F-Strings
This takes the elements in word_list and combines them
into a single string, separated by a single space
• delimiter.join(list)
F-Strings
• And finally divided into a list of separate words with .split()
String Methods
By converting the message to uppercase, it finds the match and returns the index
F-Strings
.find(string) Returns the index of the first instance of a given string .replace(string to replace, replacement) Substitutes a string with another
.upper() Converts all characters in a string to uppercase .split(optional string) Splits a string into a list based on spaces or a delimiter
.lower() Converts all characters in a string to lowercase delimiter.join(list) Combines list elements into a string, separated by a delimiter
.strip(optional string) Removes leading or trailing spaces or characters NOTE: There are many more string methods than covered; to review
those, or get additional detail on the methods covered, visit the
official Python documentation:
https://docs.python.org/3/library/stdtypes.html#string-methods
Results Preview
NEW MESSAGE
February 5, 2022
marketing_copy2.ipynb
Solution Code
NEW MESSAGE
February 5, 2022
marketing_copy2.ipynb
String Methods
Results Preview
NEW MESSAGE
February 5, 2022
price_display.ipynb
Solution Code
NEW MESSAGE
February 5, 2022
Hi again,
Our website is currently displaying static prices, so
we need to manually change them every time a
price changes, and write a new one every time we
get a new product
Can you write a piece of code for a string that takes
product and price as variables? Thanks.
P.S. Don’t work with Sierra anymore, she’s not an
employee
price_display.ipynb
Access single characters with indexing, and multiple characters with slicing
• Indexing & slicing are used with many other data types beyond strings, so they are critical to master
In this section we’ll cover conditional logic, and write programs that make decisions
based on given criteria using true or false expressions
The Boolean data type has two possible values: True & False
• True is equivalent to 1 in arithmetic operations
The Boolean
Data Type • False is equivalent to 0 in arithmetic operations
Boolean
Operators
Conditional
Control Flow
True False
The Boolean
Data Type == Equal 5 == 5 5 == 3
Boolean
Operators != Not Equal 'Hello' != 'world!' 10 != 10
Conditional
Control Flow < Less Than 5 < 6 < 7 21 < 12
Conditional
Control Flow
Boolean
Operators One is True and the other False You can chain together any number of Boolean expressions
Conditional
Control Flow
Boolean
Operators Use parentheses to control the order of evaluation:
Results Preview
NEW MESSAGE
February 6, 2022
inventory_logic.ipynb
Solution Code
NEW MESSAGE
February 6, 2022
inventory_logic.ipynb
The if statement runs lines of indented code when a given logical condition is
met
The Boolean
Data Type
if condition:
Boolean
Operators
Conditional
Control Flow
Indicates an A logical expression that
if statement evaluates to True or False
Examples:
• price > 100
• product == ‘skis’
• inventory > 0 and inventory <= 10
The if statement runs lines of indented code when a given logical condition is
met
The Boolean
Data Type
if condition:
Boolean
Operators do this
Conditional
Control Flow
Code to run if the logical
expression returns True
(must be indented!)
The if statement runs lines of indented code when a given logical condition is met
The Boolean
Data Type
EXAMPLE Determining experience level for a snowboard
How does this code work?
Boolean
Operators
if False
Conditional condition
Control Flow
True
if code
Rest of code
Control flow is a programming concept that allows you to choose which lines
to execute, rather than simply running all the lines from top to bottom
The Boolean
Data Type There are three conditional statements that help achieve this: if, else, and elif
Boolean
Operators
EXAMPLE Determining experience level for a snowboard
Conditional
Control Flow Python uses indentation to
depart from a linear flow
In this case, the first print
statement only runs if price is
greater than 500
Press tab, or use four spaces, to indent your code when writing if statements or you will receive an IndentationError
The else statement runs lines of indented code when the none of the logical
conditions in an if or elif statements are met
The Boolean
Data Type
Conditional
Control Flow if False
condition
True
Rest of code
The elif statement lets you specify additional criteria to evaluate when the
logical condition in an if statement is not met
The Boolean
Data Type
Conditional
Control Flow if False
condition
elif False
True condition
True
Rest of code
Any number of elif statements can be used between the if and else statements
As more logical statements are added, it’s important to be careful with their order
The Boolean
Data Type
Results Preview
NEW MESSAGE
February 6, 2022
inventory_query.ipynb
Solution Code
NEW MESSAGE
February 6, 2022
inventory_query.ipynb
if False
Conditional condition
Control Flow
True
Nested if False
condition
True
Rest of code
Results Preview
NEW MESSAGE
February 6, 2022
inventory_query2.ipynb
Solution Code
NEW MESSAGE With Nesting:
February 6, 2022
inventory_query2.ipynb
Conditional control flow lets you determine which lines of code to execute
• Conditional statements include IF, ELIF, and ELSE, which can be nested for multiple layers of logic
In this section we’ll cover sequence data types, including lists, tuples, and ranges, which
are capable of storing many values
Modifying Lists List Functions & Methods • Understand the different methods for copying lists
Tuples Ranges
List Basics Lists are iterable data types capable of storing many individual elements
• List elements can be any data type, and can be added, changed, or removed at any time
List Operations
List Functions
& Methods While lists can contain multiple data types,
they often contain one data type
Nested Lists
You can create an empty list
and add elements later
Copying Lists
Tuples
You can create lists from
other iterable data types
Ranges
List Basics Since lists are iterable data types, you can conduct membership tests on them
List Operations
‘M’ is not an element in sizes_in_stock,
so False is returned
Modifying Lists
List Functions
& Methods
Tuples
Ranges
List Basics Elements in a list can be accessed via their index, or position within the list
• Remember that Python is 0-indexed, so the first element has an index of 0, not 1
List Operations
List Functions
& Methods
Nested Lists
An index of 3 grabs the
fourth list element
Copying Lists
Tuples
Ranges
List Basics Slice notation can also be used to access portions of lists
[start: stop: step size]
List Operations
Nested Lists
list[::2] grabs every other
element in the list
Copying Lists
Ranges
List Operations
List Functions
& Methods
Nested Lists
Copying Lists
You need to specify the same number of variables as list elements or you will receive a ValueError
Tuples
Ranges
Results Preview
NEW MESSAGE
February 7, 2022
Hi there!
Can you create a list from the customers that made
purchases on Black Friday (attached) and:
• Return 99.99 if C00009 made a purchase;
otherwise return 0.0
• Create separate lists for the 5th and 6th
customers, every third customer, and the last 2
customers, we’re conducting market research.
Thanks again!
black_friday_customers.ipynb
Solution Code
NEW MESSAGE
February 7, 2022
Hi there!
Can you create a list from the customers that made
purchases on Black Friday (attached) and:
• Return 99.99 if C00009 made a purchase;
otherwise return 0.0
• Create separate lists for the 5th and 6th
customers, every third customer, and the last 2
customers, we’re conducting market research.
Thanks again!
black_friday_customers.ipynb
List Basics Lists elements can be changed, but not added, by using indexing
List Operations
List Functions
& Methods
Nested Lists
Tuples
Ranges
Modifying Lists
Nested Lists
Tuples
Ranges
List Basics Lists can be combined, or concatenated, with + and repeated with *
List Operations
Modifying Lists
List Functions
& Methods
Nested Lists
Copying Lists
Tuples
Ranges
List Operations 1. The del keyword deletes the selected elements from the list
• del list_name(slice)
List Functions
& Methods
Nested Lists
2. The .remove() method deletes the first occurrence of the specified value from the list
Copying Lists
Tuples • .remove(value)
Ranges
Results Preview
NEW MESSAGE
February 7, 2022
Adding C00009:
From: Sally Snow (Ski Shop Manager)
Subject: Adding Customers
Hi again!
We just found a receipt for customer C00009 in the
warehouse, can you add them to the customer list? Adding saturday_list:
While you’re at it, we decided to extend the sale
through Saturday since things were so crazy.
Can you add the customers in saturday_list to
customer_list?
Thank you!
updated_customer_lists.ipynb
Solution Code
NEW MESSAGE
February 7, 2022 Adding C00009 with .append():
From: Sally Snow (Ski Shop Manager)
Subject: Adding Customers
Hi again!
Adding C00009 with .insert():
We just found a receipt for customer C00009 in the
warehouse, can you add them to the customer list?
While you’re at it, we decided to extend the sale
through Saturday since things were so crazy.
Can you add the customers in saturday_list to Adding saturday_list
customer_list?
Thank you!
updated_customer_lists.ipynb
Results Preview
NEW MESSAGE
February 7, 2022
Removing Saturday’s customers:
From: Sally Snow (Ski Shop Manager)
Subject: Change of plan!
Hi there!
Sorry to do this to you, but we decided to keep the
Friday and Saturday sales separate for now. Can you Removing C00004:
remove Saturday’s customers from the customer list?
Also, C00004 is a friend of the owner and should not
be counted in the Black Friday sales, so please remove
them from the list.
Thanks again!
updated_updated_customer_lists.ipynb
Solution Code
NEW MESSAGE
February 7, 2022
Removing Saturday’s customers (two methods):
From: Sally Snow (Ski Shop Manager)
Subject: Change of plan!
Hi there!
Sorry to do this to you, but we decided to keep the
Friday and Saturday sales separate for now. Can you
remove Saturday’s customers from the customer list?
Also, C00004 is a friend of the owner and should not
be counted in the Black Friday sales, so please remove
them from the list. Removing C00004:
Thanks again!
updated_updated_customer_lists.ipynb
List Basics
List Operations
len(list_name) Returns the number of elements in a list sum(list_name) Returns the sum of the elements in the list
Modifying Lists
List Functions
& Methods
min(list_name) Returns the smallest element in the list max(list_name) Returns the largest element in the list
Nested Lists
Copying Lists
Tuples
Ranges
2. The sorted function returns a sorted list, but does not change the original (not in place)
Nested Lists
Copying Lists
Tuples
Ranges
List Basics
List Operations
.index(value) Returns the index of a specified value within a list (returns -1 if not found)
Modifying Lists
List Functions
& Methods
.count() Counts the number of times a given value occurs in a list
Nested Lists
Copying Lists
Ranges
Results Preview
NEW MESSAGE
February 7, 2022
Average transaction value: C00010’s transactions:
From: Sally Snow (Ski Shop Manager)
Subject: Customer C00010 Transactions
customer_transactions.ipynb
Solution Code
NEW MESSAGE
February 7, 2022
Average transaction value: C00010’s transactions:
From: Sally Snow (Ski Shop Manager)
Subject: Customer C00010 Transactions
customer_transactions.ipynb
List Basics Lists stored as elements of another list are known as nested lists
List Operations
Modifying Lists
List Functions
& Methods
Copying Lists
Ranges
List Basics List methods & functions still work with nested lists
List Operations
Modifying Lists
List Functions
& Methods
Copying Lists
Ranges
List Operations 1. Variable assignment – assigning a list to a new variable creates a “view”
• Any changes made to one of the lists will be reflected in the other
Modifying Lists
deepcopy is overkill for the vast majority of uses cases, but worth being aware of
Ranges
List Basics Copying a list via variable assignment creates a “view” of the list
• Both variables point to the same object in memory
List Operations • Changing an element in one list will result in a change to the other
Modifying Lists
List Functions
& Methods
Nested Lists
Copying Lists
The change made to list_of_lists is
reflected in list_of_lists2
Tuples
Ranges
List Basics Copying a list with the .copy() method creates a copy of the list
• Changes to entire elements (nested lists) will not carry over between original and copy
List Operations • Changes to individual elements within a nested list will still be reflected in both
Modifying Lists
List Functions
& Methods
Copying Lists
Ranges
List Basics Copying a list with the deepcopy() function creates a separate copy of the list
• Any changes made to one of the lists will NOT impact the other
List Operations
Modifying Lists This function is not part of base Python, so the copy library must be imported
List Functions
& Methods
Nested Lists
Tuples
Ranges
Results Preview
NEW MESSAGE
February 7, 2022
multi_order_customers.ipynb
Solution Code
NEW MESSAGE
February 7, 2022
multi_order_customers.ipynb
List Basics Tuples are iterable data types capable of storing many individual items
• Tuples are very similar to lists, except they are immutable
List Operations • Tuple items can still be any data type, but they CANNOT be added, changed, or removed
once the tuple is created
Modifying Lists
Copying Lists
Tuples
Ranges
List Functions
& Methods
Nested Lists
2. Operations execute quicker on tuples than on lists
Tuples
Ranges
Modifying Lists
4. Tuples are common output in imported functions
List Functions
& Methods Even asking to return multiple variables in
a code cell returns them as a tuple
Nested Lists
Copying Lists
Tuples
Ranges
Results Preview
NEW MESSAGE
February 7, 2022
sales_tax.ipynb
Solution Code
NEW MESSAGE
February 7, 2022
sales_tax.ipynb
List Basics Ranges are sequences of integers generated by a given start, stop, and step size
• They are more memory efficient than tuples, as they don’t generate the integers until needed
List Operations • They save time, as you don’t need to write the list of integers manually in the code
• They are commonly used with loops (more on that later!)
Modifying Lists
List Functions
& Methods
Note that printing a range does NOT return the integers
Nested Lists
Tuples
Ranges
Results Preview
NEW MESSAGE
February 7, 2022
Solution Code
NEW MESSAGE
February 7, 2022 Even Customers:
From: Alfie Alpine (Marketing Manager)
Subject: Customer Giveaway
Lists and tuples are sequence data types capable of storing many values
• Lists allow you to add, remove, and change elements, while tuples do not
In this section we’ll introduce the concept of loops, review different loop types and their
components, and cover control statements for refining their logic and handling errors
A loop is a block of code that will repeat until a given condition is met
Loop Basics
There are two types of loops:
For Loops
A loop is a block of code that will repeat until a given condition is met
Loop Basics
A loop is a block of code that will repeat until a given condition is met
Loop Basics
Loop Control
Don’t worry if the code looks confusing now (we’ll cover loop syntax shortly), the key takeaway is that
we wrote the conversion one time and it was applied until we looped through all the elements in the
list
For Loops
Nested Loops
Indicates a A variable name for each Iterable object to
For Loop item in the iterable loop through
For Loops
Loop Basics
Loop Control
Loop Basics
Loop Control
For Loops
PRO TIP: To create a new list (or other data type) with loops,
first create an empty list, then append values as your loop iterates
For Loops
Looping over indices can help with looping over multiple iterables, allowing
you to use the same index for items you want to process together
Loop Basics
For Loops EXAMPLE Printing the price for each inventory item
The enumerate function will return both the index and item of each item in an
iterable as it loops through
Loop Basics
Nested Loops
Results Preview
NEW MESSAGE
February 8, 2022
Good morning,
Our billing system failed to apply sales tax to our
transactions! Can you add a sales tax of 8% to each
of the subtotals?
Once you’ve calculated tax, calculate the total by 1.28 = round(subtotal[0] * .08, 2)
adding the tax to the subtotal, and create lists to 17.26 = round(1.28 + subtotal[0], 2)
store both the tax amounts and the totals.
Thanks in advance!
taxable_transactions.ipynb
Solution Code
NEW MESSAGE
February 8, 2022
Good morning,
Our billing system failed to apply sales tax to our
transactions! Can you add a sales tax of 8% to each
of the subtotals?
Once you’ve calculated tax, calculate the total by
adding the tax to the subtotal, and create lists to
store both the tax amounts and the totals.
Thanks in advance!
taxable_transactions.ipynb
Results Preview
NEW MESSAGE
February 8, 2022
Hi again!
I forgot to mention we need to apply different tax
rates to different locations. The list attached has the
location of each transaction. Our Sun Valley store is
taxed at 8%, Stowe at 6%, and Mammoth at 7.75%.
Can you adjust your tax calculator code to apply the
correct tax to each location?
Thanks!
taxable_transactions2.ipynb
Solution Code
NEW MESSAGE
February 8, 2022
Hi again!
I forgot to mention we need to apply different tax
rates to different locations. The list attached has the
location of each transaction. Our Sun Valley store is
taxed at 8%, Stowe at 6%, and Mammoth at 7.75%.
Can you adjust your tax calculator code to apply the
correct tax to each location?
Thanks!
taxable_transactions2.ipynb
For Loops
Nested Loops
Indicates a A logical expression that
While Loop evaluates to TRUE or FALSE
For Loops
While loops often include counters that grow with each iteration
Loop Basics • Counters help us track how many times our loop has run
• They can also serve as a backup condition to exit a loop early (more on this later!)
For Loops
While Loops
Loop Basics
The while loop here will run while
stock_portfolio is less than 1m
For Loops stock_portfolio starts at 800k and
increases by 5% of its value in each run:
Loop Basics
For Loops
While Loops
Nested Loops
A while loop that always meets its logical condition is known as an infinite loop
Loop Basics • These can be caused by incorrect logic or uncertainty in the task being solved
Nested Loops
Loop Control
Results Preview
NEW MESSAGE
February 9, 2022
Good morning,
Our investors are considering loaning us money to
purchase more skis.
Can you advise how many months of stock we have
left at the current monthly sales volume?
I would like to view the stock level at the end of
each month as well.
Thanks!
inventory_logic.ipynb
Solution Code
NEW MESSAGE
February 9, 2022
Good morning,
Our investors are considering loaning us money to
purchase more skis.
Can you advise how many months of stock we have
left at the current monthly sales volume?
I would like to view the stock level at the end of
each month as well.
Thanks!
inventory_logic.ipynb
EXAMPLE Printing items along with their sizes How does this code work?
While Loops
• The inner loop (size_list) will run
completely for each iteration of the
Nested Loops outer loop (item_list)
• In this case, the inner loop iterated
three times for each of the two
Loop Control item_list[0],
item_list[0],
size_list[0]
size_list[1]
iterations of the outer loop, for a total
item_list[0], size_list[2] of six print statements
item_list[1], size_list[0]
item_list[1], size_list[1] • NOTE: There is no limit to how many
item_list[1], size_list[2]
layers of nested loops can occur
Loop Basics
For Loops
While Loops
item_list (outer loop)
Nested Loops
0 Snowboard
1 Boots
0 small
1 medium
2 large
Loop Basics
For Loops
While Loops
item_list (outer loop)
Nested Loops
0 Snowboard
1 Boots
0 small
1 medium
2 large
Loop Basics
For Loops
While Loops
item_list (outer loop)
Nested Loops
0 Snowboard
1 Boots
0 small
1 medium
2 large
Loop Basics
For Loops
While Loops
item_list (outer loop)
Nested Loops
0 Snowboard
1 Boots
Loop Basics
For Loops
While Loops
item_list (outer loop)
Nested Loops
0 Snowboard
1 Boots
0 small
1 medium
2 large
Loop Basics
For Loops
While Loops
item_list (outer loop)
Nested Loops
0 Snowboard
1 Boots
Results Preview
NEW MESSAGE
February 9, 2022
Good morning,
I’ve attached a nested list containing the subtotals
for customers that have made multiple orders.
We need to apply a 10% discount for each of their
transactions and return the new totals in a list with
the same structure as the original.
Thanks!
multi_order_discounts.ipynb
Solution Code
NEW MESSAGE
February 9, 2022
Good morning,
I’ve attached a nested list containing the subtotals
for customers that have made multiple orders.
We need to apply a 10% discount for each of their
transactions and return the new totals in a list with
the same structure as the original.
Thanks!
multi_order_discounts.ipynb
Loop control statements help refine loop behavior and handle potential errors
Loop Basics • These are used to change the flow of loop execution based on certain conditions
For Loops
Break Continue Pass Try, Except
While Loops
Nested Loops
Stops the loop before Skips to the next Serves as a placeholder Help with error and
completion iteration in the loop for future code exception handling
Loop Control
Good for avoiding infinite loops Good for excluding values Good for avoiding run Good for resolving errors in
& exiting loops early that you don’t want to errors with incomplete a loop without stopping its
process in a loop code logic execution midway
For Loops
Loop Control
For Loops
The while loop here will run while stock_portfolio is
less than 1,000,000 (this would take 190
iterations/years)
While Loops
A break statement is used inside an IF function here
to exit the code in case the year_counter is greater
than 30
Nested Loops
Loop Control
PRO TIP: Use a counter and a
combination of IF and break to set
a max number of iterations
Triggering a continue statement will move on to the next iteration of the loop
Loop Basics • No other lines in that iteration of the loop will run
• This is often combined with logical criteria to exclude values you don’t want to process
For Loops
Loop Control
For Loops
The pass statement is used in
place of the eventual logic that will
live there, avoiding an error in the
While Loops
meantime
Nested Loops
Loop Control
The try & except statements resolve errors in a loop without stopping its execution
Loop Basics • Try: indicates the first block of code to run (which could result in an error)
• Except: indicates an optional block of code to run in case of an error in the try block
For Loops
Nested Loops
Loop Control
The try & except statements resolve errors in a loop without stopping its execution
Loop Basics • Try: indicates the first block of code to run (which could result in an error)
• Except: indicates an optional block of code to run in case of an error in the try block
For Loops
Nested Loops
Loop Control
The try & except statements resolve errors in a loop without stopping its execution
Loop Basics • Try: indicates the first block of code to run (which could result in an error)
• Except: indicates an optional block of code to run in case of an error in the try block
For Loops
While Loops
Nested Loops
The 0 price in the price_list
returns a ZeroDivisionError
Loop Control
The try & except statements resolve errors in a loop without stopping its execution
Loop Basics • Try: indicates the first block of code to run (which could result in an error)
• Except: indicates an optional block of code to run in case of an error in the try block
For Loops
Loop Control
Results Preview
NEW MESSAGE
February 9, 2022
Good morning,
We’ve made good progress on the item affordability
calculator, which really helps our customers buy with
confidence. We just need these tweaks to the logic:
• Skip processing for any ‘None’ elements
• Make sure prices stored as strings get
processed (we’ll fix the database later)
• Change 50 to a variable ‘budget’ so we can
change it based on customer input
• Clean up general ‘except’ statement
Improved_affordability_calculator.ipynb
Solution Code
NEW MESSAGE
February 9, 2022
Good morning,
We’ve made good progress on the item affordability
calculator, which really helps our customers buy with
confidence. We just need these tweaks to the logic:
• Skip processing for any ‘None’ elements
• Make sure prices stored as strings get
processed (we’ll fix the database later)
• Change 50 to a variable ‘budget’ so we can
change it based on customer input
• Clean up general ‘except’ statement
Improved_affordability_calculator.ipynb
Loop control statements help refine logic and handle potential errors
• These are key in “fool proofing” loops to avoid infinite loops, set placeholders for future logic, skip iterations,
and resolve errors
In this section we’ll cover dictionaries and sets, two iterable data types with helpful use
cases that allow for quick information retrieval and store unique values
Lists can be inefficient when you need to look up specific values, as they can
only be accessed via indexing
List Limitations
Sets
Dictionaries store key-value pairs, where keys are used to look up values
List Limitations • Keys must be unique & immutable (simple data types like strings are immutable)
• Values do not need to be unique and can be any data type
Dictionary Basics
Sets
The KeyError will be returned if a
given key is not in the dictionary
Dictionary Basics
Nested
Dictionaries
This returns the second element (index of 1) in
the list stored as the value for the key ‘skis’
Sets
Dictionary Basics
Modifying
Dictionaries
Dictionary
Methods And you can loop through* them
Nested Note that the items that are being looped
Dictionaries over are the dictionary keys
Sets
*Prior to Python 3.7, python dictionaries were not ordered – which meant the order of key-value pairs could change each time we iterated through
them This isn’t the case anymore, but in some workplaces, you may encounter an older version of Python being used *Copyright Maven Analytics, LLC
MODIFYING DICTIONARIES
Referencing a new key and assigning it a value will add a new key-value pair,
while referencing an existing key will overwrite the existing pair
List Limitations
Modifying
Dictionaries Therefore, assigning a value to a key of ‘bindings’ adds
the key-value pair to the dictionary
Dictionary
Methods
Nested
Dictionaries
Now that ‘bindings’ is a key in the dictionary, assigning a
value to a key of ‘bindings’ overwrites the value in the
dictionary for that key
Sets
Dictionary Basics
Modifying
Dictionaries
Dictionary
Methods
This has deleted the key-value pair with a key
of ‘boots’ from the dictionary
Nested
Dictionaries
Sets
Results Preview
NEW MESSAGE
February 10, 2022
Good morning,
I’m glad we brought you on – I’m passing on the
responsibility of managing birthday snacks to you.
Here are some of the changes needed:
• Can you let me know what Stuart’s snack is?
• Add me – I like ‘Cheese and Crackers’
• Nobody else wants raisins, can you change
Jerry’s snack to ‘Fig Bars’?
• Remove Sierra – she doesn’t work here
snack_dictionary.ipynb
Solution Code
NEW MESSAGE
February 10, 2022
Good morning,
I’m glad we brought you on – I’m passing on the
responsibility of managing birthday snacks to you.
Here are some of the changes needed:
• Can you let me know what Stuart’s snack is?
• Add me – I like ‘Cheese and Crackers’
• Nobody else wants raisins, can you change
Jerry’s snack to ‘Fig Bars’?
• Remove Sierra – she doesn’t work here
snack_dictionary.ipynb
Results Preview
NEW MESSAGE
February 10, 2022
Hello!
We need a quick way for our sales staff to look up the
inventory of our items (I’ve attached two lists).
Can you create a dictionary with each item as a key,
with ‘in stock’ if the corresponding inventory value is
greater than 0, and ‘sold out’ if the inventory value
equals zero?
These lists are a small sample, so make sure you aren’t
manually coding the dictionary.
inventory_status.ipynb
Results Preview
NEW MESSAGE
February 10, 2022
Hello!
We need a quick way for our sales staff to look up the
inventory of our items (I’ve attached two lists).
Can you create a dictionary with each item as a key,
with ‘in stock’ if the corresponding inventory value is
greater than 0, and ‘sold out’ if the inventory value
equals zero?
These lists are a small sample, so make sure you aren’t
manually coding the dictionary.
inventory_status.ipynb
Dictionary Basics
Returns the values from a dictionary .values()
Modifying
Dictionaries
Returns key value pairs from a dictionary as a list of tuples .items()
Dictionary
Returns a value for a given key, or an optional value if the key isn’t
Methods found .get(key, value if key not found)
Nested
Dictionaries
Appends specified key-value pairs, including entire dictionaries .update (key:value pairs)
Sets
Dictionary Basics
.keys() returns a view object that represents the keys as a list
(this is more memory efficient than creating a list)
Modifying
Dictionaries
This view object can be iterated through, which has the same
Dictionary
behavior as looping through the dictionary keys directly
Methods
Nested
Dictionaries
Dictionary Basics
.values() returns a view object that
represents the values as a list
Modifying (this is more memory efficient than
Dictionaries creating a list)
Dictionary
Methods This view object can be looped through as well
Here we’re grabbing the first element from each of
the lists returned by .values() and appending them
Nested
to a new list
Dictionaries
Sets
The .items() method returns key-value pairs from a dictionary as a list of tuples
List Limitations
Dictionary Basics
.items() returns a view object
that represents the key-value
Modifying pairs as a list of tuples
Dictionaries
Dictionary
Methods
The .items() method returns key-value pairs from a dictionary as a list of tuples
List Limitations
Dictionary Basics
.items() returns a view object
that represents the key-value
Modifying pairs as a list of tuples
Dictionaries
Dictionary
Methods
You can give these variables intuitive names,
Nested although k, v is common to represent keys
Dictionaries and values
Sets
The .get() method returns the values associated with a dictionary key
List Limitations • It won’t return a KeyError if the key isn’t found
• You can specify an optional value to return if the key is not found
Dictionary Basics
Dictionary
Methods
Dictionary Basics
.update() appends new key-value pairs to a dictionary, in
this case a single pair for a key of ‘bindings’
Modifying
Dictionaries • .update(key:value pairs)
Dictionary
Methods
Results Preview
NEW MESSAGE
February 10, 2022
…
We’re exploring the launch of our first store in
Torino, Italy and I need help building out some of the
data.
First, I need a dictionary containing the item numbers
as keys, the number of sizes for each item as values. …
european_planning.ipynb
Solution Code
NEW MESSAGE
February 10, 2022
…
We’re exploring the launch of our first store in
Torino, Italy and I need help building out some of the
data.
First, I need a dictionary containing the item numbers
as keys, the number of sizes for each item as values.
Then, I need you to add items 10010 and 10011
with size counts of 4 and 7, respectively.
Finally, pull the prices out of the product dictionary
and return a list with converted Euro pricing.
european_planning.ipynb
The zip() function combines two iterables, like lists, into a single iterator of tuples
List Limitations • first_iterable[0] gets paired with second_iterable[0], and so on
Dictionary Basics
Here, we’re zipping together two lists and returning a
zip object that contains the instructions for pairing the
Modifying ith object from each iterable
Dictionaries
Dictionary
Methods When you create a list from the zip object, you get a list
with the ith element from each iterable paired together
in a tuple
Nested
Dictionaries
Dictionary Basics
Dictionary
Methods
Note that you can only create a dictionary
from a zip object with two iterables
Nested
Dictionaries
Results Preview
NEW MESSAGE
February 10, 2022
Hi there!
We’re developing the architecture for our planned
European store.
Can you create a dictionary by combining item_ids
as keys with the lists item_names, euro_prices,
item_category, and sizes as the values?
We’ll upload this to our database shortly.
Exciting times!
european_dictionary.ipynb
Solution Code
NEW MESSAGE
February 10, 2022
Hi there!
We’re developing the architecture for our planned
European store.
Can you create a dictionary by combining item_ids
as keys with the lists item_names, euro_prices,
item_category, and sizes as the values?
We’ll upload this to our database shortly.
Exciting times!
european_dictionary.ipynb
Dictionary
Methods
Nested
Dictionaries
To access an inner dictionary, reference the
outer dictionary key
Sets
To access the values of an inner dictionary,
reference the outer dictionary key, then the
inner dictionary key of interest
Results Preview
NEW MESSAGE
February 10, 2022
Hi again!
We decided to restructure the dictionary you created
earlier into a nested dictionary with each attribute
represented by a key for fast lookup. Can you:
1. Verify the price on item 10009
2. Update the sizes for item 10009 to European
sizing (they are stored in a list)
3. Create a dictionary based on the new one that
includes item name as keys and sizes as values
modified_european_dictionary.ipynb
Solution Code
NEW MESSAGE
February 10, 2022
Hi again!
We decided to restructure the dictionary you created
earlier into a nested dictionary with each attribute
represented by a key for fast lookup. Can you:
1. Verify the price on item 10009
2. Update the sizes for item 10009 to European
sizing (they are stored in a list)
3. Create a dictionary based on the new one that
includes item name as keys and sizes as values
modified_european_dictionary.ipynb
Dictionary Basics
Sets can be created with
curly braces {}
Modifying
Dictionaries The absence of colons
differentiates them from
dictionaries
Dictionary
Methods
Dictionary Basics
Modifying
Dictionaries
Dictionary
Methods You can loop through them But you can’t index them (they are unordered)
Nested
Dictionaries
Sets
Results Preview
NEW MESSAGE
February 10, 2022
Hey,
I’m doing an analysis on product categories.
Can you collect the unique product category values
from our European dictionary??
How many unique categories are there?
Once you have that, can you check if ‘outdoor’ is in
there yet?
This will be really helpful, thanks!
product_categories.ipynb
Solution Code
NEW MESSAGE
February 10, 2022
Hey,
I’m doing an analysis on product categories.
Can you collect the unique product category values
from our European dictionary??
How many unique categories are there?
Once you have that, can you check if ‘outdoor’ is in
there yet?
This will be really helpful, thanks!
product_categories.ipynb
Dictionary
Returns values present in set 1, but not set 2 set1.difference(set2)
Methods
Sets
PRO TIP: Chain set operations to capture the relationship between three or more
sets, for example – set1.union(set2).union(set3)
List Limitations
Dictionary Basics
Union returns all unique values in both sets
Modifying
Dictionaries
All values from both sets are
returned, without duplicates
Dictionary
Methods
Nested
Dictionaries
List Limitations
Dictionary Basics
Intersection returns the values present in both sets
Modifying
Dictionaries
Only the values in both sets are
returned, without duplicates
Dictionary
Methods
Nested
Dictionaries
List Limitations
Dictionary Basics
Difference returns the values present set 1, but not set 2 (the order matters)
Modifying
Dictionaries
‘sled’ is the only value in friday_items
that is NOT in saturday_items
Dictionary
Methods
Nested
Dictionaries
If you reverse the order, the output changes – ‘goggles’ and ‘helmet’ are
in saturday_items but NOT in friday_items
Sets
Note that the subtraction sign can be used instead of difference
List Limitations
Dictionary Basics
Symmetrical difference returns all values not shared between sets
Modifying
Dictionaries
‘sled’ is only in set 1, and ‘goggles’
and ‘helmet’ are only in set 2
Dictionary
Methods
Nested
Dictionaries
Sets
1. Sets are more efficient than lists for performing membership tests
List Limitations
Dictionary Basics
Using
Lists
Modifying
Dictionaries
Dictionary Using
Methods Sets
Nested
Dictionaries
Sets Sets are implemented as hash tables, which makes looking up values extremely fast; the downside is that
they cannot preserve order (lists rely on dynamic arrays that preserve order but have slower performance)
Using
Dictionary Basics Lists
Modifying
Dictionaries
Dictionary
Methods
Nested
Dictionaries
Using
Sets
Sets
3. Set operations can find the data shared, or not shared, between items
without looping
List Limitations
Dictionary
Methods
Nested
Dictionaries
Using
Sets
Sets
Results Preview
NEW MESSAGE
February 10, 2022
Hey,
There are three lists with the customers who made
a purchase on Friday, Saturday, and Sunday.
Can you get me the set of unique customers who
made purchases on Saturday or Sunday?
Then return the customers that made purchases on
Friday AND during the weekend; we want to target
them with additional promotions.
weekend_sale_followup.ipynb
Solution Code
NEW MESSAGE
February 10, 2022
Hey,
There are three lists with the customers who made
a purchase on Friday, Saturday, and Sunday.
Can you get me the set of unique customers who
made purchases on Saturday or Sunday?
Then return the customers that made purchases on
Friday AND during the weekend; we want to target
them with additional promotions.
weekend_sale_followup.ipynb
In this section we’ll learn to write custom functions to boost efficiency, import external
functions stored in modules or packages, and write comprehensions
Packages Lambda Functions • Learn how to write lambda functions and apply
functions with map()
Function
Functions are reusable blocks of code that perform specific tasks when called
Components
• They take in data, perform a set of actions, and return a result
Defining
Functions
Variable Scope
Inputs to a function are known Functions are blocks of code Outputs are values returned
as arguments that perform a specific task by a function
Modules
Data, is some form, is usually When you use a function, it is
one of the arguments passed known as a function call, or
into a function calling a function
Packages
Other arguments might be The function itself is stored
options for processing the data somewhere else, and you are
or formatting the output ‘calling’ it by using its name
Lambda Side effects are changes or
Functions actions made by the function,
other than the output
Function
The built-in max() function works the same way (as do others like len(), sum(), etc.)
Components
Variable Scope
Modules
Packages
Possible arguments: Identifies the largest value The largest value in the
• A single iterable in the argument(s) provided argument(s)
Lambda
Functions • Multiple objects
Comprehensions
None
*Copyright Maven Analytics, LLC
THE ANATOMY OF MAX
Function
The built-in max() function works the same way (as do others like len(), sum(), etc.)
Components
Defining
Functions
Variable Scope
Modules
Packages
price_list Identifies the largest value 99.99
in price_list
Lambda
Functions
Comprehensions
None
*Copyright Maven Analytics, LLC
DEFINING A FUNCTION
Function
Components
def function_name(arguments):
Defining
Functions
Variable Scope
Modules Indicates you’re defining a An intuitive name to Variable names for the function
new function call you function by inputs, separated by commas
Examples:
Packages • avg
• usd_converter
Lambda
Functions
Functions have the same naming rules and best practices as variables – use ‘snake_case’!
Comprehensions
Function
Components
def function_name(arguments):
Defining
Functions do this
Variable Scope
Lambda
Functions
Comprehensions
Function
Components
def function_name(arguments):
Defining
Functions do this
Variable Scope
return output
Lambda
Functions
Comprehensions
Packages
Lambda
Note that we don’t need a code block
Functions
before return, here we’re combining
strings in the return statement
Comprehensions
Function
You should take time to define a function when:
Components
Packages
PRO TIP: There are no hard and fast rules, but in data analysis you’ll often have a similar workflow
Lambda for different projects – by taking the time to package pieces of your data cleaning or analysis
Functions workflow into functions, you are saving your future self (and your colleagues’) time
Comprehensions
Function
You can create a docstring for your function
Components
• This is used to embed text describing its arguments and the actions it performs
Defining
Functions Use triple quotes inside the function to create its docstring Use ‘?’ to retrieve the docstring, just like with built-in functions
Variable Scope
Modules
Packages
Lambda
Functions
PRO TIP: Take time to create a docstring for your function, especially if you plan to share it with others.
What’s the point in creating reusable code if you need to read all of it to understand how to use it?
Comprehensions
Results Preview
NEW MESSAGE
February 11, 2022
Good morning,
We want to expand the work you’ve done on sales tax
to all our stores, which requires a function to account
for changes to taxes or expansion into new states.
Write a function that takes a given subtotal and tax
rate, and returns the total amount owed (subtotal plus
tax).
Thanks in advance!
tax_calculator_function.ipynb
Solution Code
NEW MESSAGE
February 11, 2022
Good morning,
We want to expand the work you’ve done on sales tax
to all our stores, which requires a function to account
for changes to taxes or expansion into new states.
Write a function that takes a given subtotal and tax
rate, and returns the total amount owed (subtotal plus
tax).
Thanks in advance!
tax_calculator_function.ipynb
Function
There are several types of arguments that can be passed on to a function:
Components
• Positional arguments are passed in the order they were defined in the function
Defining
Functions
• Keyword arguments are passed in any order by using the argument’s name
Variable Scope
• Default arguments pass a preset value if nothing is passed in the function call
Modules
Comprehensions
Function
Positional arguments are passed in the order they were defined in the function
Components
Variable Scope
Therefore, changing the order of the inputs
changes the output
Modules
Packages
Lambda
Functions
Comprehensions
Function
Keyword arguments are passed in any order by using the argument’s name
Components
Defining
Functions
Variable Scope
By specifying the value to pass for each
argument, the order no longer matters
Modules
Lambda
Functions Positional arguments can be
followed by keyword arguments
(the first argument is typically
Comprehensions reserved for primary input data)
Function
Default arguments pass a preset value if nothing is passed in the function call
Components
Packages
Default arguments must come after
arguments without default values
Lambda
Functions
Comprehensions
Function
*args arguments pass any number of positional arguments as tuples
Components
Modules
Comprehensions
Function
**kwargs arguments pass any number of keyword arguments as dictionaries
Components
Using ‘**’ before the argument name allows users to enter any
Defining number of keyword arguments for the function to concatenate
Functions
Note that since the arguments are passed as dictionaries, you
need to use the .values() method to loop through them
Variable Scope
Packages
The exponentiator function has three arguments:
constant, base, and exponent
Function
Functions can return multiple values
Components
Defining
Functions
The values to return must be
separated by commas
Variable Scope
This returns a tuple of the
specified values
Modules
Packages
You can unpack the tuple
into variables during the
function call
Lambda
Functions
The variable ‘sentence’ is assigned to the first
element returned in the tuple, so if the order was
switched, it would store ‘you?’
Comprehensions
Function
Functions can return multiple values as other types of iterables as well
Components
Defining
Functions
Modules
Packages
Comprehensions
Function
The variable scope is the region of the code where the variable was assigned
Components
Comprehensions
Function
You can change variable scope by using the global keyword
Components
Variable Scope
Modules
Packages
Lambda
Functions
Comprehensions
Function
You can change variable scope by using the global keyword
Components
Variable Scope
Modules
Packages
PRO TIP: While it might be tempting, declaring global variables within a function is considered
Lambda bad practice in most cases – imagine if you borrowed this code and it overwrote an important
Functions variable! Instead, use ‘return’ to deliver the values you want and assign them to local variables
Comprehensions
Function
To save your functions, create a module in Jupyter by using the %%writefile
Components magic command and the .py extension
Defining This creates a Python module that you can import functions from
Functions
• Follow %%writefile with the name of the file and the .py extension
• By default, the .py file is stored in the same folder as the notebook
Variable Scope
• You can share functions easily by sending this file to a friend or colleague!
Modules
Packages
Comprehensions
Function
To import saved functions, you can either import the entire module or import
Components specific functions from the module
Defining
Functions import module
reads in external Python modules
Variable Scope If you import the entire module, you need to reference it when
calling its functions, in the form of module.function()
Modules
Packages
from module import function
imports specific functions from modules
Results Preview
NEW MESSAGE
February 11, 2022
Hey again,
Can you make the following changes to our sales tax
calculator?
1. Since we’ve created this calculator for Stowe
employees, set the default sales tax to 6%
2. We want the function to return subtotal, tax
and sales tax in a list
3. Save this function to tax_calculator.py
Thanks!
modified_tax_calculator.ipynb
Solution Code
NEW MESSAGE
February 11, 2022
Hey again,
Can you make the following changes to our sales tax
calculator?
1. Since we’ve created this calculator for Stowe
employees, set the default sales tax to 6%
2. We want the function to return subtotal, tax
and sales tax in a list
3. Save this function to tax_calculator.py
Thanks!
modified_tax_calculator.ipynb
Results Preview
NEW MESSAGE
February 11, 2022
Hey again,
Now that you’ve updated and saved the function, can
you import it, pass a list of transactions through, and
create a list containing the transaction information for
each?
Once you’ve done that, I’d like you to create a
dictionary with the supplied customer IDs as keys and
the transaction information as values.
Thanks!
applied_tax_calculator.ipynb
Solution Code
NEW MESSAGE
February 11, 2022
Hey again,
Now that you’ve updated and saved the function, can
you import it, pass a list of transactions through, and
create a list containing the transaction information for
each?
Once you’ve done that, I’d like you to create a
dictionary with the supplied customer IDs as keys and
the transaction information as values.
Thanks!
applied_tax_calculator.ipynb
Function
The same method used to import your own modules can be used to import
Components external modules, packages, and libraries
• Modules are individual .py files
Defining
Functions • Packages are collections of modules
• Libraries are collections of packages (library and package are often used interchangeably)
Variable Scope
Use the dir() function to view the contents for any of the above
Modules
• This is showing the directory for the saved_functions module
• Modules have many attributes associated with them that the functions will follow
Packages • ‘ __file__’ is the name of the .py file
Lambda
Functions
These are the two functions inside the module
Comprehensions
EXAMPLE Importing the math package, which contains handy mathematical functions
Function
Components
Modules
It’s helpful to look up the official documentation, which will usually
give a helpful overview of the package and its contents
docs.python.org/3/library/math.html
Packages
Lambda
Functions
PRO TIP: Import packages with an alias using the as
keyword – this saves keystrokes while still explicitly
referencing the package to help avoid naming conflicts
Comprehensions
Function
Importing external functions can lead to naming conflicts
Components
Defining
Functions
Packages
Lambda
Functions
To avoid conflicts, refer to the package
name or an alias with imported functions
Comprehensions
Function
While many come preinstalled, you may need to install a package yourself
Components
Modules
Comprehensions
Function
Use Anaconda to review all installed packages and their versions
Components
Variable Scope
Packages
Function
Python has incredible packages for data analysis beyond math and openpyxl
Components
Here are some to explore further:
Defining
Functions
Variable Scope
Modules
Packages
Lambda
Functions
Comprehensions
Function
The map() function is an efficient way to apply a function to all items in an iterable
Components
• map(function, iterable)
Defining
Functions
Variable Scope
The map function returns a map object –
which saves memory until we’ve told Python
Modules what to do with the object
Packages
You can convert the map object into a list
or other iterable
Lambda
Functions
Comprehensions
Results Preview
NEW MESSAGE
February 11, 2022
Hey again,
We’re really making some great progress on
implementing Python – can you import the tax
calculator and apply it to the newest list of
transactions?
Don’t use a for loop!
Thanks!
mapping_the_calculator.ipynb
Solution Code
NEW MESSAGE
February 11, 2022
Hey again,
We’re really making some great progress on
implementing Python – can you import the tax
calculator and apply it to the newest list of
transactions?
Don’t use a for loop!
Thanks!
mapping_the_calculator.ipynb
Function
Lambda functions are single line, anonymous functions that are only used briefly
Components
• lambda arguments: expression
Defining
Functions Lambda functions can be called on
a single value, but typically aren’t
used for this
Variable Scope
Comprehensions
Results Preview
NEW MESSAGE
February 11, 2022
Hey,
We need to apply a 10% discount for customers
who purchased more than $500 worth of product –
they’re starting to complain it hasn’t been applied.
This is a one-time promotion, so can you code up
something quick?
We won’t reuse it.
Thanks!
discount_orders.ipynb
Solution Code
NEW MESSAGE
February 11, 2022
Hey,
We need to apply a 10% discount for customers
who purchased more than $500 worth of product –
they’re starting to complain it hasn’t been applied.
This is a one-time promotion, so can you code up
something quick?
We won’t reuse it.
Thanks!
discount_orders.ipynb
Function
Comprehensions can generate sequences from other sequences
Components
Syntax:
Defining
Functions
Variable Scope EXAMPLE Creating a list of Euro prices from USD prices
Before, you needed a for loop to create the new list Now, you can use comprehensions to do this with a single line of code
Modules
Packages
Lambda
Functions
Results Preview
NEW MESSAGE
February 11, 2022
Hi there,
I’m working on some numbers for our European
expansion. Can you help me calculate the combined
cost of all of our European items?
The data is stored in the euro_data dictionary.
Thanks!
cost_of_european_items.ipynb
Solution Code
NEW MESSAGE
February 11, 2022
Hi there,
I’m working on some numbers for our European
expansion. Can you help me calculate the combined
cost of all of our European items?
The data is stored in the euro_data dictionary.
Thanks!
cost_of_european_items.ipynb
Function
Comprehensions can also create dictionaries from other iterables
Components
Syntax:
Defining
Functions
These can be expressions (including function calls!)
Variable Scope
EXAMPLE Creating a dictionary of inventory costs per item (stock quantity * price)
Lambda
Functions
You can still use conditional logic!
Comprehensions
Results Preview
NEW MESSAGE
February 11, 2022
Hey there,
We’re getting close to having a final ETL process for
our European dictionary. Can you create a function
that applies our tax calculator to a list of subtotals
and matches the output up with customer_IDs?
Store them in a dictionary, with customer IDs as
keys, and the transactions as values.
Thanks – we’re getting close to implementing this!
final_tax_calculator.ipynb
Solution Code
NEW MESSAGE
February 11, 2022
Hey there,
We’re getting close to having a final ETL process for
our European dictionary. Can you create a function
that applies our tax calculator to a list of subtotals
and matches the output up with customer_IDs?
Store them in a dictionary, with customer IDs as
keys, and the transactions as values.
Thanks – we’re getting close to implementing this!
final_tax_calculator.ipynb
Function
Comprehensions, like map(), can apply functions to an entire sequence
Components
Lambda
Functions
Comprehensions
Function
Comprehensions, like map(), can apply functions to an entire sequence
Components
Packages
Lambda In general, both methods provide an efficient way to apply a function to a list – Comprehensions are usually preferred,
Functions as they are more efficient and highly readable, but there will be instances when using map with lambda is preferred
(like manipulating a Pandas Column)
You may prefer not to use comprehensions for particularly complex logic (nested loops, multiple sequences, lots of
Comprehensions conditions), but for most use cases comprehensions are a best practice for creating new sequences based off others.
Functions are reusable blocks of code that make us more efficient analysts
• If you find yourself writing the same code over and over again, consider making it a function
In this section we’ll import the openpyxl package and manipulate data from Excel
sheets by using the Python skills learned throughout the course
Looping Through Cells Modifying Cells • Loop through cell ranges and modify cell values
The openpyxl package is designed for reading and writing Excel files
The openpyxl Without ever needing to open Excel itself, you can use openpyxl to:
Package
• Create, modify, or delete workbooks, worksheets, rows, or columns
Navigating • Leverage custom Python functions or Excel formulas (yes, really!)
Workbooks
• Automate Excel chart creation
Iterating Through • … or do almost anything else that can be done in Excel natively
Cells
openpyxl should be installed in Anaconda already, but if it isn’t you can install it like you would any other package
Orders_info
Item_info
The openpyxl
Package
Navigating
Workbooks
Just supply a file name!*
Iterating Through
Cells workbook.sheetnames returns the worksheet names in a workbook
* As long as the Excel workbook is in the same folder as your Jupyter notebook *Copyright Maven Analytics, LLC
NAVIGATING WORKSHEETS
Navigating
Workbooks The first sheet (value of 0) is active by default, but you can
change it by assigning the sheet’s index to workbook.active
Iterating Through
Cells
Modifying Cells
Sheets can also be referenced by name (like dictionary keys)
You can navigate cells by using ‘A1’ style coordinates, or Python-esque indices
The openpyxl sheet['coordinate'] returns the specified cell object, and cell.value returns the cell’s contents
Package
Navigating
Workbooks
Modifying Cells
sheet.cell(row= , column= ) returns cell objects as well
Results Preview
NEW MESSAGE
February 12, 2022
Hey there, we’ve just run our annual Black Friday Sale,
and there have been issues with the data. Most of our
data team is skiing this weekend, so we need your
help.
A customer mentioned they weren’t charged sales tax
and have graciously reached out to pay it.
Can you calculate the sales tax (8%) and total for
customer C00003? It should be in row 10.
Thanks!
excel_data_sales_tax.ipynb
Solution Code
NEW MESSAGE
February 12, 2022
Hey there, we’ve just run our annual Black Friday Sale,
and there have been issues with the data. Most of our
data team is skiing this weekend, so we need your
help.
A customer mentioned they weren’t charged sales tax
and have graciously reached out to pay it.
Can you calculate the sales tax (8%) and total for
customer C00003? It should be in row 10.
Thanks!
excel_data_sales_tax.ipynb
Looping Through
Cells
Modifying Cells
Excel columns usually contain data fields, while rows contain individual records
To loop through cells in a column, you need to move row by row in that column
The openpyxl
Package
Navigating
Workbooks
How does this code work?
print('B1', items['B1'].value)
• The for loop is iterating
Looping Through print('B2', items['B2'].value) through each row in a
Cells specified range
print('B3', items['B3'].value)
You can write data to a cell by assigning a value to it using the cell’s coordinates
The openpyxl
Package
Cell ‘F1’ starts with no data, and then a
value of ‘Euro Price’ is assigned to it
Navigating
Workbooks
Looping Through
Cells
Modifying Cells
You can write data to a column by looping through its rows and assigning values
The openpyxl
Package Each row in column ‘F’ is now equal to the matching
value in column ‘C’ multiplied by .88
Note that the range is starting at 2, since the first
Navigating row is reserved for the column header
Workbooks
Looping Through
Cells
You can reference all the cells in a column!
Modifying Cells
Use enumerate’s start argument to start the index at 1, rather than the
default of 0, to align with Excel row numbers
Results Preview
NEW MESSAGE
February 12, 2022
Hi again!
In addition to a planned EU expansion this year, we’re
considering expanding into Japan and the UK next
year.
Since we’re going to do this a few times, can you
create a currency converter function?
Once we have that, create a column for ‘GBP Price’
and ‘JPY Price’, to store Pound and Yen prices.
The notebook has conversion rates and more details.
pound_and_yen_pricing.ipynb
Solution Code
NEW MESSAGE
February 12, 2022
Hi again!
In addition to a planned EU expansion this year, we’re
considering expanding into Japan and the UK next
year.
Since we’re going to do this a few times, can you JPY Price with enumerate:
create a currency converter function?
Once we have that, create a column for ‘GBP Price’
and ‘JPY Price’, to store Pound and Yen prices.
The notebook has conversion rates and more details.
pound_and_yen_pricing.ipynb
The openpyxl sheet.insert_cols(idx=index) inserts a column in the specified sheet and index
Package
Looping Through
Cells After inserting a column at index 5 (column ‘E’), and
assigning ‘E1’ a value of ‘Euro Price’, note that
‘Available Sizes’ was shifted right to ‘F1’
Modifying Cells
The openpyxl sheet.delete_cols(idx=index) deletes the column at the specified sheet and index
Package
Looping Through
Cells After deleting the column at index 5 (column ‘E’),
‘Available Sizes’ was moved back to ‘E1’ from ‘F1’
Modifying Cells
The openpyxl
Package
Navigating
Workbooks
Looping Through
Cells
Modifying Cells
WARNING
This will replace any existing files
with the same name in your folder
If you overwrite your input excel
sheet, you could lose raw data that
could be impossible to recover
Be careful!
You now have a workflow that reads in an Excel workbook, creates a ‘Euro
Price’ column based on a given exchange rate, and saves it back out
The openpyxl
Package
Import openpyxl
Navigating
Workbooks Read in the Excel workbook
Modifying Cells
Set the exchange rate
Orders_Info
Key Objectives
NEW MESSAGE
February 13, 2022
1. Read in data from an Excel workbook
From: Sally Snow (Ski Shop Manager)
2. Define a function that prints cell contents
Subject: Black Friday Data
3. Create a dictionary using a comprehension and string
methods
Hi again, I have a BIG final ask for you!
4. Use for loops to manipulate Excel data
Our Excel expert has been skiing for 3 months now, and
we need really to analyze our Black Friday sales data! 5. Import and call a previously saved function
maven_ski_shop_data.xlsx
maven_ski_shop_analysis.ipynb
Key Objectives
NEW MESSAGE
February 13, 2022
1. Define a function that sums Excel columns, leveraging a
From: Sally Snow (Ski Shop Manager) list comprehension
Subject: RE: Black Friday Data 2. Apply numerical functions to calculate KPIs
maven_ski_shop_analysis.ipynb