0% found this document useful (0 votes)
1 views76 pages

Python Unleashed

The document is a guide for beginners learning Python, emphasizing that programming is about precision and logical thinking rather than memorization. It encourages learners to embrace confusion as a part of the learning process and provides a structured roadmap for mastering Python, including chapters on logic, data structures, and analytics. The book aims to build confidence in self-doubting learners through real-world examples, exercises, and AI-assisted learning tips.

Uploaded by

mouryag1999
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)
1 views76 pages

Python Unleashed

The document is a guide for beginners learning Python, emphasizing that programming is about precision and logical thinking rather than memorization. It encourages learners to embrace confusion as a part of the learning process and provides a structured roadmap for mastering Python, including chapters on logic, data structures, and analytics. The book aims to build confidence in self-doubting learners through real-world examples, exercises, and AI-assisted learning tips.

Uploaded by

mouryag1999
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

UNLEASHED
From Zero to Data Application Builder — A Complete Guided Journey

Python Logic Data


Basics Building Structures Algorithms Pandas SQL Thinking Analytics Cricket App

✓ Real-world examples ✓ Confidence-building journey ✓ Hands-on projects

✓ AI-assisted learning tips ✓ Cricket Analytics capstone

"You are not learning to type faster.


You are learning to think clearer.
And that changes everything."

A Complete Textbook for Beginners, Self-Doubting Learners & Aspiring Data Professionals

Python Unleashed 1
A LETTER TO YOU, THE LEARNER

This book is for you.

Not for the person who already knows Python. Not for the one who studied computer
science in college. Not for the person who learned programming as a teenager and treats it
as obvious. This book is specifically written for the person who feels uncertain, who has
started and stopped, who wonders if they're 'smart enough', who compares themselves to
faster learners and feels left behind.

Here is what I want you to know before you turn a single page:

You are not behind. You are exactly where you need to be. Intelligence in programming is
not fixed — it is trained. Every concept in this book was confusing to every expert who ever
understood it. The only difference between you and them is time and repetition. Nothing
else.

How to use this book:

Read slowly. Each chapter builds on the last. Don't skip ahead. When something is
confusing, that's not a signal to give up — it's a signal to read it again more slowly.
Confusion is the feeling of your brain building new connections. It's not failure. It's growth.

Do every exercise. Reading is passive. Programming is active. The exercises are not
optional extras — they are where actual learning happens. Even if your first attempt is
wrong, the attempt itself teaches you something.

Use AI tools as a mentor, not a shortcut. If you're stuck, ask AI to help you understand. Ask it
to explain concepts differently. Ask it to trace through your code with you. But don't ask it to
write your solutions — that would steal your learning from you.

Be patient with yourself. You are learning to think in a new way. That takes time. But every
page you read, every line of code you write, every error you debug — all of it is
compounding. Progress here is not linear. It feels slow until suddenly it feels fast.

You are capable of this. Not 'maybe' capable. Actually capable. The only version of
this journey that ends in failure is the one where you stop. As long as you keep going,
you are succeeding.

■ HOW TO READ THIS BOOK

Python Unleashed 2
Each chapter follows this structure:

● Concept Introduction — clear explanation without jargon

● Real-World Examples — connecting code to situations you know

● Code Walkthroughs — step-by-step code with comments

● Common Mistakes — the errors everyone makes, explained

● Mental Models — conceptual summaries to lock in understanding

● Exercises — practice, projects, and reflection

● AI Learning Tips — how to use AI tools as a learning partner

● Confidence Corner — encouragement grounded in reality

■ YOUR LEARNING ROADMAP

■ Week 1-2 Chapters 1-2: Foundations How computers think + Python basics

■ Week 3-4 Chapter 3: Logic Decisions, loops, conditions

Chapter 4-5: Data & Structures + problem solving


■ Week 5-6
Algorithms

■ Week 7-8 Chapter 6-7: Pandas & SQL Data manipulation at scale

■ Week 9-10 Chapter 8: Analytics Turning data into decisions

■ Week 11-12 Chapter 9: Capstone Build the complete application

Python Unleashed 3
TABLE OF CONTENTS

Chapter 1 How Computers Think

■ 1.1 The Biggest Misunderstanding About Programming

■ 1.2 What is Logic?

■ 1.3 What is an Algorithm?

■ 1.4 Why People Feel Underconfident

■ 1.5 Slow Thinking is Powerful Thinking

■ Exercises & Confidence Corner

Chapter 2 Python Basics

■ 2.1 Why Python?

■ 2.2 Variables — The Foundation of All Data

■ 2.3 Data Types

■ 2.4 Input and Output

■ 2.5 Operations

■ 2.6 Type Errors

■ Exercises & Confidence Corner

Chapter 3 Logic Building

■ 3.1 Decision Making — If, Elif, Else

■ 3.2 Comparison Operators

■ 3.3 Logical Operators

■ 3.4 Loops — For and While

■ 3.5 Indentation

■ Exercises & Confidence Corner

Chapter 4 Data Structures

■ 4.1 Lists — Ordered Collections

■ 4.2 List Slicing

■ 4.3 Sets — Unique Collections

Python Unleashed 4
■ 4.4 Dictionaries — Key-Value Mapping

■ 4.5 Nested Structures

■ 4.6 When to Use Which

■ Exercises & Confidence Corner

Chapter 5 Algorithms

■ 5.1 Functions — Packaging Your Logic

■ 5.2 Searching Algorithms

■ 5.3 Sorting Algorithms

■ 5.4 The Algorithm Design Process

■ Exercises & Confidence Corner

Chapter 6 Pandas

■ 6.1 The DataFrame

■ 6.2 Selecting Data

■ 6.3 Aggregation

■ 6.4 Creating New Columns

■ 6.5 Sorting and Ranking

■ 6.6 Handling Missing Data

■ Exercises & Confidence Corner

Chapter 7 SQL Thinking Through Pandas

■ 7.1 SQL Thinking vs. Code Thinking

■ 7.2 The Five Core SQL Operations

■ 7.3 Joining Data

■ 7.4 Building a Data Pipeline

■ Exercises & Confidence Corner

Chapter 8 Analytics Thinking

■ 8.1 The Analytical Question Framework

■ 8.2 Choosing the Right Metric

■ 8.3 Statistical Thinking

■ 8.4 Common Analytical Mistakes

Python Unleashed 5
■ 8.5 The Analytics Workflow

■ Exercises & Confidence Corner

Chapter 9 Cricket Analytics Platform

■ 9.1 System Architecture

■ 9.2 Data Design

■ 9.3 Complete Implementation

■ 9.4 Project Roadmap

■ 9.5 What You've Built

■ Exercises & Final Message

Python Unleashed 6
CHAPTER 1

How Computers Think


And Why You Already Know How

Before you write a single line of code, you need to understand something important: you already
think the way computers need you to. You just haven't been taught to recognise it yet. This
chapter will change that.

1.1 The Biggest Misunderstanding About Programming


Most beginners believe programming is about memorizing commands, functions, and
complicated syntax. That belief is completely wrong, and it's the reason so many people give up
before they even start. Programming is not about memory. Programming is about precision.

A computer is not intelligent. It is obedient. It will do exactly — and only exactly — what you tell it
to do. Not what you mean. Not what you imply. Only what you say, word for word, step for step.

■ How a Human Thinks ■ How a Computer Thinks

'Bring me some water' → They 'Bring me some water' → Error. What is


understand: get a glass, go to the tap, fill 'bring'? What is 'water'? Where is the
it, bring it back. 'me'?

Humans fill in missing steps Computers require every step spelled out
automatically. explicitly.

Context and common sense guide No assumptions, no guesses, no


decisions. improvisation.

If something seems wrong, a human will If something is missing, it crashes or


ask or adapt. gives wrong output.

Programming is the art of removing assumptions. Every time you write code, you are saying:
'Here is the exact, unambiguous instruction for what I want.' And once you embrace that,
programming becomes logical rather than mysterious.

■ Real-World Example: Making Tea

Python Unleashed 7
Think about making tea. You instinctively know how to do it. But if you were instructing a
robot, you'd have to say: (1) Pick up kettle. (2) Walk to tap. (3) Turn tap clockwise. (4) Wait
until kettle is full. (5) Turn tap counterclockwise. (6) Carry kettle to stove. (7) Turn stove to
high. (8) Wait until water boils... Each step is precise. That's programming. You already know
the logic — you just haven't written it down before.

1.2 What is Logic? (You Already Have It)


Logic, in computing, means cause and effect. It means: IF this condition is true, THEN do this
action. You use this kind of thinking every single day without realising it.

Everyday Situation The Logic Behind It

It's raining outside IF raining → carry umbrella

IF balance < 500 → show 'Low Balance'


Your bank balance is low warning

IF marks > 40 → print 'Pass' ELSE print


Student scores marks 'Fail'

IF red → stop; IF green → go; IF yellow


Traffic signal changes → prepare

IF battery < 20% → show warning


Phone battery low notification

1.3 What is an Algorithm?


An algorithm sounds like a complicated, academic word. But here's the truth: you've been
creating algorithms your entire life. An algorithm is simply a clear, ordered sequence of steps
to solve a specific problem.

Python Unleashed 8
① START


② Identify the Problem


③ Break into Steps


④ Execute Each Step in Order


⑤ END — Problem Solved!

■ Diagram: Every algorithm follows the same basic flow — start, break down, execute, finish.

■ Real-World Example: Unlocking Your Phone

Algorithm to unlock your smartphone: Step 1 — Pick up phone. Step 2 — Press power button.
Step 3 — Look at screen (or place finger on sensor). Step 4 — IF face recognised / fingerprint
matched → go to home screen. Step 5 — IF not matched → ask for PIN. Step 6 — Enter PIN.
Step 7 — IF PIN correct → unlock. ELSE → show error. You just described a real algorithm
used in every smartphone on earth.

1.4 Why People Feel Underconfident (And Why That's Okay)


Here's something important that no one tells you: feeling underconfident when starting to
code is completely normal. It doesn't mean you are not smart enough. It doesn't mean
programming isn't for you. It simply means you are at the beginning of a learning curve.

Experts aren't smarter than you. They just practiced structured thinking for longer. Every person
you admire who codes fluently was once exactly where you are — confused, uncertain,
comparing themselves to others. The difference is they kept going.

■ Important Truth

The most dangerous comparison in learning is comparing your beginning to someone


else's middle. You see their polished results. You don't see the hundreds of hours of
confusion, errors, and small breakthroughs that got them there. Your only fair
comparison is with yourself yesterday.

Python Unleashed 9
1.5 Slow Thinking is Powerful Thinking
One of the most counterintuitive truths about programming is this: the slower you think, the
better you program. Speed comes from expertise. Expertise comes from clarity. And clarity
comes from slowing down.

When you slow down and think deliberately, you:

• See the steps you would otherwise skip over


• Understand why an error occurred instead of just feeling frustrated
• Build a mental model that you can apply to new problems
• Gain genuine confidence — not just memorised answers

■ AI Learning Tip

Use AI as your thinking partner, not your answer machine. When you're stuck, try typing your
problem to an AI tool like Claude or ChatGPT like this: 'I want to build an algorithm to find the
largest number in a list. Can you help me think through the steps before writing code?' Then
review the steps, question them, and understand each one. This trains your mind to think
algorithmically while still getting support.

■ Common Mistakes to Avoid

✗ Trying to learn programming by watching videos without practising — understanding


requires doing.

✗ Comparing your speed to experienced programmers — they had years of practice you
don't see.

✗ Giving up when you get an error — errors are the most important teachers in
programming.

✗ Thinking logic is 'natural talent' — it is a trained skill, exactly like driving or cooking.

✗ Rushing through basics to get to 'the interesting stuff' — basics are the interesting stuff.

■ Mental Model

✓ A computer is an obedient machine — it does exactly what you tell it, nothing more.

Python Unleashed 10
✓ An algorithm is just a recipe — clear, ordered steps to reach an outcome.

✓ Logic is cause-and-effect thinking — IF → THEN → ELSE.

✓ Programming removes assumptions — every step must be stated explicitly.

✓ Slow, clear thinking builds programming skill faster than rushed memorisation.

■ CHAPTER SUMMARY

✓ Programming is about precision, not memory — computers do exactly what you say.

✓ You already think logically — programming gives that thinking a formal structure.

✓ An algorithm is any clear, step-by-step solution to a problem.

✓ Feeling underconfident is normal and temporary — it is the beginning, not a verdict.

✓ Slow, deliberate thinking is the foundation of strong programming skill.

✓ AI tools can help you think — use them to build understanding, not replace it.

■ EXERCISES & PRACTICE

■ Quick Practice 1: Algorithm Writing

Write a step-by-step algorithm for any ONE of these:

a) Making instant noodles

b) Withdrawing money from an ATM

c) Booking a movie ticket online

Remember: Be as explicit as possible. Assume your reader knows NOTHING.

■ Hint: Aim for at least 8-10 clear steps.

■ Logic Challenge 2: If-Then Mapping

Python Unleashed 11
For each situation below, write the IF-THEN-ELSE logic:

1. A student scores marks in an exam (passing mark is 40)

2. An e-commerce site checks if an item is in stock

3. A bank checks if a user can withdraw money (sufficient balance needed)

Format: IF [condition] → THEN [action] ELSE [action]

■ Reflection Exercise 3: Your Learning Mindset

Write your honest answers (there are no wrong answers):

1. What is one thing about programming that makes you feel uncertain right now?

2. Think of something you learned slowly but eventually mastered. What helped you?

3. What would you tell a version of yourself from 6 months ago about learning new things?

This reflection will help you understand your own learning patterns.

■ Mini Project 4: Design Your Day as an Algorithm

Describe your entire morning routine from waking up to leaving home as an algorithm.

Requirements:

✓ Must include at least one IF-THEN decision

✓ Must include at least one repetitive action (loop)

✓ Must be precise enough that a robot could follow it

Bonus: Identify which step would be hardest to explain to a machine and explain why.

★ CONFIDENCE CORNER

Python Unleashed 12
You've just completed Chapter 1, and here's what that means: you now understand the
fundamental philosophy of programming. Most people who 'know how to code' never
consciously understood what you just read. They learned by doing but couldn't explain
why it works. You already have something valuable — the mental framework. Everything
from here is just building on this foundation. You are not behind. You are exactly where
you need to be.

Python Unleashed 13
CHAPTER 2

Python Basics
Speaking Clearly to a Machine

Python is your first real tool for turning logical thinking into something a computer can execute. It
was designed to be readable, almost like writing in English — but with very specific grammar
rules. In this chapter, you will learn the foundational building blocks of Python: variables, data
types, input/output, and basic operations.

2.1 Why Python?


Python is one of the most popular programming languages in the world — used by Google,
NASA, Netflix, and thousands of data companies. But what makes it perfect for beginners is its
readability. Compare these two programs that both print 'Hello World':

Java (more complex) Python (clear & simple)

public class Hello { print("Hello World")

public static void main(

String[] args) { That's it. One line.

[Link](

"Hello World");

Python's philosophy: code should be easy to read, easy to write, and easy to understand. This
doesn't make it less powerful — it makes it more powerful because you can focus on solving
problems instead of fighting with syntax.

2.2 Variables — The Foundation of All Data


A variable is how you store information in a program. Think of it as a labelled box where you put
a piece of data. The label is the variable name. The content is the value.

Python Unleashed 14
■ Real-World Example: Labelled Envelopes

Imagine you have three envelopes on your desk. You write 'Savings', 'Rent', and 'Groceries'
on them. Each envelope holds a specific amount of money. In Python: savings = 15000, rent
= 8000, groceries = 3000. The envelope label is the variable name. The money inside is the
value. You can open any envelope (use the variable), check how much is inside (read the
value), or change the amount (update the value).

# Creating variables

name = 'Priya' # Stores a name (text)

age = 24 # Stores an age (whole number)

height = 5.6 # Stores height (decimal number)

is_student = True # Stores yes/no information

# Using variables

print(name) # Output: Priya

print(age) # Output: 24

# Updating variables

age = age + 1 # Birthday! Now age is 25

print(age) # Output: 25

Variable Naming Rules


Variable names in Python must follow these rules:

&#10003; Can contain Letters, numbers, underscores → player_name, score1, total_runs

&#10007; Cannot start with A number → 1score is INVALID

&#10007; Cannot be Python keywords → if, for, while, True are INVALID as variable names

&#10003; Case sensitive Score and score are DIFFERENT variables

&#10003; Best practice Use descriptive names → total_runs, not tr or x

2.3 Data Types — Understanding the Nature of Information


Not all data is the same. The number 25 is different from the text '25'. Python uses data types to
understand what kind of data it's working with and what operations make sense.

Python Unleashed 15
Type What It Stores Examples Real-World Use

int Whole numbers 10, -5, 0, 1000 Age, score, quantity

floa
t Decimal numbers 3.14, 99.5, -0.7 Height, price, average

Text (any
str characters) 'Hello', 'Virat' Name, address, message

True or False
bool only True, False Is_logged_in, is_available

# Type examples

player_name = 'Rohit' # str

runs_scored = 145 # int

strike_rate = 87.5 # float

is_captain = True # bool

# Checking the type

print(type(runs_scored)) # Output: <class 'int'>

print(type(strike_rate)) # Output: <class 'float'>

print(type(player_name)) # Output: <class 'str'>

2.4 Input and Output — Creating Interaction


A program that can't communicate with users is a dead program. Python gives you two
fundamental tools: input() to receive data from a user, and print() to display results. These two
functions are your communication bridge.

# Taking input from user

name = input('Enter your name: ')

age = input('Enter your age: ')

# Note: input() ALWAYS returns a string!

# To use age as a number, convert it:

Python Unleashed 16
age = int(age) # Convert string to integer

# Output with print()

print('Hello,', name) # Multiple values

print(f'You are {age} years old.') # f-string (modern way)

print(f'In 5 years you will be {age + 5}.') # Math inside f-string

■ Real-World Example: Bank ATM Interface

Every ATM uses basic input/output. It asks: 'Enter your PIN' (input). Then it shows: 'Your
balance is ■15,000' (output). If you withdraw ■2,000, it calculates the new balance and prints
the receipt (more output). Every interaction on every digital device uses this fundamental
pattern — ask, process, respond.

2.5 Operations — Making Python Calculate


Python supports all standard mathematical operations. More importantly, it can perform complex
calculations instantly:

Operation Symbol Example Result

Addition + 100 + 50 150

Subtraction - 1000 - 250 750

Multiplication * 200 * 3 600

Division / 100 / 4 25.0

Floor Division // 100 // 3 33 (no decimals)

Modulus (Remainder) % 10 % 3 1 (remainder)

Power/Exponent ** 2 ** 8 256

# Real example: Shopping bill calculator

price_per_item = 250 # Price of one item in rupees

quantity = 4 # Number of items

discount_percent = 10 # 10% discount

Python Unleashed 17
subtotal = price_per_item * quantity # 1000

discount = subtotal * discount_percent / 100 # 100

total = subtotal - discount # 900

print(f'Subtotal: Rs.{subtotal}')

print(f'Discount: Rs.{discount}')

print(f'You pay: Rs.{total}')

2.6 Type Errors — Learning from Mistakes


Python is strict about data types. If you try to mix incompatible types, it will show you an error.
This is not punishment — it's protection. The computer is telling you 'I don't know how to do this
with the data you gave me.'

# This causes a TypeError:

# result = "5" + 5 # Cannot add string and number

# Fix it by converting types:

result = int("5") + 5 # Convert string to int first

print(result) # Output: 10

# Or use str() to join text:

message = "Score: " + str(145)

print(message) # Output: Score: 145

■ Common Mistakes to Avoid

✗ Forgetting to convert input() to int or float when doing math — input() always returns a
string.

✗ Using = (assignment) instead of == (comparison) in conditions — a very common


mistake.

✗ Variable names with spaces → first name is INVALID; use first_name instead.

✗ Printing a variable before assigning it — Python doesn't know what to print.

Python Unleashed 18
✗ Using wrong quotes — Python accepts both single and double quotes, but they must
match.

■ Mental Model

✓ Variables are labelled boxes — name them clearly so you (and others) understand
them.

✓ Every value has a type — int, float, str, bool. The type determines what you can do with
it.

✓ input() always gives you a string — convert it with int() or float() for math.

✓ print() is your voice to the user — f-strings make it easy to format messages.

✓ Errors are not failures — they are Python trying to help you understand the problem.

■ CHAPTER SUMMARY

✓ Python is readable, powerful, and perfect for beginners and professionals alike.

✓ Variables store information with a name and a value — like labelled envelopes.

✓ Data types (int, float, str, bool) define what kind of information is stored.

✓ input() receives data; print() displays it — creating user interaction.

✓ Python supports all standard math operations, including special ones like // and %.

✓ Type errors are common but meaningful — they tell you exactly what needs fixing.

■ EXERCISES & PRACTICE

■ Quick Practice 1: Variable Creation

Create variables for a cricket player profile. Include:

✓ Player name (string)

✓ Age (integer)

Python Unleashed 19
✓ Batting average (float)

✓ Is_captain (boolean)

✓ Country (string)

Then print a formatted summary using f-strings.

Bonus: Ask the user to enter the player's name using input().

■ Applied Project 2: Simple Bill Calculator

Build a bill calculator program that:

1. Asks the user for item name, price, and quantity

2. Calculates the subtotal (price × quantity)

3. Applies an 18% GST tax

4. Prints a formatted receipt with all values

Sample output: 'Item: Notebook | Qty: 3 | Price: 80 | GST: 43.20 | Total: 283.20'

■ Logic Challenge 3: Type Conversion Practice

What will each of these print? (Try to answer before running):

a) print(type(3.0))

b) print(int(9.9))

c) print(str(100) + "200")

d) print(float("3.14") + 1)

Explain in your own words why each answer is what it is.

■ AI Learning Tip

Python Unleashed 20
When you get an error in Python, copy the entire error message and paste it into an AI
assistant. Ask: 'I got this error in Python. Explain what it means in simple words and tell me
how to fix it.' AI tools are incredibly good at decoding error messages. Over time, you'll start
recognising these patterns yourself — that's when you know you're growing as a
programmer.

★ CONFIDENCE CORNER

You've just learned the building blocks of every Python program ever written. Variables,
data types, input, output, operations — these are the same fundamentals that
professional developers use every single day. The rest of programming is just combining
these blocks in increasingly clever ways. You have the foundation. What comes next is
just building up.

Python Unleashed 21
CHAPTER 3

Logic Building
Learning to Think in Decisions and Patterns

Logic is the heart of programming. Every application you have ever used — from Instagram to
Google Search — runs on chains of logical decisions. In this chapter, you will learn how to make
Python think: how to handle decisions, combine conditions, and repeat actions. These three
skills — decisions, combinations, repetition — are the entire foundation of computing logic.

3.1 Decision Making — If, Elif, and Else


The if statement is Python's way of making decisions. It evaluates whether a condition is True or
False, and takes different actions accordingly.

START

Evaluate Condition (marks > 40?) TRUE → print("Pass")

FALSE ↓

print("Fail")

■ Decision Flow: Python evaluates the condition and takes the matching path.

# Simple if-else

marks = 67

if marks >= 40:

print("Pass — well done!")

else:

print("Fail — keep trying!")

# Multi-level: if-elif-else

if marks >= 90:

print("Grade A — Excellent!")

Python Unleashed 22
elif marks >= 75:

print("Grade B — Good work!")

elif marks >= 60:

print("Grade C — Above average")

elif marks >= 40:

print("Grade D — Just passing")

else:

print("Fail — Review needed")

■ Real-World Example: E-commerce Discount System

Every online shopping platform has a discount logic: IF total_purchase >= 5000 THEN apply
15% discount. ELIF total_purchase >= 2000 THEN apply 10% discount. ELIF total_purchase
>= 1000 THEN apply 5% discount. ELSE no discount. Python's if-elif-else structure maps
exactly to this kind of business rule. You've used this logic as a shopper — now you know
how to build it as a programmer.

3.2 Comparison Operators — The Language of Conditions


Conditions in Python use comparison operators to evaluate relationships between values:

Operator Meaning Example Result

== Equal to 5 == 5 True

!= Not equal to 5 != 3 True

> Greater than 10 > 5 True

< Less than 3 < 10 True

>= Greater than or equal 5 >= 5 True

<= Less than or equal 4 <= 3 False

3.3 Logical Operators — Combining Multiple Conditions

Python Unleashed 23
Real-world decisions often involve multiple conditions at once. Python handles this with logical
operators: and, or, and not.

# AND: Both conditions must be True

age = 21

has_id = True

if age >= 18 and has_id == True:

print("Entry allowed")

else:

print("Entry denied")

# OR: At least one condition must be True

is_member = False

has_coupon = True

if is_member or has_coupon:

print("Discount applied")

# NOT: Reverses the condition

is_raining = False

if not is_raining:

print("No umbrella needed")

■ Real-World Example: Stadium Entry Check

To enter a cricket stadium: You need BOTH a valid ticket AND a valid ID (AND condition).
The ticket app might give you free upgrade if you're a premium member OR if you have
3000+ loyalty points (OR condition). The entry gate checks if your account is NOT blocked
(NOT condition). These exact same operators control every app's permission and access
system.

3.4 Loops — Automating Repetition


Loops are one of the most powerful ideas in programming. They allow you to execute a block of
code multiple times without writing it multiple times. Imagine needing to print 1,000 student

Python Unleashed 24
names — you don't write 1,000 print statements. You write a loop that does it for you.

The For Loop — When You Know the Count


# Basic for loop

for i in range(5):

print(i) # Prints: 0, 1, 2, 3, 4

# range(start, stop, step)

for i in range(1, 11, 2):

print(i) # Prints: 1, 3, 5, 7, 9 (odd numbers)

# Looping over a list

players = ['Virat', 'Rohit', 'Dhoni', 'Jadeja']

for player in players:

print(f'Player: {player}')

# Practical: Sum of first 10 numbers

total = 0

for i in range(1, 11):

total = total + i

print(f'Sum: {total}') # Output: Sum: 55

The While Loop — When You Wait for a Condition


# While loop: runs as long as condition is True

balance = 5000

withdrawal = 1000

while balance >= withdrawal:

balance = balance - withdrawal

print(f'Withdrew {withdrawal}. Remaining: {balance}')

print('Insufficient balance. Stopping.')

Python Unleashed 25
# User input validation loop

password = ''

while password != 'python123':

password = input('Enter password: ')

print('Access granted!')

■ Real-World Example: OTP Verification

Every time you log into an app and it gives you a 3-attempt OTP limit, that's a while loop:
WHILE attempts_remaining > 0 AND otp_not_verified: ask for OTP, IF correct → unlock,
ELSE decrease attempts_remaining by 1. FOR each failed attempt: show 'X attempts left'.
This same pattern handles bank PIN retries, login attempts, and quiz answer checking.

3.5 Indentation — Python's Non-Negotiable Rule


In Python, indentation is not optional styling — it's part of the language syntax. Python uses
indentation to know which code belongs inside an if, for, or while block. Always use 4 spaces (or
one Tab) consistently.

# CORRECT: Consistent 4-space indentation

for i in range(3):

print(i) # This is INSIDE the loop

print('Done') # This is OUTSIDE the loop

# WRONG: Inconsistent indentation causes IndentationError

# for i in range(3):

# print(i) # 2 spaces

# print('hi') # 4 spaces - MISMATCH ERROR!

■ Common Mistakes to Avoid

✗ Using = instead of == in conditions (age = 18 assigns; age == 18 compares).

✗ Wrong indentation — Python will throw IndentationError and your code won't run.

✗ Infinite while loops — always make sure the condition eventually becomes False.

Python Unleashed 26
✗ Off-by-one errors — range(5) gives 0 to 4, not 1 to 5. range(1,6) gives 1 to 5.

✗ Forgetting the colon (:) after if, elif, else, for, while — Python requires it.

■ Mental Model

✓ if-elif-else is Python's decision tree — one path chosen based on conditions.

✓ for loops are for known repetitions — use when you know how many times to repeat.

✓ while loops are for unknown repetitions — use when repeating until something changes.

✓ Indentation defines code blocks in Python — it's structural, not cosmetic.

✓ Logical operators (and, or, not) let you combine multiple conditions cleanly.

■ CHAPTER SUMMARY

✓ if, elif, else allow Python to make decisions based on conditions.

✓ Comparison operators (==, !=, >, <, >=, <=) compare values to produce True/False.

✓ Logical operators (and, or, not) combine multiple conditions.

✓ for loops repeat a fixed number of times; while loops repeat until a condition fails.

✓ Indentation is mandatory in Python — it defines what belongs inside each block.

✓ Every real-world application is built on these decision and repetition patterns.

■ EXERCISES & PRACTICE

■ Quick Practice 1: Grade Calculator

Write a Python program that:

1. Asks user for their marks (0–100)

2. Prints the grade: A (90+), B (75-89), C (60-74), D (40-59), Fail (below 40)

Python Unleashed 27
3. Also prints 'Distinction' if marks are 95 or above

Test your program with: 95, 78, 55, 35

■ Applied Project 2: Multiplication Table Generator

Write a program that:

1. Asks the user for a number

2. Prints its complete multiplication table (1 to 12)

3. Highlights (adds '**') multiples that are greater than 50

Sample: '7 x 8 = 56 **'

■ Logic Challenge 3: Even/Odd Finder with Loop

Write a program that:

1. Loops through numbers 1 to 20

2. Prints 'X is even' or 'X is odd' for each number

3. At the end, prints total count of even and odd numbers

Hint: Use the modulus operator (%) — if number % 2 == 0, it's even.

■ Mini Project 4: Number Guessing Game

Build a number guessing game:

1. Program picks a 'secret number' (just assign it: secret = 42)

2. User has 5 attempts to guess it

3. Each wrong guess: print 'Too high' or 'Too low'

4. If correct: print 'You got it in X attempts!'

5. If all 5 used: print 'Game over! The number was 42'

Python Unleashed 28
This uses: variables, while loop, if-elif-else, comparison operators.

■ AI Learning Tip

When you're stuck on logic, describe your problem to an AI in plain English. For example: 'I
want to write a Python program that keeps asking the user for a password until they enter the
correct one. After 3 wrong attempts, it should lock them out for 30 seconds. Help me write the
pseudocode first.' AI can help you plan the logic BEFORE you write code — which is exactly
the right order to work in.

★ CONFIDENCE CORNER

Logic building is not a talent you're born with — it is a muscle you develop with every
problem you solve. If a logic problem felt confusing today, that's not a sign of failure. It's a
sign your brain is building new pathways. Every time you work through an if statement or
a loop — even if you need to look things up — you are strengthening your logical muscle.
The experts you admire didn't get there by being naturally brilliant. They got there by
solving one small problem, then another, then another. You're already doing it.

Python Unleashed 29
CHAPTER 4

Data Structures
Organising Information Intelligently

Data is everywhere. But raw, unorganised data is like a room where everything is thrown on the
floor — technically all there, but nearly impossible to use efficiently. Data structures are Python's
way of giving information a home, a structure, and a purpose. In this chapter you'll master three
essential structures: Lists, Sets, and Dictionaries.

4.1 Lists — Ordered Collections


A list is Python's most versatile data structure. It holds multiple values in a single variable, in a
specific order. You can think of it as a numbered shelf — each item has a fixed position (called
an index), starting from 0.

Index: 0 1 2 3

Value: 'Milk' 'Bread' 'Eggs' 'Sugar'

■ List Diagram: items[0] = 'Milk', items[1] = 'Bread', etc. Indexing always starts at 0.

# Creating a list

scores = [85, 92, 67, 78, 55]

# Accessing elements (index starts at 0)

print(scores[0]) # 85 (first element)

print(scores[-1]) # 55 (last element, negative index)

# Modifying elements

scores[2] = 71 # Change 67 to 71

# Adding elements

[Link](88) # Add to end

[Link](0, 95) # Add at position 0

Python Unleashed 30
# Removing elements

[Link](55) # Remove first occurrence of 55

last = [Link]() # Remove and return last element

# Useful list operations

print(len(scores)) # Number of items

print(max(scores)) # Highest value

print(min(scores)) # Lowest value

print(sum(scores)) # Sum of all values

[Link]() # Sort in ascending order

[Link](reverse=True) # Sort in descending order

■ Real-World Example: Cricket Scorecard

A cricket scorecard is a perfect list: runs_per_over = [6, 4, 8, 12, 3, 7, 10, 5]. Over 1 scored 6
runs (index 0), Over 2 scored 4 runs (index 1), and so on. You can find the highest-scoring
over with max(runs_per_over), calculate total runs with sum(runs_per_over), sort the overs by
performance, and track the run rate over time. Streaming sports apps do exactly this to
display real-time analytics.

4.2 List Slicing — Extracting Specific Portions


Slicing lets you extract a portion of a list using the syntax list[start:end:step]. This is incredibly
powerful for data analysis work.

players = ['Virat', 'Rohit', 'Dhoni', 'Jadeja', 'Bumrah', 'Shami']

print(players[0:3]) # ['Virat', 'Rohit', 'Dhoni'] (index 0,1,2)

print(players[2:]) # From index 2 to end

print(players[:3]) # First 3 elements

print(players[::2]) # Every second element

print(players[::-1]) # Reversed list

4.3 Sets — Unique Collections

Python Unleashed 31
A set stores only unique values. If you add a duplicate, it is automatically ignored. Sets are
unordered — they don't care about position. Their superpower is speed: checking if something
exists in a set is extremely fast.

# Creating a set — duplicates are removed automatically

visitors = {'Rahul', 'Priya', 'Rahul', 'Amit', 'Priya', 'Sneha'}

print(visitors) # {'Rahul', 'Priya', 'Amit', 'Sneha'} — no duplicates!

# Adding and removing

[Link]('Karan')

[Link]('Amit') # Remove without error if not present

# Set operations (like Venn diagrams)

team_a = {'Virat', 'Rohit', 'Dhoni'}

team_b = {'Rohit', 'Bumrah', 'Dhoni'}

print(team_a & team_b) # Intersection: {'Rohit', 'Dhoni'} (in both)

print(team_a | team_b) # Union: all players combined

print(team_a - team_b) # Difference: only in team_a

■ Real-World Example: Unique Website Visitors

Analytics tools like Google Analytics track unique visitors using sets. Even if you visit a
website 10 times today, you count as 1 unique visitor. The system maintains a set of user IDs
— when you visit, it adds your ID. Sets automatically ignore duplicates. This exact same logic
applies to unique voters in an election, unique SKUs in a warehouse, and unique hashtags on
social media.

4.4 Dictionaries — Key-Value Mapping


A dictionary stores data as key-value pairs. Think of a real dictionary: you look up a word (the
key) and find its meaning (the value). In Python, a dictionary lets you map any key to any value,
making it perfect for structured records.

Key (Look Up By) Value (What You Find)

'name' 'Rohit Sharma'

Python Unleashed 32
'age' 36

'runs' 10000

'is_captain' True

'country' 'India'

■ Dictionary Diagram: Key → Value mapping. Access any value instantly by its key.

# Creating a dictionary

player = {

'name': 'Rohit Sharma',

'runs': 10000,

'matches': 250,

'average': 48.6

# Accessing values

print(player['name']) # Rohit Sharma

print([Link]('runs')) # 10000 (safe — no error if key missing)

# Adding and updating

player['centuries'] = 29 # Add new key

player['matches'] = 253 # Update existing key

# Looping through a dictionary

for key, value in [Link]():

print(f'{key}: {value}')

# Check if key exists

if 'average' in player:

print(f"Average: {player['average']}")

4.5 Nested Structures — Real Data Gets Complex

Python Unleashed 33
In the real world, data is rarely flat. A cricket team has players. Each player has multiple stats.
Python handles this with nested structures — lists inside dictionaries, dictionaries inside lists,
and any combination you need.

# List of dictionaries (most common real-world pattern)

squad = [

{'name': 'Virat', 'runs': 8250, 'average': 58.5},

{'name': 'Rohit', 'runs': 7890, 'average': 47.2},

{'name': 'Dhoni', 'runs': 4950, 'average': 50.6},

# Access nested data

print(squad[0]['name']) # 'Virat' (first player's name)

print(squad[1]['average']) # 47.2 (second player's average)

# Loop through all players

for player in squad:

print(f"{player['name']}: {player['runs']} runs")

# Find highest scorer

top_scorer = max(squad, key=lambda p: p['runs'])

print(f"Top scorer: {top_scorer['name']}")

4.6 When to Use Which Structure


Structure Use When... Example Use Case

List [ ] Order matters, duplicates allowed, Scorecard, ranked results,


position-based access needed sequence of events

Set { } Only unique values matter, fast Unique visitors, voted IDs,
membership testing needed unique tags

Dictionar Need to look up values by a label, Player profile, product catalog,


y { : } structured record storage config settings

Python Unleashed 34
■ Common Mistakes to Avoid

✗ Using list when dictionary is better — if you're searching by name, use a dict, not index.

✗ Confusing list index (items[0]) with dictionary key (player['name']) — very different.

✗ Forgetting that set is unordered — don't rely on position in a set.

✗ Using mutable types (like lists) as dictionary keys — only use strings, numbers, or tuples.

✗ Modifying a list while looping over it — can cause unexpected skipping of items.

■ Mental Model

✓ List = numbered shelf — ordered, indexed, allows duplicates.

✓ Set = ballot box — only unique entries, no position, fast checking.

✓ Dictionary = contact book — look up by name (key), find details (value).

✓ Nested structures = real-world records — list of dicts is the most common data pattern.

✓ Always ask: Do I need order? Do I need uniqueness? Do I need lookup by name?

■ CHAPTER SUMMARY

✓ Lists store ordered, indexed, changeable sequences — use for collections where
position matters.

✓ Sets store only unique values — use for deduplication and fast membership checking.

✓ Dictionaries map keys to values — use for structured records and label-based lookup.

✓ Nested structures (list of dicts) are the standard pattern for real-world data.

✓ Choosing the right data structure makes your code faster, cleaner, and more logical.

■ EXERCISES & PRACTICE

■ Quick Practice 1: Cricket Squad Manager

Python Unleashed 35
Create a list of 5 cricket players (just their names). Then:

1. Print the first and last player

2. Add a new player at position 2

3. Remove a player by name

4. Sort the list alphabetically

5. Print the total number of players remaining

■ Applied Project 2: Player Profile System

Create dictionaries for 3 cricket players. Each must have:

name, runs, matches, average, is_allrounder (boolean)

Then write code to:

1. Print all profiles in a formatted way

2. Find the player with the highest average

3. Count how many are all-rounders

4. Calculate team's total runs

■ Set Challenge 3: Unique Visitors

Simulate a website visitor tracker:

1. Create a set called 'visitors_today'

2. Add 10 visitor IDs (include some duplicates!)

3. Print the number of unique visitors

4. Check if a specific ID 'USER_007' visited

5. Find visitors who came both yesterday AND today (create two sets, find intersection)

Python Unleashed 36
★ CONFIDENCE CORNER

Data structures are what separate 'someone who wrote a script' from 'someone who can
build a real application'. By mastering lists, sets, and dictionaries, you've just gained the
ability to model and organise information the way professional developers do every day.
You're no longer just printing values — you're structuring data. That's a significant jump,
and you just made it.

Python Unleashed 37
CHAPTER 5

Algorithms
Learning to Think Smart, Not Just Hard

An algorithm is not a mysterious mathematical concept. It's an organised, step-by-step approach


to solving a problem. What separates a good programmer from a great one isn't knowing more
syntax — it's having better algorithms. Better algorithms mean less time, less computation, and
cleaner solutions.

5.1 Functions — Packaging Your Logic


Before we explore algorithms, you need one more tool: functions. A function is a named block
of reusable code. Instead of writing the same logic 10 times, you write it once as a function and
call it whenever needed.

# Defining a function

def greet_player(name):

message = f'Welcome, {name}! Ready to play?'

return message

# Calling the function

print(greet_player('Virat')) # Welcome, Virat! Ready to play?

print(greet_player('Rohit')) # Welcome, Rohit! Ready to play?

# Function with multiple parameters and default value

def calculate_average(runs, matches, minimum_matches=5):

if matches < minimum_matches:

return 'Not enough matches'

return runs / matches

print(calculate_average(500, 10)) # 50.0

print(calculate_average(100, 2)) # Not enough matches

Python Unleashed 38
■ Real-World Example: Calculator App

When you press '=' on a calculator app, it calls a function. The function receives your
numbers and operation as parameters, computes the result, and returns it for display. Every
button on your phone's keyboard calls a function. Every payment on an app calls a function.
Functions are the invisible workers that make every application run.

5.2 Searching Algorithms — Finding Information


Searching is the most fundamental operation in computing. Every time you search for something
— a product on Amazon, a contact on your phone, a student record — an algorithm is at work.
There are two foundational search strategies:

Linear Search — Check Everything


def linear_search(data, target):

for index, value in enumerate(data):

if value == target:

return index # Found! Return position

return -1 # Not found

scores = [45, 78, 23, 91, 56, 34, 88]

position = linear_search(scores, 91)

print(f'Found 91 at index: {position}') # Found 91 at index: 3

# Real use: Search player by name

players = ['Virat', 'Rohit', 'Dhoni', 'Jadeja']

result = linear_search(players, 'Dhoni')

print(f'Dhoni found at position: {result}') # 2

Linear search performance: In the worst case, it checks every single item. With 1,000 items it
does 1,000 checks. With 1,000,000 items it does 1,000,000 checks. This is fine for small data but
becomes slow at scale.

Binary Search — Search Smarter (Sorted Data Required)

Python Unleashed 39
Binary search is dramatically faster. The key idea: if your data is sorted, you can eliminate half
the remaining possibilities with each check.

Data: [10, 23, 34, 45, 56, 78, 88, 91] Target: 78

Step 1: Check middle element → 45. Is 78 > 45? YES → Search RIGHT half only.

Step 2: New list: [56, 78, 88, 91]. Middle = 78. Found! ✓

Result: Found 78 in just 2 steps instead of 7 (linear would check each).

def binary_search(sorted_data, target):

left = 0

right = len(sorted_data) - 1

while left <= right:

mid = (left + right) // 2

if sorted_data[mid] == target:

return mid # Found!

elif sorted_data[mid] < target:

left = mid + 1 # Target is in right half

else:

right = mid - 1 # Target is in left half

return -1 # Not found

sorted_scores = [10, 23, 34, 45, 56, 78, 88, 91]

print(binary_search(sorted_scores, 78)) # Output: 5

5.3 Sorting Algorithms — Organising Data for Efficiency


Sorting is the act of arranging data in a specific order. It's everywhere: leaderboards, product
price rankings, search engine results. Understanding sorting builds your algorithm thinking.

Bubble Sort — Understanding the Logic


def bubble_sort(data):

Python Unleashed 40
n = len(data)

for i in range(n):

for j in range(0, n - i - 1):

if data[j] > data[j + 1]: # Wrong order?

data[j], data[j+1] = data[j+1], data[j] # Swap!

return data

scores = [64, 34, 25, 12, 22, 11, 90]

print(bubble_sort(scores)) # [11, 12, 22, 25, 34, 64, 90]

# Python's built-in sort is optimised — always use this in practice:

[Link]() # Ascending

[Link](reverse=True) # Descending

[Link](key=lambda p: p['runs']) # Sort dicts by a key

5.4 The Algorithm Design Process


Professional programmers don't sit down and immediately write code. They follow a structured
thinking process. Here's the process you should adopt for every problem:

Understand the Problem


① What exactly is the input? What exactly should the output be? Don't guess.

Identify Examples
② Work through 2-3 concrete examples by hand before writing code.

Break Into Steps


③ Write pseudocode — plain English steps of your solution.

Code the Solution


④ Translate your pseudocode into Python, one step at a time.

Python Unleashed 41
Test Edge Cases
⑤ What if the list is empty? What if input is zero? What if there are duplicates?

Refine
⑥ Is there a simpler or faster way? Could you write this as a function?

# Example: Find the average of a list of scores

# Step 1 - Understand: Input=list of numbers, Output=single average


number

# Step 2 - Example: [80, 90, 70] → average = (80+90+70)/3 = 80.0

# Step 3 - Pseudocode: sum all numbers, divide by count

# Step 4 - Code:

def calculate_average(scores):

if len(scores) == 0: # Step 5: Edge case — empty list

return 0

total = sum(scores)

count = len(scores)

return round(total / count, 2) # Round to 2 decimal places

print(calculate_average([80, 90, 70])) # 80.0

print(calculate_average([])) # 0 (handles edge case)

■ Common Mistakes to Avoid

✗ Jumping to code before understanding the problem — always think first, code second.

✗ Not testing edge cases — empty lists, zero values, and duplicates break many
algorithms.

✗ Writing functions that do too many things — each function should do ONE thing well.

✗ Forgetting return statements — a function without return gives None back.

✗ Using inefficient algorithms on large data — always consider scale in your thinking.

Python Unleashed 42
■ Mental Model

✓ Functions are reusable logic boxes — define once, use everywhere.

✓ Linear search: simple but slow. Binary search: fast but needs sorted data.

✓ Sorting is fundamental — sorted data enables faster searching and better analysis.

✓ Always: Understand → Example → Pseudocode → Code → Test → Refine.

✓ Edge cases (empty, zero, duplicate) are where algorithms succeed or fail.

■ CHAPTER SUMMARY

✓ Functions package logic into reusable blocks — they make code clean and scalable.

✓ Linear search checks every item; binary search eliminates half each time (requires
sorted data).

✓ Sorting arranges data for easier comparison and faster searching.

✓ The algorithm design process: Understand → Example → Pseudocode → Code → Test


→ Refine.

✓ Good algorithms solve problems efficiently — with less time and less computation.

✓ Edge cases are non-negotiable — always test your algorithm with unusual inputs.

■ EXERCISES & PRACTICE

■ Quick Practice 1: Function Writing

Write these functions:

a) is_even(n) — returns True if n is even, False otherwise

b) find_max(numbers) — returns the largest number in a list (without using max())

c) count_above(numbers, threshold) — counts items greater than threshold

Python Unleashed 43
Test each with at least 3 different inputs.

■ Applied Project 2: Student Ranking System

Build a student ranking system:

1. Create a list of 8 students (name + score as dictionaries)

2. Sort them by score (highest first)

3. Print a leaderboard with rank numbers

4. Find and print: highest score, lowest score, class average

5. Print names of all students who scored above the class average

All logic should be inside clearly named functions.

■ Algorithm Challenge 3: Search Implementation

Implement linear_search() that returns the INDEX of a target or -1 if not found.

Test it on: a list of 10 numbers, searching for both present and absent values.

Then: sort the same list and implement binary_search().

Compare: how many 'steps' does each algorithm take to find the same value?

Bonus: Add a step_counter variable to each function to count comparisons made.

■ Capstone Mini-Project 4: Tournament Score Analyser

Given: scores = [45, 78, 92, 56, 88, 71, 63, 84, 91, 39]

Write functions to:

1. find_winner() — highest score

2. calculate_average() — mean score

3. find_above_average() — list of above-average scores

Python Unleashed 44
4. rank_players() — return sorted list from highest to lowest

5. generate_report() — prints a formatted analysis summary

This is a mini data analysis project!

■ AI Learning Tip

When you can't figure out why your algorithm isn't working, paste your code to an AI and ask:
'Walk me through what happens when this function receives [specific input]. At what step
does it go wrong?' The AI will trace through the execution step by step. This teaches you to
'trace' code mentally — one of the most important debugging skills a programmer can
develop.

★ CONFIDENCE CORNER

Algorithms are where beginners often feel the most intimidated — and where they
discover their biggest breakthroughs. If any of these concepts felt difficult today, that's
expected. Algorithm thinking is a skill that compounds over time. Every problem you
solve makes the next one easier. You're not learning to memorise algorithms — you're
training your mind to think systematically. That mindset is transferable to every problem
you will ever face, in programming and beyond.

Python Unleashed 45
CHAPTER 6

Pandas
Learning to Think in Data at Scale

Until now, you've worked with small amounts of data — a list of 10 scores, a dictionary of 5
players. But the real world doesn't give you 10 rows. It gives you 10,000 — or 10 million. Pandas
is Python's most powerful library for working with structured data at any scale. Think of it as
Excel inside Python, but infinitely more powerful and programmable.

6.1 The DataFrame — Your New Best Friend


The central object in Pandas is the DataFrame — essentially a table with labelled rows and
columns. Every row is a record. Every column is a category of information.

Index Name Runs Balls Matches Average

0 Virat 8250 9800 220 58.5

1 Rohit 7890 10100 250 47.2

2 Jadeja 2300 2800 180 32.8

3 Bumrah 450 600 120 10.2

■ DataFrame Diagram: Rows = records (players), Columns = attributes. Like a spreadsheet.

import pandas as pd

# Create a DataFrame from a list of dictionaries

data = [

{'Name': 'Virat', 'Runs': 8250, 'Balls': 9800, 'Matches': 220},

{'Name': 'Rohit', 'Runs': 7890, 'Balls': 10100, 'Matches': 250},

{'Name': 'Jadeja', 'Runs': 2300, 'Balls': 2800, 'Matches': 180},

df = [Link](data)

Python Unleashed 46
# Or load from a CSV file

df = pd.read_csv('cricket_data.csv')

# First look at your data

print([Link]()) # First 5 rows

print([Link](3)) # Last 3 rows

print([Link]) # (rows, columns) e.g., (3, 4)

print([Link]) # List of column names

print([Link]) # Data type of each column

print([Link]()) # Statistical summary (mean, min, max...)

6.2 Selecting Data — Asking Questions Column by Column


# Select a single column (returns a Series)

runs = df['Runs']

print(runs) # All runs values

# Select multiple columns (returns a DataFrame)

summary = df[['Name', 'Runs', 'Matches']]

# Select rows by condition (filtering)

high_scorers = df[df['Runs'] > 5000]

print(high_scorers) # Only players with >5000 runs

# Multiple conditions

elite = df[(df['Runs'] > 5000) & (df['Matches'] > 200)]

# Select by row index

print([Link][0]) # First row (by position)

print([Link][0]) # Row with index label 0

# Select specific cell

print([Link][0]['Runs']) # Virat's runs

Python Unleashed 47
■ Real-World Example: E-commerce Product Filtering

When you filter products on Amazon — 'Electronics', 'Under ■5000', 'Rating 4+ stars' — the
backend runs queries like: df[(df['category']=='Electronics') & (df['price']<5000) &
(df['rating']>=4)]. This returns exactly the products matching all your filters. Every filter button
on every e-commerce site is a Pandas-style condition in a database.

6.3 Aggregation — Turning Data Into Insights


# Basic statistics on a column

print(df['Runs'].sum()) # Total runs by all players

print(df['Runs'].mean()) # Average runs

print(df['Runs'].max()) # Highest score

print(df['Runs'].min()) # Lowest score

print(df['Runs'].count()) # Number of non-null values

print(df['Runs'].median()) # Middle value

print(df['Runs'].std()) # Standard deviation

# GroupBy: Aggregate by category

team_stats = [Link]('Team')['Runs'].sum()

print(team_stats) # Total runs per team

# Multiple aggregations at once

player_stats = [Link]('Name').agg({

'Runs': ['sum', 'mean', 'max'],

'Matches': 'count'

})

6.4 Creating New Columns — Deriving Insights


Often the most valuable insight isn't directly in the data — it's derived from it. Pandas makes it
easy to create new columns based on existing ones.

# Create calculated columns

Python Unleashed 48
df['StrikeRate'] = (df['Runs'] / df['Balls']) * 100

df['Average'] = df['Runs'] / df['Matches']

df['RunsPerMatch'] = df['Runs'] / df['Matches']

# Categorise using conditions (apply + lambda)

df['Performance'] = df['Average'].apply(

lambda avg: 'Elite' if avg >= 50

else ('Good' if avg >= 35 else 'Developing')

# Round values for clean display

df['Average'] = df['Average'].round(2)

df['StrikeRate'] = df['StrikeRate'].round(1)

print(df[['Name', 'Runs', 'Average', 'StrikeRate', 'Performance']])

6.5 Sorting and Ranking


# Sort by single column

leaderboard = df.sort_values('Runs', ascending=False)

# Sort by multiple columns

ranked = df.sort_values(['Average', 'Runs'], ascending=[False, False])

# Add rank column

df['Rank'] = df['Runs'].rank(ascending=False).astype(int)

# Get top N performers

top_3 = [Link](3, 'Runs')

bottom_3 = [Link](3, 'Average')

print('=== LEADERBOARD ===')

print(leaderboard[['Rank', 'Name', 'Runs',


'Average']].to_string(index=False))

Python Unleashed 49
6.6 Handling Missing Data
In real datasets, missing data is inevitable. A player who missed matches, a form that wasn't
filled, a sensor that went offline — all create missing values. Pandas gives you tools to detect
and handle them professionally.

# Detect missing values

print([Link]()) # True where data is missing

print([Link]().sum()) # Count missing per column

print([Link]().any()) # Which columns have any missing

# Options for handling missing data

[Link]() # Remove rows with ANY missing value

[Link](subset=['Runs']) # Remove only if 'Runs' is missing

[Link](0) # Replace missing with 0

df['Average'].fillna(df['Average'].mean()) # Replace with column mean

# Check for duplicates

print([Link]().sum()) # Count duplicate rows

df.drop_duplicates() # Remove all duplicates

■ Real-World Example: Hospital Patient Records

In a hospital database, some patients may have missing blood test results or incomplete
address fields. Before running any analysis (average recovery time, common diagnoses), the
data team runs isnull().sum() to find gaps, then decides: drop incomplete records, or fill
missing values with averages or defaults. This data cleaning step happens in every
professional data project — it's not optional, it's foundational.

■ Common Mistakes to Avoid

✗ Forgetting to import pandas as pd — always include this at the top of your file.

✗ Modifying a slice of a DataFrame — always use .copy() when creating a subset you'll
modify.

Python Unleashed 50
✗ Chaining conditions without parentheses — (df['A'] > 5) & (df['B'] < 10) needs the
brackets.

✗ Using df['col'] when column doesn't exist — causes KeyError; check [Link] first.

✗ Ignoring missing values — they silently corrupt averages and comparisons.

■ Mental Model

✓ DataFrame = Excel spreadsheet in Python — rows are records, columns are attributes.

✓ Filtering (df[condition]) is how you ask 'Which rows match my criteria?'

✓ Aggregation (.sum(), .mean(), .groupby()) turns raw data into summary insights.

✓ Creating new columns is analytical thinking — derive what the data doesn't directly
state.

✓ Always clean data before analysing — missing or duplicate values distort every result.

■ CHAPTER SUMMARY

✓ Pandas is Python's essential library for working with structured data at any scale.

✓ DataFrames are tabular data structures — rows as records, columns as attributes.

✓ Filtering with conditions extracts only the rows that match your criteria.

✓ Aggregation (.sum(), .mean(), .groupby()) converts raw data into summary insights.

✓ Creating new columns derives analytical value from existing data.

✓ Always check for and handle missing data before drawing any conclusions.

■ EXERCISES & PRACTICE

■ Quick Practice 1: DataFrame Exploration

Create a DataFrame with 6 cricket players (name, runs, balls, matches, team).

Python Unleashed 51
Then perform:

1. [Link]() — observe the output

2. Filter: players with runs > 5000

3. Sort by runs (descending)

4. Add a 'StrikeRate' column: (runs/balls)*100

5. Find the team with the highest total runs using groupby

■ Applied Project 2: Sales Data Analyser

Imagine a sales DataFrame: columns = Date, Product, Units_Sold, Price_Per_Unit, Region

Write Pandas code to find:

1. Total revenue per product (Units_Sold * Price_Per_Unit summed by product)

2. Top 3 products by total revenue

3. Best performing region

4. Products with any missing Price_Per_Unit values

5. Average units sold per day

Even if you don't have the file, write the code structure.

■ Mini Project 3: Missing Data Challenge

Create a DataFrame where 3 cells are intentionally missing (use None or float('nan')).

1. Use isnull().sum() to identify the gaps

2. Fill missing numeric values with the column mean

3. Fill missing string values with 'Unknown'

4. Verify no missing values remain

Python Unleashed 52
5. Export your cleaned data with df.to_csv('cleaned_data.csv', index=False)

■ AI Learning Tip

Pandas has hundreds of functions. Don't memorise them all — use AI as your Pandas
reference. When you need something, ask: 'In Pandas, how do I calculate the rolling 7-day
average of a column?' or 'How do I pivot this DataFrame so each player is a column and each
row is a match?' Describe what you want to achieve, and AI will give you the exact code.
Then understand it, run it, tweak it — that's how professionals learn.

★ CONFIDENCE CORNER

Pandas is what most data professionals use every single day. By working through this
chapter, you've learned skills that are directly applicable to real jobs in data analysis,
business intelligence, and software development. The fact that you're learning this
systematically — understanding the concepts, not just copying code — puts you ahead of
many people who use Pandas mechanically without understanding why it works.

Python Unleashed 53
CHAPTER 7

SQL Thinking Through Pandas


Learning to Ask Better Questions from Data

SQL (Structured Query Language) is the universal language of databases. Even if you never
write SQL directly, the thinking behind it is fundamental to every data operation. The beautiful
thing is that Pandas implements SQL-style operations in Python. By learning to think in SQL
patterns, you become a dramatically better data analyst.

7.1 SQL Thinking vs. Code Thinking


■ Code Thinking (Procedural) ■ SQL Thinking (Declarative)

'How do I loop through these rows and 'WHAT do I want from this data?'
check each one?'

'Let me use a for loop to build up my 'SELECT players WHERE runs >
result.' average'

'I'll store results in a new list as I go.' 'GROUP BY team and SUM the runs'

Focus: HOW to do it step by step Focus: WHAT you want, not how to
get it

SQL thinking is analytical thinking. You describe the question you want answered, and the
system figures out how to get it. Pandas lets you think this way in Python.

7.2 The Five Core SQL Operations (in Pandas)


SQL Operation What It Does Pandas Equivalent

SELECT columns Choose which columns to display df[['col1', 'col2']]

WHERE condition Filter rows matching a condition df[df['col'] > value]

[Link]('col')['val'].
GROUP BY column Aggregate data by category
sum()

Python Unleashed 54
ORDER BY column Sort results df.sort_values('col')

Combine data from multiple [Link](df1, df2,


JOIN table
tables on='key')

import pandas as pd

# Load our cricket data

df = pd.read_csv('cricket_stats.csv')

# SELECT: Choose specific columns

selected = df[['Name', 'Runs', 'Average']]

# WHERE: Filter rows

good_batters = df[df['Average'] > 40]

# WHERE with multiple conditions

elite = df[(df['Average'] > 50) & (df['Runs'] > 5000)]

# GROUP BY: Summarise by team

team_totals = [Link]('Team').agg({

'Runs': 'sum',

'Matches': 'count',

'Average': 'mean'

}).round(2)

# ORDER BY: Sort results

leaderboard = df.sort_values('Runs', ascending=False)

# Combine them all

final_report = (

df[(df['Average'] > 40)]

[['Name', 'Team', 'Runs', 'Average']]

.sort_values('Runs', ascending=False)

Python Unleashed 55
.head(10)

7.3 Joining Data — Connecting Related Information


Real data is rarely in one table. A cricket database might have a players table, a matches table,
and a performance table. Joining connects them using a common key.

players_df performance_df combined_df


+ =
PlayerID, Name, PlayerID, Runs, Name, Country, Runs,
Country, DOB Wickets, Matches Wickets...

■ Join Diagram: Two tables combined on a shared 'PlayerID' key into one unified DataFrame.

# Two separate tables

players_df = [Link]({

'PlayerID': [1, 2, 3],

'Name': ['Virat', 'Rohit', 'Jadeja'],

'Country': ['India', 'India', 'India']

})

performance_df = [Link]({

'PlayerID': [1, 2, 3],

'Runs': [8250, 7890, 2300],

'Wickets': [0, 0, 260]

})

# Join on PlayerID (inner join — only matching rows)

combined = [Link](players_df, performance_df, on='PlayerID',


how='inner')

# Left join — keep all rows from left even if no match in right

combined = [Link](players_df, performance_df, on='PlayerID',


how='left')

print(combined)

Python Unleashed 56
7.4 Building a Data Pipeline
A data pipeline is a sequence of operations that transforms raw data into a meaningful result.
This is what every data analyst does daily:


LOAD Read CSV/Excel/DB into DataFrame

② INS
PECT head(), shape, dtypes, describe()

③ CLE
AN Handle missing values, fix types, remove duplicates

④ FILT
ER Keep only rows relevant to your question

⑤ TRA
NSFO
RM Create calculated columns, group, merge

⑥ AN
ALYS
E Aggregations, statistics, comparisons

⑦ REP
ORT Sort, select final columns, export or display

■ Real-World Example: IPL Analytics Dashboard

The IPL analytics team follows this exact pipeline each match day: Load ball-by-ball data
(LOAD). Check for missing deliveries or duplicate records (INSPECT + CLEAN). Filter for T20
matches only (FILTER). Calculate strike rates, economy rates, powerplay averages
(TRANSFORM). Find who outperformed their season average (ANALYSE). Build the
leaderboard and insights report (REPORT). Every professional data project follows this
pipeline.

■ Common Mistakes to Avoid

✗ Thinking of data operations as loops — use Pandas vectorised operations, not for loops.

✗ Not specifying 'how' parameter in merge — default is 'inner', which drops non-matching
rows.

Python Unleashed 57
✗ Forgetting to reset index after filtering — use .reset_index(drop=True) for clean indexing.

✗ Using == to compare with NaN — use .isnull() instead; NaN != NaN by design.

✗ Doing analysis on uncleaned data — always clean before you query.

■ CHAPTER SUMMARY

✓ SQL thinking means asking WHAT you want from data, not HOW to retrieve it step by
step.

✓ The five core operations: SELECT, WHERE (filter), GROUP BY, ORDER BY, JOIN —
all in Pandas.

✓ Joining connects related tables through a shared key column.

✓ A data pipeline: Load → Inspect → Clean → Filter → Transform → Analyse → Report.

✓ Pandas vectorised operations replace manual loops for efficiency and clarity.

✓ Real-world data always lives in multiple tables — joins are essential skills.

■ EXERCISES & PRACTICE

■ SQL to Pandas 1: Translate These Queries

Translate each SQL statement to Pandas code:

a) SELECT Name, Runs FROM players WHERE Team = 'Mumbai'

b) SELECT Team, AVG(Average) FROM players GROUP BY Team

c) SELECT * FROM players ORDER BY Runs DESC LIMIT 5

d) SELECT [Link], [Link] FROM players p JOIN stats s ON [Link] = [Link]

■ Applied Project 2: Complete Data Pipeline

Build a complete pipeline for this scenario:

Python Unleashed 58
Dataset 1: [Link] (PlayerID, Name, Team, Country)

Dataset 2: [Link] (PlayerID, Runs, Wickets, Catches)

Tasks:

1. Load both, inspect each

2. Clean: remove any rows with missing Runs

3. Join the two tables on PlayerID

4. Create a 'AllRounder_Score' column: (Runs/100) + Wickets

5. Rank and display the top 5 all-rounders

■ AI Learning Tip

SQL is one of the most valuable skills in any data-related career. If you want to go deeper,
ask an AI: 'I understand Pandas. Teach me how the same operations look in actual SQL
syntax, using these same cricket examples.' This parallel learning approach builds both skills
simultaneously. Many companies use both SQL databases AND Pandas for different parts of
their data workflow.

★ CONFIDENCE CORNER

SQL thinking is the skill that elevates a 'Python programmer' into a 'data professional'.
When you can look at raw data and immediately think 'I need to filter by X, group by Y,
and sort by Z to answer this question' — that's the mindset of someone who adds real
business value. You're building that mindset right now, one operation at a time.

Python Unleashed 59
CHAPTER 8

Analytics Thinking
From Data to Decisions

Data alone is not insight. Numbers on a page don't make decisions — interpretation does.
Analytics thinking is the ability to look at data, ask the right questions, apply the right frameworks,
and extract conclusions that inform real decisions. This chapter teaches you how to think like an
analyst — not just how to code like one.

8.1 The Analytical Question Framework


Before touching any data, the most important question is: What decision will this analysis
support? Every piece of analysis should serve a decision. Without this anchor, you'll generate
interesting numbers that lead to nothing.

Type Question Pattern Cricket Example Decision It Supports

Descriptive What happened? How many runs did the Season performance
team score this season? review

Diagnostic Why did it Why did the team lose 3 Identify weaknesses to
happen? consecutive matches? fix

Predictive What will happen? Based on current form, who Player selection strategy
will top-score next match?

Prescriptive What should we Given the opponent's Optimise team strategy


do? weakness, which batting
order maximises wins?

8.2 Choosing the Right Metric


A metric is a measurable value that represents performance or progress. Choosing the wrong
metric leads to wrong conclusions — and wrong decisions. This is one of the most common
mistakes in data analysis.

Python Unleashed 60
■ Metric Trap: Total vs. Average

Wrong Question: 'Who has the most total runs in the tournament?'

This could be biassed by a player who simply played more matches.

Better Question: 'Who has the highest batting average (runs per innings)?'

This normalises for the number of opportunities, giving a fair comparison.

# Bad metric: Total runs (biassed by matches played)

[Link]('Name')['Runs'].sum().sort_values(ascending=False)

# Better metric: Average runs per match

df['Average'] = df['Runs'] / df['Matches']

df.sort_values('Average', ascending=False)

# Even better: Performance Index (multiple factors)

df['Performance_Index'] = (

(df['Average'] * 0.4) +

(df['StrikeRate'] * 0.3) +

(df['Consistency'] * 0.3) # Std deviation of scores, inverted

# Benchmark against tournament average

tournament_avg = df['Average'].mean()

df['Above_Average'] = df['Average'] > tournament_avg

print(df[df['Above_Average']][['Name', 'Average',
'Performance_Index']])

8.3 Statistical Thinking — Making Sense of Numbers


Concept What It Tells You Cricket Application

Python Unleashed 61
Mean (Average) Typical value in a dataset Average runs per innings — fair
performance measure

Median Middle value — resistant to Median score more reliable when


outliers one knock was unusually high

Standard Deviation How spread out the values are Low std dev = consistent player;
high = unpredictable

Min / Max Range of values Worst and best performance —


shows ceiling and floor

Percentile Relative position vs. all others 'Top 10% of batters' = above
90th percentile

import pandas as pd

import numpy as np

# Complete statistical profile of a player's scores

scores = [45, 78, 23, 91, 56, 34, 88, 12, 67, 84]

mean = [Link](scores)

median = [Link](scores)

std_dev = [Link](scores)

consistency = 100 - (std_dev / mean * 100) # Higher = more consistent

print(f'Mean: {mean:.1f}')

print(f'Median: {median:.1f}')

print(f'Std Deviation: {std_dev:.1f}')

print(f'Consistency Score: {consistency:.1f}%')

# Percentile rank

score_75 = [Link](scores, 75) # 75th percentile value

print(f'75th percentile score: {score_75}')

Python Unleashed 62
8.4 Common Analytical Mistakes to Avoid
✖ Small Sample Size Drawing conclusions from too few data points. 3 matches is not
enough to determine a player's skill level.

✖ Ignoring Context Numbers without context mislead. A 'low' strike rate of 80 might be
excellent for a Test opener.

✖ Correlation ≠ Two things happening together doesn't mean one causes the other.
Causation 'Teams with more sixes win more' — but is it the sixes causing wins?

✖ Cherry-Picking Selecting only the data that supports what you already believe. Always
look at the full picture.

✖ Survivorship Bias Analysing only successful cases. If you study only top performers, you
miss what separates them from average.

8.5 The Analytics Workflow


# Complete analytics workflow example

# STEP 1: Define the question

# Q: Which players are consistently performing above team average?

# STEP 2: Load and clean

df = pd.read_csv('cricket_stats.csv')

df = [Link](subset=['Runs', 'Matches'])

df = df[df['Matches'] >= 5] # Only players with 5+ matches

# STEP 3: Create metrics

df['Average'] = (df['Runs'] / df['Matches']).round(2)

df['StrikeRate'] = ((df['Runs'] / df['Balls']) * 100).round(1)

# STEP 4: Benchmark

team_avg = df['Average'].mean()

team_sr = df['StrikeRate'].mean()

Python Unleashed 63
# STEP 5: Analyse

df['Above_Avg'] = df['Average'] > team_avg

df['Above_SR'] = df['StrikeRate'] > team_sr

df['Consistent_Top'] = df['Above_Avg'] & df['Above_SR']

# STEP 6: Report

top_players = df[df['Consistent_Top']][['Name', 'Average',


'StrikeRate']]

print('=== CONSISTENTLY ABOVE-AVERAGE PLAYERS ===')

print(top_players.sort_values('Average',
ascending=False).to_string(index=False))

■ Mental Model

✓ Analytics starts with a decision — what will this analysis help us do differently?

✓ Choose metrics that are fair — averages beat totals when players have different
opportunities.

✓ Statistical thinking: mean, median, std deviation tell a complete story together.

✓ Always question your conclusions — what context am I missing? Is my sample large


enough?

✓ The analytics workflow: Question → Clean → Metric → Benchmark → Analyse →


Interpret → Report.

■ CHAPTER SUMMARY

✓ Analytics thinking means asking what decision your analysis will support before you
start.

✓ Four analytics types: Descriptive (what), Diagnostic (why), Predictive (will), Prescriptive
(should).

✓ Metrics choice is critical — the wrong metric leads to the wrong conclusion.

✓ Statistical measures (mean, median, std deviation) together paint the complete picture.

Python Unleashed 64
✓ Common mistakes: small sample, ignoring context, correlation vs. causation,
cherry-picking.

✓ The analytics workflow is question-first, clean-second, analyse-third, interpret-always.

■ EXERCISES & PRACTICE

■ Metric Design 1: Choose Your KPIs

For each scenario, define the best metric and explain why:

a) An HR team wants to assess employee productivity

b) A school wants to evaluate teacher effectiveness

c) An IPL team wants to select their best all-rounder

d) A hospital wants to measure quality of patient care

For each: name the metric, explain what it measures, and name one pitfall of using it.

■ Applied Project 2: Player Performance Dashboard

Build a complete analytics report for a cricket dataset:

1. Load data: 10 players, 5 attributes each

2. Calculate: average, strike rate, consistency score (100 - cv*100)

3. Benchmark all metrics against team average

4. Categorise: 'Elite' (top 20%), 'Good' (average+), 'Developing' (below average)

5. Generate a printed report: top 3, bottom 3, most consistent, most improved

★ CONFIDENCE CORNER

Python Unleashed 65
Analytics thinking is one of the most valuable skills in any organisation. Companies pay
significant salaries for people who can look at data and extract decisions — not just
numbers. The fact that you're learning to ask 'why', benchmark, think statistically, and
avoid common mistakes puts you ahead of the vast majority of people who simply report
numbers without interpretation. You're learning to think like someone who matters to a
business.

Python Unleashed 66
CHAPTER 9

Cricket Analytics Platform


Bringing It All Together — Your Capstone Project

You've come an extraordinary distance. You understand how computers think, how Python
speaks, how logic controls flow, how data structures organise information, how algorithms solve
problems, how Pandas handles data at scale, how SQL thinking extracts insights, and how
analytics thinking converts data into decisions. Now it's time to bring every single one of those
skills together into a real, working application.

■ Your Capstone Project

This is your Capstone Project — a CricHeroes-style Cricket Analytics Platform. It is


not a toy exercise. It is a complete application with real architecture, real data
structures, and real analytical value. Building it will change how you see yourself as a
programmer.

9.1 System Architecture — Think Before You Code


Professional developers design systems before writing a single line of code. They ask: What are
the modules? What data do I need? How do the pieces connect? Let's design our Cricket
Analytics Platform systematically.

■ CRICKET ANALYTICS PLATFORM

Module 1 ■ Player Module 2 ■ Match Module 3 ■ Analytics Module 4 ■ Report


Management Management Engine Generator

Add/Update Player Calculate Stats & Leaderboards & Season


Profiles Record Match Scores Rankings Summary

■ Architecture: 4 modules, each with a clear responsibility — this is system thinking.

9.2 Data Design — The Foundation


Before coding, design your data structures. In a real application these would be database tables.
For our Python implementation, they are CSV files and DataFrames:

Python Unleashed 67
Table Columns Purpose

[Link] PlayerID, Name, Team, Age, Master list of all players in the
Role, Country system

[Link] MatchID, Date, Team1, Team2, All matches played with results
Venue, Result

performance MatchID, PlayerID, Runs, Player stats for each match


.csv Balls, 4s, 6s, Wickets,
Catches

derived StrikeRate, Average, Economy, Calculated columns (added by


AllRounderScore analytics engine)

9.3 Complete Implementation


import pandas as pd

import numpy as np

# ============================================================

# MODULE 1: PLAYER MANAGEMENT

# ============================================================

def load_players(filepath='[Link]'):

"""Load player data from CSV."""

try:

return pd.read_csv(filepath)

except FileNotFoundError:

print(f'File not found: {filepath}')

return [Link]()

def add_player(df, player_id, name, team, age, role):

"""Add a new player to the system."""

if player_id in df['PlayerID'].values:

Python Unleashed 68
print(f'Player {player_id} already exists!')

return df

new_player = {'PlayerID': player_id, 'Name': name,

'Team': team, 'Age': age, 'Role': role}

return [Link]([df, [Link]([new_player])],


ignore_index=True)

def get_player(df, name):

"""Find a player by name."""

result = df[df['Name'].[Link](name, case=False)]

if [Link]:

print(f'No player found matching: {name}')

return result

# ============================================================

# MODULE 2: MATCH MANAGEMENT

# ============================================================

def record_performance(match_id, player_id, runs, balls, wickets=0):

"""Create a performance record for a player in a match."""

if balls == 0:

strike_rate = 0

else:

strike_rate = round((runs / balls) * 100, 2)

return {

'MatchID': match_id,

'PlayerID': player_id,

'Runs': runs,

'Balls': balls,

'StrikeRate': strike_rate,

'Wickets': wickets

Python Unleashed 69
def load_performance(filepath='[Link]'):

"""Load all match performances."""

try:

df = pd.read_csv(filepath)

df['StrikeRate'] = (df['Runs'] / df['Balls'].replace(0, 1) *


100).round(2)

return df

except FileNotFoundError:

return [Link]()

# ============================================================

# MODULE 3: ANALYTICS ENGINE

# ============================================================

def build_player_stats(players_df, performance_df):

"""Calculate comprehensive stats per player."""

# Aggregate performance data

agg = performance_df.groupby('PlayerID').agg(

Total_Runs=('Runs', 'sum'),

Total_Balls=('Balls', 'sum'),

Matches=('MatchID', 'nunique'),

Total_Wickets=('Wickets', 'sum'),

Best_Score=('Runs', 'max')

).reset_index()

# Merge with player info

stats = [Link](players_df, agg, on='PlayerID', how='left')

# Calculate derived metrics

stats['Average'] = (stats['Total_Runs'] /
stats['Matches']).round(2)

stats['StrikeRate'] = (

Python Unleashed 70
(stats['Total_Runs'] / stats['Total_Balls'].replace(0, 1)) *
100).round(1)

stats['AllRounder_Score'] = (

(stats['Average'] * 0.6) + (stats['Total_Wickets'] * 10 *


0.4)).round(2)

return stats

def get_consistency_score(performance_df, player_id):

"""Calculate how consistent a player is (lower std dev = more


consistent)."""

player_scores = performance_df[performance_df['PlayerID'] ==
player_id]['Runs']

if len(player_scores) < 3:

return None

mean_score = player_scores.mean()

if mean_score == 0:

return 0

cv = player_scores.std() / mean_score # Coefficient of variation

return round(100 - (cv * 100), 1) # Higher = more consistent

# ============================================================

# MODULE 4: REPORT GENERATOR

# ============================================================

def print_leaderboard(stats_df, top_n=10):

"""Print the batting leaderboard."""

leaderboard = stats_df.nlargest(top_n, 'Total_Runs')

print('\n' + '=' * 60)

print(f' TOP {top_n} BATTING LEADERBOARD')

print('=' * 60)

print(f"{'Rank':<5} {'Name':<15} {'Runs':<8} {'Avg':<8} {'SR':<8}")

print('-' * 60)

Python Unleashed 71
for rank, (_, row) in enumerate([Link](), 1):

print(f"{rank:<5} {row['Name']:<15} {row['Total_Runs']:<8}"

f" {row['Average']:<8} {row['StrikeRate']:<8}")

def print_team_summary(stats_df):

"""Print team-level summary."""

team_stats = stats_df.groupby('Team').agg(

Total_Runs=('Total_Runs', 'sum'),

Avg_Batting_Avg=('Average', 'mean'),

Players=('Name', 'count')

).sort_values('Total_Runs', ascending=False)

print('\n=== TEAM PERFORMANCE SUMMARY ===')

print(team_stats.round(2).to_string())

# ============================================================

# MAIN PROGRAM

# ============================================================

def main():

players_df = load_players('[Link]')

performance_df = load_performance('[Link]')

if players_df.empty or performance_df.empty:

print('No data found. Please add player and match data first.')

return

stats = build_player_stats(players_df, performance_df)

while True:

print('\n=== CRICKET ANALYTICS PLATFORM ===')

print('1. View Leaderboard')

print('2. View Team Summary')

print('3. Search Player')

Python Unleashed 72
print('4. Exit')

choice = input('\nEnter choice (1-4): ')

if choice == '1': print_leaderboard(stats)

elif choice == '2': print_team_summary(stats)

elif choice == '3':

name = input('Enter player name: ')

p = get_player(stats, name)

if not [Link]: print(p.to_string())

elif choice == '4': break

if __name__ == '__main__':

main()

9.4 Project Roadmap — Build Incrementally


Phase CSV Foundation Create sample CSV data files. Build load_players() and
1 load_performance(). Run head() on both DataFrames.

Phase Analytics Core Implement build_player_stats(). Calculate Average and


2 StrikeRate. Print results as a formatted table.

Phase Leaderboard Implement print_leaderboard(). Add rank column. Display top 10


3 players sorted by total runs.

Phase Team Analytics Add team-level groupby. Identify best and worst performing
4 teams. Add consistency scores.

Phase Menu Interface Build the while-loop menu system. Connect all modules. Handle
5 edge cases and missing data.

Phase Enhancement Add matplotlib charts. Export PDF reports. Build a simple web
6 dashboard using Flask (optional).

9.5 What You've Built — A Professional Portfolio Piece


Let's reflect on what this application actually demonstrates. When you show this to a recruiter, a
client, or a university evaluator, here is what they see:

Python Unleashed 73
System Component Skills Demonstrated

Player & Match data loading File handling, exception handling, Pandas DataFrames

build_player_stats() GroupBy, merge, derived column creation, data


transformation

Leaderboard generation Sorting, ranking, formatting output, analytical thinking

Team summary report Multi-level aggregation, SQL thinking, result


interpretation

Menu-based interface Loops, conditionals, user input handling, program


structure

Edge case handling Professional code quality, defensive programming,


try/except

Modular architecture Function design, separation of concerns, system


thinking

■ CHAPTER SUMMARY

✓ System design comes before code — modules, data design, and connections first.

✓ Modular architecture separates concerns: player management, match management,


analytics, reporting.

✓ Data design (tables, columns, relationships) is the foundation of every real application.

✓ Complete implementation uses every skill from this book: variables, loops, functions,
Pandas, analytics.

✓ The project roadmap shows how to build incrementally — never try to build everything
at once.

✓ This application is a real portfolio piece demonstrating professional-level thinking.

Python Unleashed 74
■ EXERCISES & PRACTICE

■ Phase 1 Task 1: Setup and Load

Create two CSV files manually in a text editor:

[Link]: 8 rows of (PlayerID, Name, Team, Role)

[Link]: 20 rows of (MatchID, PlayerID, Runs, Balls, Wickets)

Load both with pd.read_csv() and verify with head() and shape.

Fix any issues you encounter — this is real data engineering experience.

■ Phase 3 Task 2: Build the Leaderboard

Implement build_player_stats() and print_leaderboard() exactly as shown.

Then extend it:

1. Add a 'Rank' column

2. Highlight the top performer with '*** TOP ***' marker

3. Add an 'Efficiency' column: Runs/Balls (only if Balls > 0)

4. Print a separate leaderboard for wicket-takers

■ Full Capstone 3: Complete Application

Build the complete Cricket Analytics Platform through all 5 phases.

Required features:

✓ Load and validate data (handle missing files gracefully)

✓ Calculate: average, strike rate, all-rounder score, consistency

✓ Leaderboard (batting and bowling separately)

Python Unleashed 75
✓ Team summary with best and worst performer per team

✓ Player search by name

✓ Menu-based interface with input validation

Bonus: Export the leaderboard to a new CSV file using df.to_csv()

■ AI Learning Tip

When building this project, use AI as a collaborator on specific problems: 'I want to add a
feature that shows how a player's average has changed over time (match by match). How
would I structure this in Pandas?' Or 'My merge is returning fewer rows than expected. Here
is my code — what might be wrong?' This is exactly how professional developers use AI tools
in their daily work — targeted questions for specific problems, not asking AI to write the entire
thing.

■ YOU BUILT THIS

When you started this book, you may have doubted whether programming was
'for you'. You may have felt that the people who learn quickly are somehow
fundamentally different from you. I want you to stop and recognise what you've
actually accomplished.

You understand how computers think. You write Python. You build logic. You
organise data. You design algorithms. You analyse with Pandas. You think in
SQL. You draw conclusions from data. And you designed a complete application.

That is not beginner work. That is the foundation of a professional career. The
difference between you and someone who 'knows how to code' is now just time
and practice — and you've already started.

The world of data and programming needs people who think clearly,
question deeply, and build honestly. You have all three. Keep going.

Python Unleashed 76

You might also like