0% found this document useful (0 votes)
4 views13 pages

Chandan Python Notes DataAnalyst

This document is a comprehensive guide for beginners to intermediate Python programming, specifically tailored for data analysts. It covers essential topics such as Python basics, data types, functions, file handling, and libraries like Pandas and Matplotlib, along with practical examples and exercises. The document also includes practice questions to reinforce learning and improve coding skills.

Uploaded by

motup5361
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)
4 views13 pages

Chandan Python Notes DataAnalyst

This document is a comprehensive guide for beginners to intermediate Python programming, specifically tailored for data analysts. It covers essential topics such as Python basics, data types, functions, file handling, and libraries like Pandas and Matplotlib, along with practical examples and exercises. The document also includes practice questions to reinforce learning and improve coding skills.

Uploaded by

motup5361
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 Notes

Data Analyst Edition


Prepared for: Chandan Kumar
Topics: Basics → Variables → Loops → Functions → Libraries → Pandas → Matplotlib
Beginner to Intermediate | With Examples & Explanations

Table of Contents
# Chapter Topics

01 Python Basics Print, Variables, Data Types, Input

02 Operators & Conditions Arithmetic, Comparison, If-Else

03 Loops For Loop, While Loop, Range, Break, Continue

04 Lists, Tuples & Dictionaries Collections, Indexing, Methods

05 Functions def, Arguments, Return, Lambda

06 File Handling Read, Write, CSV files

07 NumPy Arrays, Math Operations

08 Pandas DataFrame, Read CSV, Filter, GroupBy

09 Matplotlib Line, Bar, Pie Charts — Data Visualization

10 Practice Questions Real Data Analyst Problems


CHAPTER 01 — Python Basics
Print, Variables, Data Types, Comments, Input

1.1 Print Function


Print function screen pe output dikhata hai. Yeh sabse pehla command hai jo Python mein seekhte hain.

# Basic print
print("Hello Chandan!")
>>> Hello Chandan!
# Multiple values print
print("Name:", "Chandan", "Age:", 17)
>>> Name: Chandan Age: 17
# Print with separator
print("Power", "BI", "SQL", sep=" | ")
>>> Power | BI | SQL

1.2 Variables
Variable ek container hai jisme data store karte hain. Python mein type declare nahi karna padta — Python khud samajh jaata
hai.

# Variable banana
name = "Chandan Kumar" # String
age = 17 # Integer
salary = 25000.50 # Float
is_analyst = True # Boolean

# Variables print karo


print(name) >>> Chandan Kumar
print(age) >>> 17
print(salary) >>> 25000.5

■ Tip: Variable naam mein space nahi hota — underscore use karo. Example: my_name, total_sales

1.3 Data Types


Python mein mainly 5 data types hain:

Data Type Example Use Case

int (Integer) age = 17 Poore numbers — count, ID

float (Decimal) price = 99.99 Price, percentage, ratio

str (String) name = "Chandan" Text, names, messages

bool (Boolean) active = True Yes/No, True/False conditions

list skills = ['SQL','PowerBI'] Multiple values store karna


# type() function se data type check karo
print(type(17)) >>>
print(type("Chandan")) >>>
print(type(99.99)) >>>
print(type(True)) >>>

1.4 Input Function


input() se user se data le sakte hain program mein:

name = input("Apna naam batao: ")


print("Hello", name)

# Number input lena ho toh int() ya float() use karo


age = int(input("Apni age batao: "))
print("Teri age hai:", age)
CHAPTER 02 — Operators & Conditions
Arithmetic, Comparison, Logical, If-Elif-Else

2.1 Arithmetic Operators


a = 20
b = 6
print(a + b) >>> 26 # Addition
print(a - b) >>> 14 # Subtraction
print(a * b) >>> 120 # Multiplication
print(a / b) >>> 3.33 # Division
print(a // b) >>> 3 # Floor Division (poora number)
print(a % b) >>> 2 # Modulus (remainder/bacha hua)
print(a ** b) >>> 64000000 # Power (a ki power b)

2.2 Comparison Operators


x = 10
y = 20
print(x == y) >>> False # Equal hai kya?
print(x != y) >>> True # Not equal hai kya?
print(x > y) >>> False # Bada hai kya?
print(x < y) >>> True # Chota hai kya?
print(x >= 10) >>> True # Bada ya equal?
print(x <= 5) >>> False # Chota ya equal?

2.3 If-Elif-Else (Conditions)


Condition check karna — agar yeh toh woh, nahi toh yeh:
# Simple if-else
salary = 30000

if salary > 50000:


print("High salary!")
elif salary > 25000:
print("Medium salary")
else:
print("Low salary")

>>> Medium salary


# Data Analyst example
marks = 85
if marks >= 90:
grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 60:
grade = "C"
else:
grade = "Fail"
print("Grade:", grade) >>> Grade: B

■ Tip: Python mein indentation (4 spaces ya 1 tab) bahut important hai — bina indentation code kaam nahi karega!
CHAPTER 03 — Loops
For Loop, While Loop, Range, Break, Continue

3.1 For Loop


Ek cheez ko baar baar repeat karna — list ya range ke saath:

# List pe loop
skills = ["SQL", "Power BI", "Excel", "Python"]
for skill in skills:
print("Mujhe aata hai:", skill)

>>> Mujhe aata hai: SQL


>>> Mujhe aata hai: Power BI
>>> Mujhe aata hai: Excel
>>> Mujhe aata hai: Python
# range() ke saath loop
for i in range(1, 6): # 1 se 5 tak
print(i)
>>> 1 2 3 4 5

3.2 While Loop


Jab tak condition sahi ho — tab tak chalao:

count = 1
while count <= 5:
print("Count:", count)
count = count + 1 # Ya count += 1

>>> Count: 1
>>> Count: 2 ...upto 5

3.3 Break & Continue


# Break — loop band karo
for i in range(1, 10):
if i == 5:
break # 5 aate hi band ho jaao
print(i)
>>> 1 2 3 4
# Continue — is step skip karo, aage badho
for i in range(1, 8):
if i == 4:
continue # 4 skip karo
print(i)
>>> 1 2 3 5 6 7
CHAPTER 04 — Lists, Tuples & Dictionaries
Collections, Indexing, Methods — Data Analyst ke liye Most Important!

4.1 Lists
List mein multiple values store hoti hain — changeable (mutable) hoti hai:

skills = ["SQL", "Power BI", "Excel", "Python"]

# Indexing — 0 se shuru hoti hai


print(skills[0]) >>> SQL
print(skills[-1]) >>> Python # Last element

# List methods
[Link]("DAX") # Naya add karo
[Link]("Excel") # Remove karo
print(len(skills)) >>> 4 # Length
print(skills[1:3]) # Slicing — index 1 se 2 tak

# List mein loop


for s in skills:
print(s)

4.2 Dictionaries
Dictionary mein key-value pairs hote hain — bilkul Excel ke column-row jaise:

# Dictionary banana
student = {
"name": "Chandan Kumar",
"age": 17,
"city": "Muzaffarpur",
"skills": ["SQL", "Power BI"]
}

# Values access karo


print(student["name"]) >>> Chandan Kumar
print(student["age"]) >>> 17

# Naya key-value add karo


student["certificate"] = "Deloitte"

# Dictionary loop
for key, value in [Link]():
print(key, ':', value)

■ Data Analyst tip: Dictionary aur List milake JSON data handle karte hain — APIs aur databases mein bahut use hota hai!
CHAPTER 05 — Functions
def, Arguments, Return Values, Lambda Functions

5.1 Function kya hai?


Function ek reusable block of code hai — ek baar likho, baar baar use karo:

# Function banana — def keyword se


def greet(name):
print("Hello", name, "!")

# Function call karo


greet("Chandan") >>> Hello Chandan !
greet("Recruiter") >>> Hello Recruiter !

5.2 Return Values


# Data Analyst example — sales calculate karo
def calculate_profit(revenue, cost):
profit = revenue - cost
return profit

result = calculate_profit(50000, 30000)


print("Profit:", result) >>> Profit: 20000

# Multiple returns
def get_stats(numbers):
total = sum(numbers)
average = total / len(numbers)
maximum = max(numbers)
return total, average, maximum

data = [100, 200, 300, 400, 500]


t, a, m = get_stats(data)
print("Total:", t, "| Avg:", a, "| Max:", m)
>>> Total: 1500 | Avg: 300.0 | Max: 500

5.3 Lambda Functions


Short one-line functions — Pandas mein bahut use hote hain:

# Normal function
def double(x):
return x * 2

# Same kaam Lambda se


double = lambda x: x * 2
print(double(5)) >>> 10

# Pandas mein use — column pe apply karna


# df['salary'].apply(lambda x: x * 1.1) # 10% raise
CHAPTER 06 — Pandas Library
DataFrame, CSV Read, Filter, GroupBy — Data Analyst ka Main Tool!

6.1 Pandas Install & Import


# VS Code terminal mein run karo pehli baar
# pip install pandas
# Har file mein import karo
import pandas as pd

# pd alias hai — [Link] likhenge aage

6.2 DataFrame banana


DataFrame = Excel ka table jaise — rows aur columns:

import pandas as pd

# Dictionary se DataFrame banao


data = {
"Name": ["Rahul", "Priya", "Amit", "Sunita"],
"Department": ["Sales", "HR", "IT", "Sales"],
"Salary": [35000, 42000, 55000, 38000],
"Experience": [2, 5, 8, 3]
}

df = [Link](data)
print(df)

>>> Name Department Salary Experience


>>> 0 Rahul Sales 35000 2
>>> 1 Priya HR 42000 5
>>> 2 Amit IT 55000 8
>>> 3 Sunita Sales 38000 3

6.3 CSV File Read karna


# CSV file padhna — Data Analyst ka daily kaam!
df = pd.read_csv("sales_data.csv")

# Basic info dekhna


print([Link]()) # Pehli 5 rows
print([Link]()) # Aakhri 5 rows
print([Link]) # (rows, columns) kitne hain
print([Link]()) # Data types aur null values
print([Link]()) # Mean, Min, Max, Std sab
print([Link]) # Column names

6.4 Data Filter karna


# Salary > 40000 wale employees
high_salary = df[df['Salary'] > 40000]
print(high_salary)

# Sales department wale


sales_team = df[df["Department"] == "Sales"]

# Multiple conditions
top_sales = df[(df["Department"] == "Sales") & (df["Salary"] > 35000)]

# Specific columns select karo


names_salary = df[["Name", "Salary"]]

6.5 GroupBy — SQL ka GROUP BY jaise!


# Department wise average salary
dept_avg = [Link]("Department")["Salary"].mean()
print(dept_avg)

>>> Department
>>> HR 42000.0
>>> IT 55000.0
>>> Sales 36500.0
# Multiple aggregations
summary = [Link]("Department").agg({
"Salary": ["mean", "sum", "max"],
"Experience": "mean"
})
print(summary)

6.6 Data Cleaning


# Null values check karo
print([Link]().sum())

# Null values fill karo


df['Salary'].fillna(0, inplace=True)

# Null rows drop karo


[Link](inplace=True)

# Duplicates remove karo


df.drop_duplicates(inplace=True)

# Column rename karo


[Link](columns={"Name": "Employee_Name"}, inplace=True)

# New column banana


df['Annual_Salary'] = df['Salary'] * 12
CHAPTER 07 — Matplotlib
Charts & Visualization — Python se Power BI jaise graphs!

7.1 Matplotlib Install & Import


# pip install matplotlib
import [Link] as plt
import pandas as pd

7.2 Line Chart


# Monthly sales data
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales = [15000, 22000, 18000, 30000, 25000, 35000]

[Link](figsize=(10, 5))
[Link](months, sales, color='blue', marker='o', linewidth=2)
[Link]("Monthly Sales Trend")
[Link]("Month")
[Link]("Sales (Rs)")
[Link](True)
plt.tight_layout()
[Link]("sales_trend.png") # Save karo
[Link]()

7.3 Bar Chart


departments = ['Sales', 'HR', 'IT', 'Marketing']
avg_salary = [36500, 42000, 55000, 48000]

[Link](figsize=(8, 5))
[Link](departments, avg_salary, color=['blue','green','red','orange'])
[Link]("Average Salary by Department")
[Link]("Department")
[Link]("Average Salary")
plt.tight_layout()
[Link]()

7.4 Pie Chart


categories = ['Electronics', 'Clothing', 'Food', 'Books']
sales_share = [40, 25, 20, 15]

[Link](figsize=(6, 6))
[Link](sales_share, labels=categories, autopct='%1.1f%%',
colors=['#2563eb','#16a34a','#ea580c','#7c3aed'])
[Link]("Sales Distribution by Category")
[Link]()

7.5 Pandas + Matplotlib combo


# Seedha DataFrame se plot karo
import pandas as pd
import [Link] as plt

df = pd.read_csv("[Link]")

# Bar chart seedha DataFrame se


[Link]("Department")["Revenue"].sum().plot(kind="bar")
[Link]("Revenue by Department")
plt.tight_layout()
[Link]()
CHAPTER 08 — Practice Questions
Real Data Analyst Problems — Khud Try Karo!

Q1. Basic Ek program likho jo user se naam aur salary le, aur bataye ki salary zyada hai ya kam (cutoff: 30000).

Q2. Loop 1 se 100 tak ke saare even numbers print karo.

Q3. Function Ek function banao calculate_tax(salary) jo 10% tax return kare agar salary > 50000 ho, warna 5%.

Q4. List Ek sales list banao — [15000, 22000, 8000, 35000, 12000] — total, average, max aur min find karo.

Q5. Dictionary Ek employee dictionary banao 5 employees ke saath name, dept, salary — phir sirf IT department
wale print karo.

Q6. Pandas Ek CSV file padhke: null values count karo, salary column ka average nikalo, aur experience > 3 wale
filter karo.

Q7. Visualization Pandas DataFrame se ek bar chart banao — department vs total salary — colors aur title ke saath.

Q8. Real Project Apne Credit Card Transaction dataset ko Python mein load karo — groupby card_category karo aur
revenue ka sum nikalo — phir bar chart banao!

Keep Coding, Chandan! ■■


Python Learning Tips
■ Roz kam se kam 30 min code likho — padhna kaafi nahi!
■ Errors se daro mat — error message padho, samjho, fix karo
■ Apne real dashboards ke datasets pe Python try karo
■ VS Code mein Jupyter Notebook extension install karo
■ August tak Pandas master karo — September se job apply karo!

You might also like