0% found this document useful (0 votes)
0 views77 pages

Python Mod1

The document outlines a course on Python for Data Analytics, focusing on programming fundamentals and the integration of generative AI tools. It emphasizes the importance of coding skills for effective collaboration with large language models (LLMs) and covers key programming concepts such as data types, variables, and functions. The course aims to equip learners with the ability to automate data analysis tasks, enhance efficiency, and create customized visualizations.

Uploaded by

ptdd07082003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views77 pages

Python Mod1

The document outlines a course on Python for Data Analytics, focusing on programming fundamentals and the integration of generative AI tools. It emphasizes the importance of coding skills for effective collaboration with large language models (LLMs) and covers key programming concepts such as data types, variables, and functions. The course aims to equip learners with the ability to automate data analysis tasks, enhance efficiency, and create customized visualizations.

Uploaded by

ptdd07082003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python for Data Analytics

Module 1: Programming
fundamentals for data analytics
Python for Data Analytics

Welcome to Python for


Data Analytics
Python for Data Analytics

Generative AI in this course


In this course, you’ll…
💡 Learn how to use LLMs to:
● Find and fix code errors
● Discover new Python features
● Customize data visualizations
● Interpret inferential statistics
● And more!

Sean Barnes
Our philosophy
💡 LLMs are: 📚 In this course, you’ll:
● A complement to skills, not a ● Learn fundamentals of coding and
replacement LLM collaboration
● Excellent coding companions for ● Build code interpretation skills
coding and fix bugs ● Develop intuition about what tasks
LLMs excel at and can go wrong
🧠 You’ll get the most from LLMs if you ● Use Coursera’s built-in lab chatbot
know how to code
to completement code writing

Sean Barnes
LLMs in this course
● New models and features
🗓 Demonstrates the most up-to-date constantly released
capabilities as of 2025

🌲 Evergreen principles: Changes you should expect

● How to think about and use ● More advanced and specialized


generative AI regardless of product features
● Cheaper tools
🧠 Develop a mindset of iteration and ● Faster tools
skepticism
● Higher quality outputs overall

Sean Barnes
LLM options

❌ You won’t need to purchase any ✅ You’ll develop confidence


additional products experimenting and selecting tools

❌ This course does not ✅ You’ll see several tools throughout


recommended any single tool the modules

✅ You’ll learn core principles to work


with LLMs: free and paid, now and
in the future

Sean Barnes
Programming fundamentals
for data analytics

Module 1 introduction
Module 1 outline Library revenue Safety inspection scores

Fundamentals
Role of programming Control flow
of Python

Compare Python to Conditionals


Data types
spreadsheets

Use Jupyter
notebook Variables Loops
environment

Lists
Modify your code
Functions using an LLM

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Computer programming
What is computer programming?
🧠 Your role:
● Tell computers very precisely what
you want them to do

💻 Computer’s role:
● Carry out commands to the letter
● If you don’t tell them exactly how to do
what you want, they might:
⛔ Make a mistake
⛔ Only do some of your commands

Sean
SeanBarnes
Barnes
Why computer programming?
● Automates thinking work like:
● Math
● Data analysis

● Computers excel in:


● Efficiency
● Traceability
Adds up all figures at
● Repeatability
the end of the month
to create sales report

Intern

Sean
SeanBarnes
Barnes
Efficiency Compute average
Completing tasks with minimal time daily sales for:
and resources
A particular item
📱 Intern: 20 seconds
1 💻 Python: < 0.001 seconds

200 products
📱 Intern: > 1 hour

200 💻 Python: < 0.5 seconds

100 stores
📱 Intern: > 2 weeks

000 💻 Python: A few seconds


2 0 ,
“at scale”

Sean
SeanBarnes
Barnes
Traceability Your averages look too low:
The ability to track how tasks are completed.

Steps might be:

1. Opening dataset of sales [Link] [Link]

2. Selecting rows for each product Intern averages suspiciously low:


3. Averaging the sales ❌ Might not have record of what
4. Saving or displaying that average they did
❌ Probably have to redo the
analysis
✅ When something goes wrong, you can
quickly identify & fix it

Sean
SeanBarnes
Barnes
Repeatability
Doing the same task in the same way many times.

Easy to repeat the same


steps over and over again

For next year’s analysis:

Change the filename:

● Intern might teach how she


did the analysis before
[Link]
● They may not execute it the
Rerun the code same way

Sean
SeanBarnes
Barnes
Quick note about Python

● It has a broad user base: ● It has a great readability

󰟜 Individual programmers ⏰ Often faster to write compared


with many other languages
🏢 Companies
● It has some great technical
● It has a great support for: features

📊 Visualizations
⚙ Automation
🌐 Web development

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Navigating the Jupyter


notebook environment
Programming fundamentals
for data analytics

Input, processing, output


Input, processing, output Type of data Numerical representation

● Computer programs basically do Number 1 2 3 4 5 6 7 8 9 0


math
104 101 108 108 111
Text H e l l o
● Do math on numbers that represent
data, whatever the format:
Digital image = rgb(151,175,72)
Change a color image to
black and white
Video
Calculate confidence
interval for daily sales
New
Determine whether Yelp Information Math
information
review is positive or negative

Sean
SeanBarnes
Barnes
What code does
🔢 Numbers 📁 Folder of images Program needs to expect
Input
📄 Dataset 📊 Something else data in that format

📥 Run code on the input


Processing 👣 Execute each step by step

🖥 Displaying something on screen


Output 💾 Altering or saving a new file
📄 Sending results to another program or computer

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Python or a spreadsheet?
Interface
Spreadsheets
● Manually managing the data
● Easily format data with colors and fonts
● Store data in one format

Python import pandas as pd


● Processing happens in background
import [Link] as plt

● Inspect data, but won’t be managing


# Load the CSV file
it as directly
file_path = '[Link]'
● Format the markdown
df = pd.read_csv(file_path)

Sean
SeanBarnes
Barnes
Interface
Spreadsheets
● Manually managing the data
● Easily format data with colors and fonts
● Store data in one format

Python
● Processing happens in background
● Inspect data, but won’t be managing
it as directly
● Format the markdown

Sean
SeanBarnes
Barnes
Interface
Spreadsheets
● Manually managing the data
● Easily format data with colors and fonts
● Stores data in one format

Python
● Processing happens in background
● Inspect data, but won’t be managing
it as directly
● Format the markdown

Sean
SeanBarnes
Barnes
Complexity of analysis
Spreadsheets
● Sorting
● Filtering
● Hypothesis testing

Returns the p-value


Python
You could also manually calculate:
● Expands those capabilities
● Perform sophisticated statistics
● Test statistic
● Degrees of freedom
● Run simulations
● Confidence interval
● Create machine learning models
● More custom analysis t_stat, p_value = ttest_ind(sample1, sample2)

Sean
SeanBarnes
Barnes
Visualization
❌ Not possible to create
boxplot in Google Sheets
Spreadsheets
● Sorting
● Filtering
● Hypothesis testing
Source: Google Docs Editor Help

Python
● Expands those capabilities ✅ Customize every
● Perform sophisticated statistics aspect of plot
✅ Apply unique color
● Run simulations
schemes
● Create machine learning models ✅ Create several plots at
● A more custom analysis once

● Create box plots

Sean
SeanBarnes
Barnes
Traceability & Repeatability
?
Spreadsheets
● You can use version history raw_data.csv organized_data.csv

Python ⭐ 1. Import data


2. Filter out rows with missing price
● Each step completed line by line
3. Add new column to track discount amount
● Make small changes to produce
many similar outputs quickly
15 of sales data sets Dataset with
● Running the same analysis formatted in same way 20 features
on similar data
● Producing many analyses Change 1 line of code, 95% confidence intervals
or visualizations then run same analyses for each feature

Sean
SeanBarnes
Barnes
Summary

Spreadsheets Python
If you’re looking to: If you’re looking for:

● Quickly put together an analysis, ● A highly efficient analysis at scale


especially at a small scale with larger datasets
● Be able to see the full the dataset ● Complex or customized analysis or
visualizations
● You’re not concerned with
traceability or repeatability ● A traceable process that makes it
easy to repeat tasks across
● You want a lot of formatting and
different datasets or features
customization options

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Types and expressions


Data types
Determines what kinds of operations you can perform on the data

Integers Floats Strings


● Whole counting numbers ● Real numbers including a ● Text
● Negatives decimal point ● Must be contained inside
● Can be negative quotation marks
-1
0.0 "oranges and apples"
0
1.7 "(づ ◕‿◕ )づ"
-177
-200.03

Integer 400/2 String "400"/2


200 Error!

Sean
SeanBarnes
Barnes
Data types in action

In this lesson, you’ll work with: 📍 Connecticut, USA

⬜ A real world data set of yearly


library data for one library

You
Data Analyst

Sean
SeanBarnes
Barnes
Summary

Integers Floats Strings


Whole counting numbers Numbers with decimals Text

-1 0.0 "oranges and apples"


0 1.7 "(づ ◕‿◕ )づ"
4000 -200.03

Can be used in mathematical expressions as


you would in a spreadsheet

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Printing and commenting


Comments

On their own line # This is a comment


print("Hello, it's me")

# Total coffee cups in a year


End of a line that
print("Cups per year:") # Display message
has commands
print(1.5 * 365)

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Storing information:
variables
Variables Create a variable:

income_2023 = 830696
💾 Used to store values you expect
to change or reuse
1⃣ Declare 2⃣ Assign
only once
📦 A box that can store some
information

830696
830000 Overwriting:
income_2023
income_2023 = 830000

830000
830696
● Don’t need the previous value
income_2023
● Otherwise, create a new variable

Sean
SeanBarnes
Barnes
Variables

income_2023 = 830696
print(income_2023
print(35602)
830696 - 794398)

35602

830696
income_2023

803696
income_2023

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Debugging with variables


Variable naming
● Stick with:

● Letters uppercase or lowercase INCOME = 803696


income = 803696
● Numbers
income2023 = 803696
● Underscores income_2023 = 803696

● Start your variable with a letter

● Keep in mind that variables are income_2023 = 803696


case sensitive Income_2023 = 803696

Sean
SeanBarnes
Barnes
The coder’s mindset
💪 Be resilient

🔍 Treat errors as part of the process

Key strategies:

🔄 Try code changes

💬 Ask an LLM

🌐 Search the web

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Creating lists
Lists [737487, 740967, 756155, 763415, 830696]

● A type of sequence
● A collection of values that has an order
incomes
● Values inside a list are also called items

Declares a variable
and assigns value Brackets create a list

Plural incomes = [737487, 740967, 756155, 763415, 830696]

Individual values separated by commas

One value income_2023 = 830696

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

List operations
Recap length of list - 1
0 1 2 3 4

● Lists are zero-indexed incomes = [737487, 740967, 756155, 763415, 830696]

Name Index

● To access items: incomes[4]

Name for 3rd item New value

● To update an item: incomes[2] = 830000

Dot allows you to perform an action

● To append an item: [Link](837404)

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Taking action:
calling functions
Functions
Input you provide Processes it Produce output

Values or Processes Displays to


print("Income from 2023:")
expressions input the screen

incomes = [737487, 740967, 756155] Adds


A list Total
sum(incomes) everything

List & item Add item New,


[Link](837404) to append to list longer list

Sean
SeanBarnes
Barnes
Functions
Inputs to a function: arguments

sum() .append()

sum(incomes) [Link](837404)

List variable Item to


Inputs
Name of the name Name of the append
function function

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

State
State
📸 Computer's "state" is like a
snapshot of all current info

💾 Until you close notebook or


restart kernel, variables are
saved

📤 Helps focus on output of


program, rather than steps

Sean
SeanBarnes
Barnes
Hidden state from helper_functions import get_list
incomes = get_list("Total Income")
print(incomes)
✅ 100% reliability: don’t always
need to see intermediate steps
● Can’t actually see what values are in list
✅ Makes calculations fasts ● Calculate without seeing data itself:
○ max()
○ min()
Problems:
○ sum() / len()
⛔ Think variable has a value, but
it has a different one ● Use print() to:

⛔ A dataset loaded correctly ○ Make sure data is loaded


when it didn’t ○ Form intuition about what values
should look like

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Control flow
Control flow Sequential control flow
● Order in which individual lines of ● Default way code runs
code are executed
● Lines of code will execute in order
● Determines the path computer
takes through the code

● Four main types: Conditional control flow


⬜ Sequential ● Executes certain lines of code
only if a condition is true
⬜ Conditional
● Creates branching paths
⬜ Repetitive
● Code goes down one path, not
⬜ Function calls both

Sean
SeanBarnes
Barnes
Conditional control flow
● Dataset: Libraries from Start
all around the world

● Goal: Count number of


libraries in Brazil 󰎙
Yes No
“Country” is Brazil?
COUNTIF

SUMIF
Add 1 to total Nothing

AVERAGEIF There are over 75,000 libraries in Brazil! 🤯

Sean
SeanBarnes
Barnes
Repetitive control flow
● Data: A 100 items in a list items = [item0, item1, item2,..., item99]
item[0] = item[0] / 2
● Goal: Divide them all by 2 item[1] = item[1] / 2
item[2] = item[2] / 2

● Allows you to write a few lines of item[99] = item[99] / 2
code that repeat an action

● “Print all the numbers


between 1 and 100” ARRAYFORMULA

● “Add each item in this ● Repeat the operation for each


list to my total variable” cell with just one formula

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Comparison
Yes No
Scenario 90 or above

Inspection Yes No

A 80 to 89

Inspection Yes No
Give score from 0 to 100 based on
B
● 70 to 79
its sanitation
● Raw score are analyzed to: Inspection

🥘 Better understand how


restaurants perform overall C
😷 Inform consumers about
health and safety violations

Sean
SeanBarnes
Barnes
Comparison operators
● Answers question about values
>= ● Two possible answers: True False Type: Boolean

● Look exactly the same as


in spreadsheets < <= > >=
● Compute a Boolean value Less than Less than Greater than Greater than
based on the inequality or equal to or equal to

● = is taken by the
assignment operator == !=
● If you’re checking for Equals Not equals
equality, always write ==

Sean
SeanBarnes
Barnes
Comparison operators The
Beverly Pasta Melrose Modern Alfred’s
Falafel Roma Shrimp Eats Coffee
A B C Failure

90-100 80-89 70-79 0-69


scores = [ 96, 91, 79, 93, 86 ]

Question Inequality

Did Beverly Falafel score an A? scores[0] >= 90

Did Modern Eats fail their inspection? scores[3] < 70 or scores[3] <= 69

Did Pasta Roma score exactly 90? scores[1] == 90

Sean
SeanBarnes
Barnes
Knowledge check
1. Which of these expressions answers the question
“Did Beverly Falafel score a 100?”?

scores[0] >= 100

scores[0] == 100

scores[0] > 99

scores[0] < 101

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Branching code: if & else


Recall
Start
● Task: Assign a grade based on
the restaurant’s score

scores[0] >= 90 Yes No


Score is 90 or above

● To take a particular action based


on decision, use an if statement:
Inspection Inspection
○ Print whether grade is A
○ Or not an A
A A

Sean
SeanBarnes
Barnes
Score: 100 Score: 73

print("Start
bf_score = 96of code") # 1 print("Start
bf_score = 96of code") # 1
a =score
if 90 #>=minimum
90: score for an A a =score
if 90 #>=minimum
90: score for an A
print("A") # 2 print("A") # 2
# minimum score for an A # minimum score for an A
else: else:
print(bf_score >= a) print(bf_score >= a)
print("Less than A") # 3 print("Less than A") # 3
print("End of code") # 4 print("End of code") # 4

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Repeating actions: for loops


● Creates new variable of type list scores = [96, 91, 79, 93, 86]

print("Starting loop")

● Creates a loop for score in scores: for loop


● for keyword - Indicates to repeat block if score >= a:
of code for a certain number of times
print("A")
● Creates a new variable score else:
○ Changes each time the loop runs print("Less than A")
○ Takes on each values in scores in turn print("Done with the loop!")
● Run same lines of code for each item in list

● Once the loop reaches last item:


○ Loop stops
○ Moves onto next line of code

Sean
SeanBarnes
Barnes
Getting Started with Python

Indentation
Indentation
Tells Python which lines belong with
which control structure scores = [96, 91, 79, 93, 86]
Outside
print("Starting loop")
if score >= A:
print("You got an A!") for score in scores:

if score >= a:
for score in scores: print("A")
Inside
print(score)
else:

● Colon indicates Python should print("Less than A")


expect a block of lines
Outside print("Done with the loop!")
● A group of lines that belong
with that if statement or loop

Sean
SeanBarnes
Barnes
Recap: Indentation
● Conditionals and loops needs an if score >= A:
indented block of code print("You got an A!")
● Python will throw an error if you don’t
include it for score in scores:
print(score)
● Indentation sets aside the code you
want to execute when:
● Can cause silent errors:
✅ Condition is true
💬 Try debugging with LLM
🔄 Inside the loop
🖨 Print statements

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Branching code: elif


elif statement
Start
One of these branches
grades = [] will execute for each
True False score in the list scores
for score in scores: score >= A
if score >= A:
[Link]("A")
Append True False
elif score >= B:
“A” score >= B
[Link]("B")
elif score >= C:
Append True False
[Link]("C") “B” score >= C
else:
[Link]("Failed")
Append Append
“C” “Failed”

Sean
SeanBarnes
Barnes
elif statement if score >= A:

● You can create as many branches as print("You got an A!")


you need
elif:score >= 80:
elif

● Always have one if statement print("You got a B.")

● Optionally an else statement elif:score >= 70:


elif

● Add elifs in the middle print("You got a C.")

else:score >= 60:


elif
● Each condition implies the previous
one was False. print("You got a D.")

● Avoid checking both high and else:


low boundaries print("You got an F.")

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Repeating actions: range


Access items in list
1. Using their index: 3. Loop over numbers by:

scores = [96, 91, 79, 93, 86, …] ● Getting a list of numbers


item[0] # 1st item ● Use each number to access
item[100] # 101st item multiple lists at once
● Access same position in
2. Looping through single list multiple lists

scores = [96, 91, 79, 93, 86, …]


for score in scores:
print(score)

Sean
SeanBarnes
Barnes
Recap: range If you need to:
1. range()
⬜ Access to a single list:
Creates list of numbers, from 0 to
number you specify Use for score in scores

scores = [96, 91, 79, 93, 86, …] ⬜ More flexibility or access to


for i in range(len(scores)): multiple lists:
Use index-based loops
2. Looping over lists with an index

for i in range(len(scores)): Use i to access each item


print(scores[i]) Access corresponding items
print(names[i]) with the same index

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Execution order
1 A = 90
2 B = 80
3 C = 70
4 scores = [96, 91, 79, 93, 86, …] Variable Value
5
6 num_As = 0 num_As 2
3
0
1
7 num_Bs = 0
8 num_Cs = 0 num_Bs 1
0
9
10 for score in scores: num_Cs 1
0
11 if score >= A:
12 num_As += 1
score 91
79
96
93
86
13 elif score >= B:
14 num_Bs += 1
15 elif score >= C:
16 num_Cs += 1
17
18 num_scores = len(scores)

Sean
SeanBarnes
Barnes
Programming fundamentals
for data analytics

Your first graded lab


Labs in the course
💻 Autograded
○ We test output of your code
against the correct answer # GRADED CELL: Exercise 1

○ Test your code as many times ### START CODE HERE ###
as you like before you submit
num_observations = None
💡 To make sure you get best grade:
### END CODE HERE ###
○ Use provided variables names
○ Replace instances of “None”
○ Only need modify cells that
include comment “Graded cell”

Sean
SeanBarnes
Barnes

You might also like