0% found this document useful (0 votes)
9 views19 pages

Python Basics and Google Colab Guide

The document introduces Python as a popular programming language, particularly for analytics, and highlights its advantages over Excel, including higher salary potential and suitability for large datasets. It also covers Google Colab as a free, user-friendly platform for running Python code, and outlines core programming concepts, data structures, and the importance of responsible AI use in coding. Additionally, it emphasizes the need for well-documented and readable code in data science practices.

Uploaded by

divya.chouhan205
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)
9 views19 pages

Python Basics and Google Colab Guide

The document introduces Python as a popular programming language, particularly for analytics, and highlights its advantages over Excel, including higher salary potential and suitability for large datasets. It also covers Google Colab as a free, user-friendly platform for running Python code, and outlines core programming concepts, data structures, and the importance of responsible AI use in coding. Additionally, it emphasizes the need for well-documented and readable code in data science practices.

Uploaded by

divya.chouhan205
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

Introduction to Python and

Google Colab

MKT46150
Lecture 2
“Big” meaning datasets with more
than 1 million rows, which Excel
cannot handle
Why Python?
• Python is the most popular general programming
language (and 2nd after JavaScript overall)
• In terms of projects on GitHub
• In terms of tags on StackOverflow
• World Economic Forum predicts a 30-
35% increase in analytics jobs by 2027
• 37% increase within retail sector
• CWJobs reports average salary for roles
with Python skills in the UK is £67,500
• Compared to £37,500 for comparable roles
requiring Excel skills
• 53% of marketing executives in Ireland
report upskilling in analytics is necessary
• Marketing analytics tasks which can be
performed in Excel can be automated in
a replicable manner with Python
• Python is appropriate for “big” data,
machine learning, AI, etc…
What is Python?
• A general-purpose programming language
• Open source meaning it is:
• “Free” as in “speech”: Anyone can change or contribute
to the project
• “Free” as in “beer”: There is no cost associated with using
Python

• Created by Guido van Rossum in 1991


• Named the language after “Monty Python’s
Flying Circus”
• Features:
• Focused on human readability
• Indentation is meaningful
• An interpreted language, meaning code is
executed directly
• A high-level language, meaning the concerns of
the computing machine are abstracted away
• These features make Python easier to use
than many other programming languages
More about this later…

What is Colab?
• A hosted notebook service
• Hosted meaning it is stored on
Google’s servers and is accessible
via web browser
• Notebook meaning it integrates plain
language with executable Python
code blocks
• Requires no setup
• Free with a Google account
• e.g., your UCD email address
• Access Google Colab:
[Link] Open Google Colab now!
Let’s try in Colab Operator Type Operation Sample Return
Expression
+ Binary Addition a+b Arithmetic sum of a

Doing math in Python


and b
- Unary Negation -a Negative value of a

- Binary Subtraction a-b Difference of a and


b

• Python uses operators to * Binary Multiplication a*b Product of a and b

define mathematical / Binary Division a/b Quotient of a and b


expressions % Binary Modulo a%b The remainder of a
• Operator: Special token which divided by b
represent common computations // Binary Integer a // b Quotient of a and b,
• Expression: A combination of division rounded down to
values, variables, operators, and the nearest integer
functions to be evaluated ** Binary Exponentiation a**b a raised to the
power of b
• Python follows PEMDAS rules of == Binary Equivalence a == b A Boolean value
order in evaluation, from left to indicating whether
right: a is the same as b
1. Parentheses >(=) Binary Greater than a>b A Boolean value
2. Exponentiation (or equal to) indicating whether
a is greater than b
3. Multiplication OR division <(=) Binary Less than a<b A Boolean value
4. Addition OR subtraction (or equal to) indicating whether
a is less than b
Variables and assignment
• Note in the last exercise, Colab
raised a warning:
• Expression value is unused
• Python completed the evaluation,
but we didn’t tell it what to do with
the result
• The most common option is to a = 5
store the output as a variable a = a + 2
• A variable is a reference to an b = 3
object in memory b = a + b
b
• Variables allow us to capture the
output of an expression and refer What is the value of b? Let’s try in Colab
to this output later
• Variables are assigned with the
binary operator: =
Data types in Python
• We can convert one data type to
• Data types classify values another (in many cases):
according to the kind of data a = 4.0
they represent a = int(a)
• Integer (int): Whole (real) • And check the data type of a
numbers without decimal values
variable:
• Floating point (float): Real
numbers with decimal values type(a)
• Boolean (bool): Logical truth
values, either True or False In Colab, follow this sequence of
• String (str): A sequence of commands, then convert a to a
characters (i.e., text) string type. What do you notice?
• NoneType (None): The absence of
a value
Comments are notes written for
humans which will be ignored by

Data structures in Python 1 Python. They start with #

hello_world = “hello world.”


• A Data structure organizes • Indexed means we can select items
different data types based on their place in the order:
hello_world[0] # Index starts at 0
• A string is both a data type hello_world[2]
and structure (sequence): hello_world[-1] # Count from right to left
hello_world = “hello world.”
• Sliced means we can select a range
• Strings are defined by quotes based on indexes:
(single or double) hello_world[0:5]
• A sequence is a collection of hello_world[5:]
items (e.g., characters) hello_world[5:-1]
• Items are ordered Try indexes and slices in Colab.
• Items are indexed Do you notice an unusual
• Sequences can be sliced behavior in how slice values
are interpreted?
Note that the type of brackets
used defines the data structure

Data structures in Python 2


• There are several common data Special data structures
structures in Python: • Dataframe: A tabular format like an
• Strings: immutable (cannot be Excel spreadsheet, enabled by the
changed by index) and ordered Pandas library
• List: mutable, ordered, allows
duplicates • Array: A matrix of numbers, enabled
fruits = [“apple”, “pear”, “orange”] by the NumPy library
• Tuple: immutable, ordered, allows
duplicates
colors = (“red”, “green”, “blue”)
• Set: mutable, unordered, does not
allow duplicates
• Input: unique_numbers = {1, 1, 2, 3, 3}
• Output: unique_numbers = {1, 2, 3}
• Dictionary: mutable, unordered,
stored in key-value pairs
student = {”name”: “Alice”, “age”: 22}
fruit is a temporary variable
capturing each step of the iteration

Navigating data structures


• We can iterate over items in a • Data structures can contain a
data structure using a for loop: mixture of data types
fruits = [“apple”, “pear”, “orange”]
• Data structures can even contain
for fruit in fruits:
print(fruit)
other data structures:
students = {”name”: [“Alice”, “John”],
“age”: [22, 24]}

Experiment with some different data


structures and for loops in Colab

Note that the whitespace or


indentation here is important!
Working with data structures
• Ordered and mutable data • In Colab, create a set of fruits
structures can be modified by • Ask Gemini to add an item “avocado”
index: to the set
fruits[1] = “mango”
• Or updated with special
functions called “dot methods”:
[Link](“cherry”)
• What dot method did it use to add an
• Or combined: item to the set?
veg = [“carrot”, “broccoli”, “spinach”]
basket = fruits + veg
Using conditional logic
• An if statement checks a condition and runs a • Let’s try with our basket list…
block of code if the condition is True.
for item in basket:
• Python uses an if..elif…else logic if item in fruits:
Temperature = 25 print(item, “is a fruit”)
if temperature > 30: elif item in veg:
print(“It’s hot outside!”) print(item, “is a vegetable”)
• Elif means “else if”: else:
if temperature > 30: print(item, “is neither fruit nor vegetable”)
print(“It’s hot outside!”)
elif temperature < 15:
print(“It’s cold outside!”)
• Else captures all other conditions:
if temperature > 30:
print(“It’s hot outside!”)
elif temperature < 15:
print(“It’s cold outside!”)
else:
print(“It’s pleasant outside.”)
Pulling it together: Defining functions
• Functions are reusable blocks of code
which can be called by name
• Let’s turn our basket conditional
def greeting(name):
into a function:
return “Hello, “ + name
• Functions: def identify_item(item):
if item in fruits:
• Have a name (“greeting”)
id = item + “ is a fruit”
• Take arguments (“name”) elif item in veg:
• Return an output id = item + “ is a vegetable”

• Functions are then called by name: else:


id = item + “ is neither fruit nor vegetable”
greeting(“David”)
return id
Interlude: Vibe coding for fun and profit
• “Vibe coding basically refers to using
generative AI not just to assist with coding, but
to generate the entire code for an app” Noah
Giansiracusa
• “The idea is to let AI do the heavy lifting while
you focus on the bigger picture. Supporters
argue vibe-coding free developers from the
constraints of manual coding, making
development faster and simpler” Paolo
Perrone
…but it’s not all super unicorns…

How it starts… How it’s going… How it ends…


Tips for responsible vibe coding
• Choose popular and simple tools
• “Their ability to generate correct, useful code is
directly proportional to the quality and quantity
of examples available online. The more common
and well-documented the framework or
language, the better the LLM’s performance.”
Paolo Perrone
Include evidence of this approach in
• Make code generation deterministic
your notebooks and project reports!
• Break down problems into smaller, defined steps.
Prompt AI for each step individually
• Use examples to help the AI understand what
you’re looking for (e.g., provide input and output
examples)
• Provide rich context including code examples,
data structures, output formats, and constraints
• Review and test carefully!
Vibe coding for data analysis
• Inspect the data file provided on
BrightSpace Gemini prompt: Write a function which asks
• It’s often helpful to get a sense of the the user to upload an xlsx file. Then read the
data structure via Excel second sheet in the file into a dataframe.
• Use Gemini to read the file into Print the name of the dataframe.
Colab and create a dataframe
• Use Gemini to print information
about the dataframe Gemini prompt: Print information for
• What do you learn from this output? dataframe.

• Summarize the data using


descriptive statistics Gemini prompt: Print a summary of
• What do you learn form this output? descriptive statistics for the dataframe.
• Create a plot of average order_value Gemini prompt: Plot average order_value on
and average order_size by refferal the y axis and average order_size on the x
group axis, where values are the average per
• What do you learn from this plot? referral_channel in the dataframe.
Embrace literate programming
• Code should ideally be self-
documenting
• Easy to read and understand
• Variable names should be meaningful
• Have a clear and clean structure
• Code should be well-documented
• Literate programming integrates the
thoughts and motivations of the writer
with the code itself
• Use text blocks in Colab to document
your process
• Text blocks can be formatted with the
WYSIWYG editor or Markdown
• Always include the Gemini prompts used
to generate code blocks!
• Don’t be afraid to show and discuss what
worked and what didn’t
Formalized by computer scientist Donald Knuth
• This is required for your assignment
submissions!
Lecture summary
• Python for Marketers: Python is a dominant programming language in tech and data science, with
increasing job demand in analytics. It's more scalable than Excel, especially for large datasets, and offers
higher salary potential for roles requiring Python.
• Python and Colab: Python is a general-purpose, open-source language focused on readability and ease of
use. Google Colab is a free, browser-based platform for running Python code in interactive notebooks, ideal
for beginners.
• Core Programming Concepts: Python syntax for math operations, define, assigning variables, and key data
types.
• Data Structures: Navigating basic data structures with indexing, slicing, mutability, and iterating through
data using for loops.
• Logic and Functions: Python’s conditional logic enables decision-making in code, while user-defined
functions help package reusable logic.
• Vibe Coding with Generative AI: When using tools like Gemini to generate full code blocks from prompts, it’s
important to focus on structure and context while letting AI handle syntax.
• Responsible AI Use in Coding: Best practices for AI-assisted coding include breaking down problems, giving
clear examples, making prompts deterministic, and documenting both successes and failures.
• Literate Programming: Emphasis is placed on well-commented, readable code. Use text cells in Colab to
document reasoning and Gemini prompts, aligning with good data science and academic practices.

You might also like