0% found this document useful (0 votes)
20 views28 pages

UNIT-1 Notes

The document outlines a course on Data Driven Decision Making (DDDM) using Python, covering topics from Python basics to advanced programming concepts. It includes sections on data types, lists, conditional logic, loops, and functions, along with practical applications and study tips. The course aims to equip learners with essential Python skills for business applications.

Uploaded by

dhirajsingh24524
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)
20 views28 pages

UNIT-1 Notes

The document outlines a course on Data Driven Decision Making (DDDM) using Python, covering topics from Python basics to advanced programming concepts. It includes sections on data types, lists, conditional logic, loops, and functions, along with practical applications and study tips. The course aims to equip learners with essential Python skills for business applications.

Uploaded by

dhirajsingh24524
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

Data Driven Decision Making

Using Python

UNIT - 1
DDDM using Python Unit 1

Contents

1 Course Overview & Python Basics 3


1.1 What is Python and Why It Matters for Business . . . . . . . . . . . . . . . . . . . . . . 3
1.1.1 Introduction to Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.2 Why Companies Use Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Understanding Google Colab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.1 What is Google Colab? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.2 How to Access Google Colab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Understanding the Colab Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Writing Your First Python Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4.1 The Print Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4.2 Variables - Storing Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2 Python Fundamentals - Data Types 7


2.1 Introduction to Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Numbers - Integers and Decimals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2.1 Integers (Whole Numbers) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2.2 Floats (Decimal Numbers) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3 Strings - Text Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.3.1 String Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.4 Basic Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

3 Working with Lists 11


3.1 Introduction to Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.2 Creating Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.3 Accessing List Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.4 List Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.5 Adding and Removing Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.5.1 Adding Items to Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.5.2 Removing Items from Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.6 List Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

4 Conditional Logic 16
4.1 Introduction to Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
4.2 If-Else Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
4.3 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.4 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

5 Loops and Automation 18


5.1 Introduction to Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.2 For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.2.1 Basic For Loop with Range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.2.2 Looping Through Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.3 While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

6 Introduction to Functions 22
6.1 What Are Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

1
DDDM using Python Unit 1

6.2 Creating Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22


6.3 Functions with Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
6.4 Functions with Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
6.5 ROI Calculator Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

7 Unit 1 Summary 25
7.1 Key Concepts Covered . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
7.2 Skills Gained . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
7.3 Business Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
7.4 Study Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

8 Appendix 27
8.1 Common Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
8.2 Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
8.2.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
8.2.2 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
8.2.3 Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
8.2.4 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
8.2.5 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
8.3 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

2
DDDM using Python Unit 1

1 Course Overview & Python Basics


1.1 What is Python and Why It Matters for Business
1.1.1 Introduction to Python
Python is a programming language - a way to communicate with computers to perform tasks
automatically. Think of it as giving instructions to a very fast, very obedient assistant who can process
massive amounts of data in seconds.
Business Insight
In business, Python helps you:
• Analyze sales data from thousands of transactions
• Predict customer behavior and trends
• Automate repetitive tasks like report generation
• Make data-driven decisions instead of relying on gut feelings
• Save time and reduce human errors in calculations
1.1.2 Why Companies Use Python
Leading companies like Netflix, Amazon, Google, and JP Morgan use Python for:
• Netflix: Recommending movies based on viewing patterns
• Amazon: Pricing optimization and inventory management
• Google: Data analysis and machine learning
• Banks: Risk assessment and fraud detection
Key Point
Python is chosen because it’s:
• Easy to read: Code looks almost like English
• Powerful: Can handle millions of data points
• Free: No licensing costs
• Versatile: Works for data analysis, automation, web development, and more

1.2 Understanding Google Colab


1.2.1 What is Google Colab?
Google Colab (Colaboratory) is a free online platform where you can write and run Python code
directly in your web browser. No installation needed!
Key Point
Think of Google Colab as:
• A Google Doc, but for writing code
• Runs on Google’s powerful computers (not your laptop)
• Automatically saves your work to Google Drive
• Allows you to share your analysis with colleagues

1.2.2 How to Access Google Colab


1. Open your web browser
2. Go to: [Link]
3. Sign in with your Google account
4. Click on ”New Notebook” to start coding

1.3 Understanding the Colab Interface


When you open a new notebook, you’ll see:
• Code Cells: Where you write Python code (gray boxes)
• Text Cells: Where you write notes or explanations
• Play Button: Runs the code in a cell

3
DDDM using Python Unit 1

• Menu Bar: File, Edit, View options (similar to Microsoft Word)

1.4 Writing Your First Python Code


1.4.1 The Print Function
The print() function is used to display information on the screen.
Example
Simple Print Statement:
1 print ( " Hello , Welcome to Python ! " )

Output:

Hello, Welcome to Python!

Code Explanation
Let’s break down this code:
• print - Command that tells Python to display something
• () - Parentheses hold what you want to display
• "Hello, Welcome to Python!" - Text inside quotes
• The quotation marks tell Python this is text, not code

Example
Printing Numbers:
1 print (100)
2 print (2024)
3 print (3.14)

Output:

100
2024
3.14

Note: Numbers don’t need quotation marks!

Example
Printing Multiple Items:
1 print ( " Company Revenue : " , 1000000)
2 print ( " Year : " , 2024 , " Quarter : " , " Q4 " )

Output:

Company Revenue: 1000000


Year: 2024 Quarter: Q4

1.4.2 Variables - Storing Information


A variable is like a labeled box where you store information.
Key Point
Why use variables?
• Store values to use later in calculations
• Make code easier to read and understand
• Avoid typing the same value multiple times
• Update values easily in one place

4
DDDM using Python Unit 1

Example
Creating Variables:
1 # Storing business information
2 company_name = " TechCorp "
3 annual_revenue = 5000000
4 growth_rate = 0.15
5 is_profitable = True
6
7 # Displaying the information
8 print ( " Company : " , company_name )
9 print ( " Revenue : " , annual _revenue )
10 print ( " Growth Rate : " , growth_rate )
11 print ( " Profitable : " , is_profitable )

Output:

Company: TechCorp
Revenue: 5000000
Growth Rate: 0.15
Profitable: True

Code Explanation
Understanding the code:
• company name - Variable name (the label on the box)
• = - The equals sign means ”store this value”
• "TechCorp" - This is the value being stored
• # - Lines starting with # are comments (ignored by Python)

Example
Business Scenario - Calculating Total Sales:
1 # Monthly sales data
2 january_sales = 50000
3 february_sales = 62000
4 march_sales = 58000
5
6 # Calculate quarterly sales
7 q1_sales = january_sales + februar y_sales + march_sales
8
9 # Display results
10 print ( " January Sales : " , january_sales )
11 print ( " February Sales : " , february _sales )
12 print ( " March Sales : " , march_sales )
13 print ( " Q1 Total Sales : " , q1_sales )

Output:

January Sales: 50000


February Sales: 62000
March Sales: 58000
Q1 Total Sales: 170000

Business Insight
Variables in Business Context:
• Store customer information (names, IDs, purchase amounts)
• Track financial metrics (revenue, costs, profit)
• Monitor performance indicators (sales targets, conversion rates)
• Manage inventory (product names, quantities, prices)

Practice Exercise
Try it yourself:
1. Create a variable called product name

5
DDDM using Python Unit 1

2. Create a variable called price


3. Create a variable called quantity
4. Print all three variables with appropriate labels

6
DDDM using Python Unit 1

2 Python Fundamentals - Data Types


2.1 Introduction to Data Types
In Python, every piece of data has a type.
Key Point
The main data types we’ll use for business analytics:
• Integer (int): Whole numbers (e.g., 100, 500, 1000)
• Float: Decimal numbers (e.g., 19.99, 3.14, 0.15)
• String (str): Text data (e.g., ”Sales Report”)
• Boolean (bool): True/False values

2.2 Numbers - Integers and Decimals


2.2.1 Integers (Whole Numbers)
Integers are whole numbers without decimal points.
Example
Integer Examples in Business:
1 # Product inventory
2 laptops_in_sto c k = 150
3 smartphones_so l d = 89
4 customer_id = 10234
5
6 # Display
7 print ( " Laptops available : " , l a p t o p s _ i n _ s t o c k )
8 print ( " Smartphones sold : " , s m a r t p h o n e s_ s o l d )
9 print ( " Customer ID : " , customer_id )
10 print ( type ( la p t o p s _i n _ s t o c k ) )

Output:

Laptops available: 150


Smartphones sold: 89
Customer ID: 10234
<class ’int’>
2.2.2 Floats (Decimal Numbers)
Floats are numbers with decimal points.
Example
Float Examples in Business:
1 # Financial data
2 product_price = 999.99
3 tax_rate = 0.18
4 d i s c o u n t_ p e r c e n t a g e = 15.5
5 interest_rate = 6.75
6
7 # Display
8 print ( " Product Price : $ " , product_price )
9 print ( " Tax Rate : " , tax_rate )
10 print ( " Discount : " , discount_percentage , " % " )
11 print ( type ( product_price ) )

Output:

Product Price: $ 999.99


Tax Rate: 0.18
Discount: 15.5 %
<class ’float’>

7
DDDM using Python Unit 1

2.3 Strings - Text Data


Strings are sequences of characters (text). They’re enclosed in quotation marks - either single (’) or
double (") quotes.
Example
String Examples:
1 # Customer information
2 customer_name = " Sarah Johnson "
3 product_catego r y = ’ Electronics ’
4 department = " Sales and Marketing "
5 email = " sarah . j@company . com "
6
7 # Multi - line strings ( using triple quotes )
8 p r o d u c t _d e s c r i p t i o n = " " "
9 High - performance laptop with 16 GB RAM ,
10 512 GB SSD , and Intel i7 processor .
11 Perfect for business professionals .
12 """
13
14 print ( " Customer : " , customer_name )
15 print ( " Category : " , p r o d u c t _ c at e g o r y )
16 print ( " Department : " , department )
17 print ( " Email : " , email )
18 print ( " Description : " , p r o d u c t _ d e s c r i p t i o n )
19 print ( type ( customer_name ) )

Output:

Customer: Sarah Johnson


Category: Electronics
Department: Sales and Marketing
Email: sarah.j@[Link]
Description:
High-performance laptop with 16GB RAM,
512GB SSD, and Intel i7 processor.
Perfect for business professionals.

<class ’str’>
2.3.1 String Operations
Example
String Concatenation:
1 first_name = " John "
2 last_name = " Smith "
3 full_name = first_name + " " + last_name
4 print ( " Full Name : " , full_name )
5
6 # Creating product codes
7 category_code = " ELC "
8 product_number = " 1045 "
9 ful l_p rodu ct_ c o d e = category_code + " -" + p roduct_ number
10 print ( " Product Code : " , f u l l _ p r o d u c t _ c o d e )

Output:

Full Name: John Smith


Product Code: ELC-1045

Example
String Formatting for Reports:
1 # Sales report data
2 sales_person = " Emily Davis "
3 monthly_sales = 125000
4 target = 100000
5

8
DDDM using Python Unit 1

6 # Method 1: Using f - strings ( recommended )


7 report1 = f " { sales_person } achieved $ { monthly_sales } in sales "
8 print ( report1 )
9
10 # Method 2: Using . format ()
11 report2 = " {} exceeded target by $ {} " . format (
12 sales_person , monthly_sales - target )
13 print ( report2 )
14
15 # More complex formatting
16 performance = f " " "
17 Sales Report
18 ============
19 Employee : { sales_person }
20 Sales : $ { monthly_sales : ,}
21 Target : $ { target : ,}
22 Achievement : {( monthly_sales / target ) *100:.1 f }%
23 """
24 print ( performance )

Output:

Emily Davis achieved $125000 in sales


Emily Davis exceeded target by $25000
Sales Report
============
Employee: Emily Davis
Sales: $125,000
Target: $100,000
Achievement: 125.0%

2.4 Basic Arithmetic Operations

Operation Symbol Example


Addition + 100 + 50 = 150
Subtraction - 200 - 80 = 120
Multiplication * 50 * 3 = 150
Division / 100 / 4 = 25.0
Exponentiation ** 2 ** 3 = 8

Table 1: Python Arithmetic Operators

Example
Business Calculations:
1 # Revenue calculation
2 units_sold = 150
3 price_per_unit = 299.99
4 total_revenue = units_sold * pric e_per_un it
5
6 print ( " Units Sold : " , units_sold )
7 print ( " Price per Unit : $ " , price_ per_uni t )
8 print ( " Total Revenue : $ " , total_revenue )
9
10 # Profit calculation
11 revenue = 50000
12 cost = 32000
13 profit = revenue - cost
14 profit_margin = ( profit / revenue ) * 100
15
16 print ( " \ nProfit Analysis : " )
17 print ( " Revenue : $ " , revenue )
18 print ( " Cost : $ " , cost )
19 print ( " Profit : $ " , profit )
20 print ( " Profit Margin : " , profit_margin , " % " )

Output:
Units Sold: 150
Price per Unit: $ 299.99

9
DDDM using Python Unit 1

Total Revenue: $ 44998.5

Profit Analysis:
Revenue: $ 50000
Cost: $ 32000
Profit: $ 18000
Profit Margin: 36.0 %

Practice Exercise
Practice Problems:
1. Calculate total cost: product costs $50, buy 12 units, 18% tax
2. Salesperson earns $3000 base + 7% commission on $80,000 sales
3. Create variables for customer name, email, and print welcome message

10
DDDM using Python Unit 1

3 Working with Lists


3.1 Introduction to Lists
A list is a collection of items stored in a single variable.
Key Point
Why lists are essential for business:
• Store multiple related items (sales figures, customer names)
• Keep data organized and easy to access
• Process large amounts of data efficiently
• Represent real-world business data

3.2 Creating Lists


Lists are created using square brackets [] with items separated by commas.
Example
Creating Business Lists:
1 # Sales data for each month
2 monthly_sales = [45000 , 52000 , 48000 , 61000 , 58000 , 63000]
3
4 # Product names
5 products = [ " Laptop " , " Mouse " , " Keyboard " , " Monitor " , " Headphones " ]
6
7 # Customer names
8 customers = [ " Alice Johnson " , " Bob Smith " , " Carol Davis " , " David Lee " ]
9
10 # Mixed data types in a list
11 laptop_info = [ " Dell Inspiron " , 899.99 , 25 , True ]
12
13 # Empty list ( to be filled later )
14 new_orders = []
15
16 print ( " Monthly Sales : " , monthly_sales )
17 print ( " Products : " , products )
18 print ( " Customers : " , customers )
19 print ( " Laptop Info : " , laptop_info )

Output:

Monthly Sales: [45000, 52000, 48000, 61000, 58000, 63000]


Products: [’Laptop’, ’Mouse’, ’Keyboard’, ’Monitor’, ’Headphones’]
Customers: [’Alice Johnson’, ’Bob Smith’, ’Carol Davis’, ’David Lee’]
Laptop Info: [’Dell Inspiron’, 899.99, 25, True]

3.3 Accessing List Items


Each item in a list has a position number called an index. Python uses zero-based indexing.
Key Point
List Indexing:
• First item: index 0
• Second item: index 1
• Third item: index 2
• And so on...

Example
Accessing Items:
1 products = [ " Laptop " , " Mouse " , " Keyboard " , " Monitor " , " Headphones " ]
2 prices = [899.99 , 25.50 , 79.99 , 299.99 , 149.99]
3
4 first_product = products [0]
5 third_product = products [2]
6 last_product = products [4]

11
DDDM using Python Unit 1

7
8 print ( " First product : " , first_product )
9 print ( " Third product : " , third_product )
10 print ( " Last product : " , last_product )
11
12 # Access using negative indexing ( from the end )
13 last_item = products [ -1]
14 second_last = products [ -2]
15
16 print ( " \ nUsing negative indexing : " )
17 print ( " Last product : " , last_item )
18 print ( " Second to last : " , second_last )
19
20 # Accessing prices
21 first_price = prices [0]
22 print ( " \ nPrice of " , products [0] , " is $ " , first_price )

Output:

First product: Laptop


Third product: Keyboard
Last product: Headphones

Using negative indexing:


Last product: Headphones
Second to last: Monitor

Price of Laptop is $ 899.99

Code Explanation
Understanding List Indexing:

List: ["Laptop", "Mouse", "Keyboard", "Monitor", "Headphones"]


Index: 0 1 2 3 4
Negative: -5 -4 -3 -2 -1

• products[0] gives ”Laptop” (first item)


• products[-1] gives ”Headphones” (last item)
• products[2] gives ”Keyboard” (third item)
• Negative indices count from the end

3.4 List Slicing


Slicing allows you to extract a portion of a list. The syntax is list[start:end], where:
• start - index where slice begins (inclusive)
• end - index where slice ends (exclusive)
Example
List Slicing:
1 # Quarterly sales data
2 monthly_sales = [45000 , 52000 , 48000 , 61000 , 58000 , 63000 ,
3 55000 , 59000 , 62000 , 67000 , 64000 , 70000]
4
5 # Get Q1 sales ( first 3 months )
6 q1_sales = monthly_sales [0:3]
7 print ( " Q1 Sales : " , q1_sales )
8
9 # Get Q2 sales ( months 4 -6 , indices 3 -5)
10 q2_sales = monthly_sales [3:6]
11 print ( " Q2 Sales : " , q2_sales )
12
13 # Get last 3 months
14 last_quarter = monthly_sales [ -3:]
15 print ( " Last Quarter : " , last_quarter )
16
17 # Get first 6 months
18 first_half = monthly_sales [:6]

12
DDDM using Python Unit 1

19 print ( " First Half : " , first_half )


20
21 # Get every other month
22 alternate_mon t h s = monthly_sales [::2]
23 print ( " Alternate Months : " , a l t e r n a t e _ mo n t h s )
24
25 # Calculate Q1 total
26 q1_total = sum ( q1_sales )
27 print ( f " \ nQ1 Total Sales : $ { q1_total } " )

Output:

Q1 Sales: [45000, 52000, 48000]


Q2 Sales: [61000, 58000, 63000]
Last Quarter: [67000, 64000, 70000]
First Half: [45000, 52000, 48000, 61000, 58000, 63000]
Alternate Months: [45000, 48000, 58000, 55000, 62000, 64000]

Q1 Total Sales: $145000

3.5 Adding and Removing Items


Lists are mutable, meaning you can change them after creation.
3.5.1 Adding Items to Lists
Example
Adding Items:
1 customer_order = []
2 print ( " Initial order : " , cu stomer_ order )
3
4 # Method 1: append () - adds item to the end
5 customer_order . append ( " Laptop " )
6 print ( " After adding laptop : " , custo mer_ord er )
7
8 customer_order . append ( " Mouse " )
9 customer_order . append ( " Keyboard " )
10 print ( " After adding more items : " , cus tomer_or der )
11
12 # Method 2: insert () - adds item at specific position
13 customer_order . insert (1 , " Monitor " )
14 print ( " After inserting Monitor at position 1: " , custom er_orde r )
15
16 # Method 3: extend () - adds multiple items
17 additional_it e m s = [ " USB Cable " , " Laptop Bag " ]
18 customer_order . extend ( a d d i t i o n a l _ i t e m s )
19 print ( " After extending : " , custom er_orde r )
20
21 # Real business example - Daily sales tracking
22 daily_sales = [1200 , 1500 , 1300]
23 print ( " \ nSales for first 3 days : " , daily_sales )
24
25 daily_sales . append (1450)
26 print ( " After day 4: " , daily_sales )
27
28 daily_sales . append (1600)
29 print ( " After day 5: " , daily_sales )
30
31 total = sum ( daily_sales )
32 print ( " Total sales for 5 days : $ " , total )

Output:

Initial order: []
After adding laptop: [’Laptop’]
After adding more items: [’Laptop’, ’Mouse’, ’Keyboard’]
After inserting Monitor at position 1: [’Laptop’, ’Monitor’,
’Mouse’, ’Keyboard’]
After extending: [’Laptop’, ’Monitor’, ’Mouse’, ’Keyboard’,
’USB Cable’, ’Laptop Bag’]

13
DDDM using Python Unit 1

Sales for first 3 days: [1200, 1500, 1300]


After day 4: [1200, 1500, 1300, 1450]
After day 5: [1200, 1500, 1300, 1450, 1600]
Total sales for 5 days: $ 7050

3.5.2 Removing Items from Lists


Example
Removing Items:
1 inventory = [ " Laptop " , " Mouse " , " Keyboard " , " Monitor " ,
2 " Headphones " , " Webcam " ]
3 print ( " Initial : " , inventory )
4
5 # Method 1: remove () - removes first occurrence of value
6 inventory . remove ( " Mouse " )
7 print ( " After selling Mouse : " , inventory )
8
9 # Method 2: pop () - removes item at index and returns it
10 sold_item = inventory . pop (0)
11 print ( " Sold item : " , sold_item )
12 print ( " Remaining inventory : " , inventory )
13
14 # pop () without index removes last item
15 last_sold = inventory . pop ()
16 print ( " Last item sold : " , last_sold )
17 print ( " Current inventory : " , inventory )
18
19 # Method 3: del - deletes item at specific index
20 del inventory [1]
21 print ( " After deletion : " , inventory )
22
23 # Business scenario - Managing waitlist
24 waitlist = [ " Customer A " , " Customer B " , " Customer C " , " Customer D " ]
25 print ( " \ nWaitlist : " , waitlist )
26
27 served = waitlist . pop (0)
28 print ( f " Now serving : { served } " )
29 print ( " Updated waitlist : " , waitlist )

Output:

Initial: [’Laptop’, ’Mouse’, ’Keyboard’, ’Monitor’,


’Headphones’, ’Webcam’]
After selling Mouse: [’Laptop’, ’Keyboard’, ’Monitor’,
’Headphones’, ’Webcam’]
Sold item: Laptop
Remaining inventory: [’Keyboard’, ’Monitor’, ’Headphones’,
’Webcam’]
Last item sold: Webcam
Current inventory: [’Keyboard’, ’Monitor’, ’Headphones’]
After deletion: [’Keyboard’, ’Headphones’]

Waitlist: [’Customer A’, ’Customer B’, ’Customer C’,


’Customer D’]
Now serving: Customer A
Updated waitlist: [’Customer B’, ’Customer C’, ’Customer D’]

3.6 List Operations


Example
Common Operations:
1 prices = [299.99 , 149.99 , 79.99 , 499.99 , 199.99]
2
3 print ( " Number of products : " , len ( prices ) )
4 print ( " Lowest price : $ " , min ( prices ) )
5 print ( " Highest price : $ " , max ( prices ) )

14
DDDM using Python Unit 1

6 print ( " Total value : $ " , sum ( prices ) )


7 average = sum ( prices ) / len ( prices )
8 print ( " Average : $ " , average )
9
10 # Sorting ( creates new sorted list )
11 sorted_prices = sorted ( prices )
12 print ( " \ nPrices ( low to high ) : " , sorted_prices )
13
14 sorted_desc = sorted ( prices , reverse = True )
15 print ( " Prices ( high to low ) : " , sorted_desc )
16
17 # Sort in place ( modifies original list )
18 prices . sort ()
19 print ( " Original list sorted : " , prices )
20
21 # Count occurrences
22 sales_regions = [ " North " , " South " , " North " , " East " , " North " , " West " ]
23 north_count = sales_regions . count ( " North " )
24 print ( " \ nSales from North region : " , north_count )
25
26 # Check if item exists
27 if " East " in sales_regions :
28 print ( " We have sales in East region " )
29
30 # Find index of item
31 position = sales_regions . index ( " South " )
32 print ( " South is at position : " , position )

Output:

Number of products: 5
Lowest price: $ 79.99
Highest price: $ 499.99
Total value: $ 1229.95
Average: $ 245.99

Prices (low to high): [79.99, 149.99, 199.99, 299.99, 499.99]


Prices (high to low): [499.99, 299.99, 199.99, 149.99, 79.99]
Original list sorted: [79.99, 149.99, 199.99, 299.99, 499.99]

Sales from North region: 3


We have sales in East region
South is at position: 1

Practice Exercise
Practice:
1. Create a list of 5 employee salaries and calculate total payroll
2. Create a list of temperatures and find highest and lowest
3. Create a shopping cart, add 5 items, remove 2, display final cart

15
DDDM using Python Unit 1

4 Conditional Logic
4.1 Introduction to Conditionals
In business, we make decisions based on conditions.
Key Point
Conditional statements let your program make decisions based on whether conditions are true or
false.

4.2 If-Else Statements


Example
Simple If Statement:
1 actual_sales = 75000
2 target_sales = 50000
3
4 if actual_sales >= target_sales :
5 print ( " Sales target achieved ! " )
6 print ( f " Actual Sales : $ { actual_sales } " )
7 print ( f " Target : $ { target_sales } " )

Output:

Sales target achieved!


Actual Sales: $75000
Target: $50000

Example
If-Else Statement:
1 current_stock = 15
2 minimum_stock = 20
3
4 if current_stock >= minimum_stock :
5 print ( " Stock level is adequate " )
6 else :
7 print ( " LOW STOCK ALERT ! " )
8 shortage = minimum_stock - current_stock
9 print ( f " Please reorder : { shortage } units " )

Output:

LOW STOCK ALERT!


Please reorder: 5 units

Example
If-Elif-Else:
1 sal es_ achi eve m e n t = 120
2
3 if sal es_a chi e v e m e n t >= 150:
4 rating = " Outstanding "
5 bonus = 15000
6 elif sa les _ac h i e v e m e n t >= 120:
7 rating = " Excellent "
8 bonus = 10000
9 elif sa les _ac h i e v e m e n t >= 100:
10 rating = " Good "
11 bonus = 5000
12 else :
13 rating = " Needs Improvement "
14 bonus = 0
15
16 print ( " Rating : " , rating )
17 print ( " Bonus : $ " , bonus )

Output:
Rating: Excellent

16
DDDM using Python Unit 1

Bonus: $ 10000

4.3 Comparison Operators

Operator Symbol Meaning


Equal to == Are values equal?
Not equal != Are values different?
Greater than ¿ Is left larger?
Less than ¡ Is left smaller?
Greater or equal ¿= Left larger or equal?
Less or equal ¡= Left smaller or equal?

Table 2: Comparison Operators

4.4 Logical Operators


Example
Using AND, OR, NOT:
1 credit_score = 720
2 annual_income = 75000
3
4 if credit_score >= 700 and annual_income >= 50000:
5 print ( " LOAN APPROVED " )
6 if credit_score >= 750:
7 interest_rate = 6.5
8 else :
9 interest_rate = 7.5
10 print ( f " Interest Rate : { interest_rate }% " )
11 else :
12 print ( " LOAN DENIED " )

Output:

LOAN APPROVED
Interest Rate: 7.5%

Practice Exercise
Practice:
1. Check if student passed (grade ¿= 60)
2. Discount: 10% if purchase ¿ $100, 20% if ¿ $500
3. Check voting eligibility (age ¿= 18)

17
DDDM using Python Unit 1

5 Loops and Automation


5.1 Introduction to Loops
Loops allow you to repeat code multiple times.
Business Insight
In business, loops are used for:
• Processing all customers in a database
• Calculating totals from multiple transactions
• Generating reports for multiple products

5.2 For Loops


The for loop is used when you know how many times to repeat or when you want to go through each
item in a collection.
5.2.1 Basic For Loop with Range
Example
Simple For Loop:
1 print ( " Counting from 1 to 5: " )
2 for i in range (1 , 6) :
3 print ( i )
4
5 # range (1 , 6) generates numbers : 1 , 2 , 3 , 4 , 5
6 # Note : 6 is not included !

Output:

Counting from 1 to 5:
1
2
3
4
5

Code Explanation
Understanding the For Loop:
• for - keyword that starts the loop
• i - variable that holds the current value
• in - keyword meaning ”from”
• range(1, 6) - generates numbers from 1 to 5
• : - marks the end of the loop declaration
• Indented code - executes for each value
Range Function Variations:
• range(5) - generates 0, 1, 2, 3, 4
• range(1, 6) - generates 1, 2, 3, 4, 5
• range(0, 10, 2) - generates 0, 2, 4, 6, 8 (step of 2)

5.2.2 Looping Through Lists


Example
Processing Sales Data:
1 daily_sales = [1200 , 1350 , 1100 , 1450 , 1600 , 1800 , 1400]
2 days = [ " Mon " , " Tue " , " Wed " , " Thu " , " Fri " , " Sat " , " Sun " ]
3
4 print ( " === DAILY SALES REPORT ===\ n " )
5
6 # Method 1: Loop through list directly

18
DDDM using Python Unit 1

7 for sale in daily_sales :


8 print ( f " Daily Sale : $ { sale } " )
9
10 print ( " \ n " + " = " *40 + " \ n " )
11
12 # Method 2: Loop with index to access multiple lists
13 for i in range ( len ( days ) ) :
14 print ( f " { days [ i ]}: $ { daily_sales [ i ]} " )
15
16 print ( " \ n " + " = " *40 + " \ n " )
17
18 # Method 3: Using enumerate
19 for index , day in enumerate ( days ) :
20 sale = daily_sales [ index ]
21 print ( f " Day { index + 1} ({ day }) : $ { sale } " )
22
23 # Highlight best sales day
24 if sale >= 1600:
25 print ( " Outstanding performance ! " )

Output:

=== DAILY SALES REPORT ===

Daily Sale: $1200


Daily Sale: $1350
Daily Sale: $1100
Daily Sale: $1450
Daily Sale: $1600
Daily Sale: $1800
Daily Sale: $1400

========================================

Mon: $1200
Tue: $1350
Wed: $1100
Thu: $1450
Fri: $1600
Sat: $1800
Sun: $1400

========================================

Day 1 (Mon): $1200


Day 2 (Tue): $1350
Day 3 (Wed): $1100
Day 4 (Thu): $1450
Day 5 (Fri): $1600
Outstanding performance!
Day 6 (Sat): $1800
Outstanding performance!
Day 7 (Sun): $1400

Example
Calculating Totals with Loops:
1 months = [ " Jan " , " Feb " , " Mar " , " Apr " , " May " , " Jun " ]
2 sales = [45000 , 52000 , 48000 , 61000 , 58000 , 63000]
3
4 print ( " === MONTHLY SALES ANALYSIS ===\ n " )
5
6 # Calculate running total

19
DDDM using Python Unit 1

7 total_sales = 0
8 for i in range ( len ( months ) ) :
9 total_sales += sales [ i ]
10
11 print ( f " { months [ i ]}: $ { sales [ i ]: ,} " )
12 print ( f " Running Total : $ { total_sales : ,} " )
13
14 # Calculate growth from previous month
15 if i > 0:
16 growth = sales [ i ] - sales [i -1]
17 growth_ percent = ( growth / sales [i -1]) * 100
18
19 if growth > 0:
20 print ( f " Growth : + $ { growth : ,} ({ gr owth_pe rcent :.1 f }%) " )
21 else :
22 print ( f " Decline : $ { growth : ,} ({ gr owth_pe rcent :.1 f }%) " )
23 print ()
24
25 # Final summary
26 average_sales = total_sales / len ( sales )
27 print ( " = " *40)
28 print ( f " Total Sales (6 months ) : $ { total_sales : ,} " )
29 print ( f " Average Monthly Sales : $ { average_sales : ,.2 f } " )

Output:

=== MONTHLY SALES ANALYSIS ===

Jan: $45,000
Running Total: $45,000

Feb: $52,000
Running Total: $97,000
Growth: +$7,000 (15.6%)

Mar: $48,000
Running Total: $145,000
Decline: $-4,000 (-7.7%)

Apr: $61,000
Running Total: $206,000
Growth: +$13,000 (27.1%)

May: $58,000
Running Total: $264,000
Decline: $-3,000 (-4.9%)

Jun: $63,000
Running Total: $327,000
Growth: +$5,000 (8.6%)

========================================
Total Sales (6 months): $327,000
Average Monthly Sales: $54,500.00

5.3 While Loops


Example
While Loop:
1 count = 5
2 print ( " Countdown : " )
3 while count > 0:
4 print ( count )
5 count -= 1

20
DDDM using Python Unit 1

6 print ( " Done ! " )

Output:

Countdown:
5
4
3
2
1
Done!

Practice Exercise
Practice:
1. Calculate factorial of 5 using a loop
2. Apply 15% discount to a list of prices
3. Create multiplication table for numbers 1-5

21
DDDM using Python Unit 1

6 Introduction to Functions
6.1 What Are Functions
A function is a reusable block of code that performs a specific task.
Key Point
Benefits of Functions:
• Reusability: Write once, use many times
• Organization: Break complex problems into smaller pieces
• Maintainability: Update code in one place
• Readability: Give meaningful names to operations

6.2 Creating Functions


Example
Basic Function:
1 def greet_customer () :
2 print ( " Welcome to our store ! " )
3 print ( " How can we help you today ? " )
4
5 # Call the function
6 greet_customer ()

Output:

Welcome to our store!


How can we help you today?

6.3 Functions with Parameters


Example
Function with Parameters:
1 def greet_customer ( customer_name ) :
2 print ( f " Welcome { customer_name }! " )
3 print ( " Thank you for shopping with us . " )
4
5 greet_customer ( " Sarah " )
6 greet_customer ( " Michael " )

Output:

Welcome Sarah!
Thank you for shopping with us.
Welcome Michael!
Thank you for shopping with us.

6.4 Functions with Return Values


Example
Returning Values:
1 def calculate_tax ( amount , tax_rate ) :
2 tax = amount * tax_rate
3 return tax
4
5 def calculate_ to t al ( price , quantity , tax_rate ) :
6 subtotal = price * quantity
7 tax = subtotal * tax_rate
8 total = subtotal + tax
9 return total
10
11 # Using the functions
12 product_price = 100
13 qty = 3

22
DDDM using Python Unit 1

14 tax_rate = 0.18
15
16 tax_amount = calculate_tax ( product_price * qty , tax_rate )
17 print ( f " Tax Amount : $ { tax_amount } " )
18
19 final_total = ca lc ul a te _t o ta l ( product_price , qty , tax_rate )
20 print ( f " Final Total : $ { final_total } " )

Output:

Tax Amount: $54.0


Final Total: $354.0

6.5 ROI Calculator Example


Example
ROI Calculator:
1 def calculate_roi ( initial , final ) :
2 " " " Calculate Return on Investment " " "
3 profit = final - initial
4 roi_percentage = ( profit / initial ) * 100
5 return profit , r oi_perce ntage
6
7 def d is p la y _r o i _ r e p o r t ( name , initial , final ) :
8 " " " Display a formatted ROI report " " "
9 profit , roi = calculate_roi ( initial , final )
10
11 print ( f " \ n === ROI ANALYSIS : { name } === " )
12 print ( f " Initial Investment : $ { initial : ,} " )
13 print ( f " Final Value : $ { final : ,} " )
14 print ( f " Profit / Loss : $ { profit : ,} " )
15 print ( f " ROI : { roi :.2 f }% " )
16
17 if roi > 0:
18 print ( " Status : Profitable Investment " )
19 elif roi < 0:
20 print ( " Status : Loss on Investment " )
21 else :
22 print ( " Status : Break - even " )
23
24 # Test the functions
25 d is pl a y_ r oi _r e p o r t ( " Marketing Campaign A " , 50000 , 75000)
26 d is pl a y_ r oi _r e p o r t ( " Product Launch B " , 100000 , 95000)
27 d is pl a y_ r oi _r e p o r t ( " Store Renovation " , 200000 , 280000)
28
29 # Calculate ROI for multiple investments
30 print ( " \ n " + " = " *50)
31 print ( " PORTFOLIO ANALYSIS " )
32 print ( " = " *50)
33
34 investments = [ " Stock A " , " Stock B " , " Real Estate " , " Bonds " ]
35 initial_amount s = [10000 , 15000 , 200000 , 50000]
36 current_values = [12500 , 14000 , 250000 , 52500]
37
38 total_invested = 0
39 total_current = 0
40
41 for i in range ( len ( investments ) ) :
42 profit , roi = calculate_roi ( i ni ti al _ am ou n ts [ i ] ,
43 curr ent_val ues [ i ])
44 print ( f " \ n { investments [ i ]}: " )
45 print ( f " ROI : { roi :+.2 f }% " )
46 print ( f " Profit : $ { profit :+ ,} " )
47
48 total_invested += in it ia l _a mo un t s [ i ]
49 total_current += curre nt_value s [ i ]
50
51 # Portfolio overall ROI
52 portfolio_profit , portfolio_roi = calculate_roi ( total_invested ,
53 total_current )
54 print ( " \ n " + " = " *50)
55 print ( " PORTFOLIO SUMMARY : " )
56 print ( f " Total Invested : $ { tota l_invest ed : ,} " )
57 print ( f " Current Value : $ { total_current : ,} " )
58 print ( f " Overall ROI : { portfolio_roi :.2 f }% " )
59 print ( f " Total Profit : $ { p o r t f o l i o _ p r o f i t : ,} " )

Output:

23
DDDM using Python Unit 1

=== ROI ANALYSIS: Marketing Campaign A ===


Initial Investment: $50,000
Final Value: $75,000
Profit/Loss: $25,000
ROI: 50.00%
Status: Profitable Investment

=== ROI ANALYSIS: Product Launch B ===


Initial Investment: $100,000
Final Value: $95,000
Profit/Loss: $-5,000
ROI: -5.00%
Status: Loss on Investment

=== ROI ANALYSIS: Store Renovation ===


Initial Investment: $200,000
Final Value: $280,000
Profit/Loss: $80,000
ROI: 40.00%
Status: Profitable Investment

==================================================
PORTFOLIO ANALYSIS
==================================================

Stock A:
ROI: +25.00%
Profit: $+2,500

Stock B:
ROI: -6.67%
Profit: $-1,000

Real Estate:
ROI: +25.00%
Profit: $+50,000

Bonds:
ROI: +5.00%
Profit: $+2,500

==================================================
PORTFOLIO SUMMARY:
Total Invested: $275,000
Current Value: $329,000
Overall ROI: 19.64%
Total Profit: $54,000

Practice Exercise
Practice:
1. Create a function to calculate rectangle area
2. Write a function to convert Celsius to Fahrenheit
3. Create a function that applies discount to a list of prices

24
DDDM using Python Unit 1

7 Unit 1 Summary
7.1 Key Concepts Covered
1. Python Basics
• What Python is and why it’s valuable
• Using Google Colab
• Print statements and variables
2. Data Types
• Integers and floats
• Strings
• Basic arithmetic operations
3. Lists
• Creating and accessing lists
• Adding and removing items
• List operations
4. Conditional Logic
• If-else statements
• Comparison operators
• Logical operators
5. Loops
• For loops
• While loops
• Processing data
6. Functions
• Creating functions
• Parameters and return values
• Business calculations

7.2 Skills Gained


By completing Unit 1, you can now:
• Write basic Python programs
• Store and manipulate data
• Make automated decisions
• Process datasets with loops
• Create reusable functions
• Analyze sales data
• Calculate profits and commissions

7.3 Business Applications


• Automate sales calculations
• Analyze product profitability
• Calculate commissions
• Manage inventory
• Process transactions
• Generate reports

7.4 Study Tips


1. Practice Regularly: Code daily for 15-30 minutes
2. Apply to Real Scenarios: Use workplace examples
3. Experiment: Modify examples
4. Break Down Problems: Step by step approach
5. Use Comments: Document your code
6. Review Errors: Learn from mistakes

25
DDDM using Python Unit 1

Key Point
Programming improves with practice. Every expert started as a beginner!

26
DDDM using Python Unit 1

8 Appendix
8.1 Common Errors

Error Solution
SyntaxError Check colons, parentheses, quotes
IndentationError Use consistent indentation
NameError Variable doesn’t exist
TypeError Incompatible types
IndexError List index out of range
ZeroDivisionError Dividing by zero

Table 3: Common Python Errors

8.2 Quick Reference


8.2.1 Variables
1 name = " John " # String
2 age = 25 # Integer
3 price = 19.99 # Float
4 is_active = True # Boolean

8.2.2 Lists
1 items = [1 , 2 , 3 , 4 , 5]
2 items [0] # First item
3 items . append (6) # Add to end
4 items . remove (3) # Remove value
5 len ( items ) # Length
6 sum ( items ) # Sum

8.2.3 Conditionals
1 if condition :
2 # code
3 elif an oth er_ co n d i t i o n :
4 # code
5 else :
6 # code

8.2.4 Loops
1 for item in items :
2 print ( item )
3
4 for i in range (5) :
5 print ( i )
6
7 while condition :
8 # code

8.2.5 Functions
1 def function_name ( param1 , param2 ) :
2 result = param1 + param2
3 return result
4
5 value = function_name (5 , 10)

8.3 Resources

27

You might also like