0% found this document useful (0 votes)
31 views104 pages

Python Note Till Django

The document provides a comprehensive introduction to Python programming, covering its definition, features, and various use cases across domains such as web development, data science, and machine learning. It explains fundamental concepts including syntax, variables, data types, operators, conditionals, and loops, along with practical examples and common mistakes. Additionally, it outlines the Python code execution lifecycle and includes questions for self-assessment.

Uploaded by

bikashbbsahu
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)
31 views104 pages

Python Note Till Django

The document provides a comprehensive introduction to Python programming, covering its definition, features, and various use cases across domains such as web development, data science, and machine learning. It explains fundamental concepts including syntax, variables, data types, operators, conditionals, and loops, along with practical examples and common mistakes. Additionally, it outlines the Python code execution lifecycle and includes questions for self-assessment.

Uploaded by

bikashbbsahu
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
You are on page 1/ 104

OCAC TRAINING

CENTRE
Subject :- Python

Introduction to Programming :
What is programming :-

Programming is giving instructions to a computer to perform specific tasks.

Why do we need programming languages?

Computers only understand binary. Languages like Python help us communicate with them
in human-friendly terms.

Types of programming languages:

1. Low-level (Machine, Assembly)


2. Machine Language (Binary Code):

Example:

01100110 00001010 (This is an example of an addition instruction, where the numbers


represent the CPU operations and the operands).

Assembly Language (Mnemonic Codes):

Example:

MOV AX, 5 (This instruction moves the value 5 into the AX register, which is a mnemonic
representing the machine code).

High-level (Python, Java, C++)

What is Python?

Definition

Python is a high-level, interpreted, general-purpose programming language. It was created


by Guido van Rossum and released in 1991. Python is known for:

Simple, readable syntax (like plain English)

Vast ecosystem and community

Being versatile across domains


Features of Python :

➢ Simple & Readable – Easy-to-read code; looks almost like English.


➢ Interpreted Language – No compilation step; code runs line by line using the Python
interpreter.
➢ Dynamically Typed – You don’t need to declare variable types.
➢ Cross-Platform – Python works on Windows, macOS, and Linux.
➢ Multi-paradigm – Supports object-oriented, functional, and procedural programming.
➢ Huge Standard Library – Modules for file I/O, networking, math, web services, etc.
➢ Community Support – Millions of developers, forums, and open-source packages.

Python Use Cases :-

Domain Tools/Libraries Examples

Web Development Django, Flask Websites, REST APIs, admin dashboards

Pandas, NumPy,
Data Science Data analysis, visualizations, reports
Matplotlib

Machine Learning TensorFlow, Scikit-learn Predictions, face recognition, chatbots

File renaming, email sending, browser


Automation Selenium, OS, Scripts
tasks

Mobile/Desktop
Kivy, Tkinter, BeeWare GUI applications
Apps

Cybersecurity Nmap, Scapy, Paramiko Network scanning, ethical hacking tools

Game Development Pygame 2D games like Snake or Flappy Bird

Python Code Execution Lifecycle (Step-by-step) :-

➤ Step 1: Source Code (Your .py file)

You write code like:

print("Hello, World!")

➤ Step 2: Parsing

Python reads the code and checks for syntax errors.


➤ Step 3: Compilation to Bytecode

Internally, Python converts your .py code into bytecode (intermediate code).

Stored temporarily as .pyc in __pycache__ folder.

➤ Step 4: Interpretation

The Python Virtual Machine (PVM) executes this bytecode line by line.

➤ Step 5: Execution Result

Output is shown:

Hello, World!

B. Python Basics – Syntax and Semantics

1. What Are Syntax and Semantics?

Term Explanation

Syntax The rules for writing Python code — structure, indentation, symbols.

Semantics The meaning behind the code — what the code does when executed.

2. Key Syntax Rules in Python

a) Indentation (No {} like other languages)

Python uses indentation (spaces/tabs) to define blocks of code (e.g., inside functions,
loops, conditionals).

# Correct

if True:

print("Hello")

# Incorrect (will cause IndentationError)

if True:

print("Hello")

Default: 4 spaces per indentation level (no tabs recommended).


b) Case Sensitivity

Python treats uppercase and lowercase as different.

name = "Alice"

Name = "Bob"

print(name) # Alice

print(Name) # Bob

Variables name and Name are different.

c) Statements Don’t End with ;

No need to use ; to end a line in Python.

# Valid

x=5

# Also valid (but not recommended)

x = 5;

Semicolons are optional unless writing multiple statements on one line.

d) Comments in Python

Single-line comment: Use #

Multi-line comment / Docstring: Use ''' or """

# This is a single-line comment

'''

This is a

multi-line comment

'''

def greet():

"""This is a function docstring"""

print("Hi")

Docstrings are used for documenting functions/classes/modules.

3. Real-Life Analogy

Syntax is like grammar in English.


Semantics is the meaning behind the sentence.

Example:

Print("Hello") → Wrong syntax (capital P)

print("Hello") → Correct syntax & semantics (prints to screen)

4. Common Syntax Mistakes

Mistake Error Type

Wrong indentation IndentationError

Using tabs and spaces mixed TabError

Misspelling keywords SyntaxError

Unmatched quotes/brackets SyntaxError

5. Sample Code Example

# This program prints user greeting

name = "John"

if name == "John":

print("Welcome, John!")

Variables in Python :-
1. What is a Variable?

A variable is a name that refers to a value stored in memory. It acts like a label that
allows you to access or change that value later.

Think of a variable as a container with a label.

age = 25

Here:

age is the variable (label).

25 is the value inside the container (memory).


3. Characteristics of Python Variables :

Feature Description

No Declaration You don’t need to declare the type before using a variable.

Dynamic Typing Python automatically detects the type of variable based on the value.

Case-sensitive Age and age are different variables in Python.

3. Real-Life Analogy

Imagine a jar with a label:

[age] → 25

The jar (age) holds the value 25. You can replace it anytime:

age = 30 # Now the jar contains 30 instead of 25

4. Identifiers

An identifier is the name used to identify variables, functions, classes, modules, etc.

It must follow the same rules as variable naming.

Valid:

Must begin with a letter (a-z, A-Z) or underscore (_)

Can contain letters, digits, and underscores

Use snake_case (e.g., user_name, total_amount)

Invalid:

Cannot start with a digit

Cannot use special characters like @, $, &, %, -, etc.

Cannot use Python reserved keywords (e.g., class, if, def, etc.)

Valid Examples Invalid Examples

name, user_age 2name, user-age

_score, price99 @price, def


5. Examples of Python Variables

name = "Rahul" # string

price = 99.99 # float

is_logged_in = True # boolean

age = 25 # integer

6. Keywords in Python :-

Keywords are reserved words that have special meaning in Python.

You cannot use them as identifiers (variable/function names).

Common Keywords:

if, else, while, for, class, def, return, True, False, None, import, try, except

To list all keywords:

import keyword

print(keyword.kwlist)

4. Basic Data Types in Python

Built-in Types:

Type Example Use Case

int 100, -7 Age, count of items

float 9.99, 3.14 Prices, temperature

str "hello" Names, messages

bool True, False Conditions, login status

NoneType None No value assigned


Example:

name = "Alice" # str

age = 30 # int

balance = 105.75 # float

is_admin = False # bool

address = None # NoneType

Real-life Examples:

str: Your name on an ID card

int: Number of books

float: Room temperature

bool: Light switch (on/off)

None: Empty parking slot

5. Operators in Python

Categories:

A. Arithmetic Operators

+ - * / % // **

x = 10

y=3

print(x + y) # 13

print(x ** y) # 1000

B. Comparison Operators

== != > < >= <=

a=5

b=8

print(a != b) # True

C. Logical Operators

and or not
print(True and False) # False

D. Assignment Operators

= += -= *= /= //= %= **=

total = 10

total += 5 # total = 15

E. Membership Operators

in, not in

fruits = ["apple", "banana"]

print("apple" in fruits) # True

F. Identity Operators

is, is not

x = y = [1, 2]

print(x is y) # True (same memory)

Type Conversion in Python

What is Type Conversion?

Changing one data type into another.

Python supports two types:

1. Implicit Conversion (Automatic)

Python automatically converts a smaller data type to a larger one.

x = 10 # int

y = 2.5 # float

result = x + y

print(result) # 12.5

print(type(result)) # <class 'float'>

int was converted to float automatically.


2. Explicit Conversion (Type Casting)

You manually convert using built-in functions:

int(): Converts to integer

float(): Converts to float

str(): Converts to string

bool(): Converts to boolean

# Convert float to int

a = 9.8

b = int(a)

print(b) # 9

# Convert int to string

x = 100

y = str(x)

print(y) # "100"

print(type(y)) # <class 'str'>

# Convert string to float

s = "3.14"

f = float(s)

print(f + 1) # 4.14

# Convert int to bool

print(bool(0)) # False

print(bool(5)) # True
Caution:

int("abc") # Error: invalid literal

Input and Output in Python :-

print() – Output to Screen

Syntax:

print(object, ..., sep=' ', end='\n')

print("Hello, World!")

print("Age:", 25)

print("Python", "is", "fun", sep="-")

Hello, World!

Age: 25

Python-is-fun

input() – Get Input from User

Syntax:

variable = input("Prompt message")

Real-life Example:

Taking user input like a form:

name = input("Enter your name: ")

print("Welcome,", name)

➢ Input is always a string by default.

Convert Input :-

age = int(input("Enter your age: "))

print("You will be", age + 1, "next year.")


QUESTIONS:

1. Which of these are valid variable names? (Choose all that apply)
A. 2score
B. _user
C. user-name
D. totalAmount

2. What will be the output?

price = 99.99

print(type(price))

3. What is the output?

x = 10

y = "5"

print(x + int(y))

4. Will this code work? If not, why?

a = "abc"

b = int(a)

5. What is the output of:

x=7

y=2

print(x // y)

6. Write a Python program that asks the user for their favorite color and prints a
message like:

"Your favorite color is Blue!"

7. What is the output of this code if input is 10?

age = int(input("Enter your age: "))

print("Next year you will be", age + 1)


Conditional Statements in Python (if, elif, else) :-

What are Conditionals?

Conditionals allow a program to make decisions and execute code only if a certain condition
is True.

Real-life Analogy:

"If it’s raining, take an umbrella. Else if it’s cloudy, take a jacket. Else, wear sunglasses."

if condition:

# code to run if condition is True

elif another_condition:

# code to run if first condition is False but this one is True

else:

# code to run if all above conditions are False.

Note: Indentation is critical in Python.

Python uses indentation (usually 4 spaces) to define code blocks.

Example:

age = int(input("Enter your age: "))

if age < 13:

print("Child")

elif age < 18:

print("Teenager")

else:

print("Adult")

Logical Operators Inside Conditions:

temp = 25

if temp > 20 and temp < 30:

print("Nice weather!")
Loops in Python :-

Loops are used to repeat a block of code as long as a certain condition is true. They help
avoid writing repetitive code.

1. while Loop

When to Use:

Use a while loop when you don’t know in advance how many times to run — you
loop until a condition becomes False.

while condition:

# repeat block

Example:

count = 1

while count <= 5:

print("Count:", count)

count += 1

What’s Happening:
Starts with count = 1

As long as count <= 5, it prints and increases the value

Stops when count becomes 6

Common Pitfall:

Don’t forget to update the variable (count += 1), or it may cause an infinite loop.

2. for Loop :-

When to Use:

Use for loops when you want to iterate:

Over a known range of numbers

Over an iterable (like a list, string, etc.)

for variable in iterable:

# block
Example:

for i in range(1, 6):

print("Number:", i)

range(1, 6) → 1 to 5 (not including 6)

Output: 1, 2, 3, 4, 5

range() Function

range(n) → 0 to n-1

range(start, stop) → start to stop-1

range(start, stop, step) → includes step (e.g., skip every second number)

for i in range(0, 10, 2):

print(i) # 0, 2, 4, 6, 8

Looping Through a List:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

print("I like", fruit)

break, continue, pass :-

Keyword Use Example Use Case

break Exit the loop early Stop loop if condition met

continue Skip current iteration Skip a value but continue

pass Do nothing (placeholder) Empty block for future use


break Example:

for i in range(1, 6):

if i == 4:

break # exits the loop when i is 4

print(i)

# Output:

#1

#2

#3

continue Example:

for i in range(1, 6):

if i == 3:

continue # skips printing 3

print(i)

# Output:

#1

#2

#4

#5

pass Example:

for i in range(3):

if i == 1:

pass # does nothing, placeholder

print("i =", i)

# Output:

#i=0

#i=1

#i=2
Nested Loops :-

Used when you need to loop inside another loop.

for i in range(1, 4):

for j in range(1, 3):

print(f"i={i}, j={j}")

# Output:

# i=1, j=1

# i=1, j=2

# i=2, j=1

# i=2, j=2

# i=3, j=1

# i=3, j=2

QUESTIONS:-

1. Count from 1 to 10 but skip 5

Use a for loop to print numbers from 1 to 10, but skip 5.

Uses: for, continue

2. Print First 3 Even Numbers in Range

Use a loop and break to print only the first 3 even numbers from 1 to 20.

Uses: for, if, break

3. Simple Password Checker

Ask the user for a password. Keep asking until the correct one is entered.

Uses: while, input, conditionals

4. Print All Odd Numbers from 1 to 15

Write a loop to print all odd numbers between 1 and 15.

Uses: for, if, continue


5. Nested Loop Pattern

Print the following using nested loops:

11

12

21

22

Uses: nested for loops

6. Loop With pass

Loop from 0 to 4, and use pass when the number is 2. Just for syntax practice.

Uses: for, pass

7. Sum of First N Numbers

Ask the user for a number n, and calculate the sum of the first n natural numbers
using a loop.

Uses: for, input, arithmetic

8. Temperature Advisor

Ask for a temperature. Use if-elif-else:

< 10: "Very Cold"

10–20: "Cold"

21–30: "Nice Weather"

>30: "Hot"

Uses: logical conditions

9. Count Down With While

Start from 10 and count down to 1 using a while loop.

Uses: while, decrementing loop

count = 10

while count >= 1:

print(count)

count -= 1
What is a Data Structure?

Definition:

A data structure is a way of organizing and storing data in memory so it can be accessed and
modified efficiently.

Why Do We Need Data Structures?

To handle large and complex data.

To perform faster searching, sorting, and manipulation.

To use memory efficiently.

To write clean, optimized, and scalable code.

What is a List?

A list is an ordered, changeable (mutable) collection of items.

It can contain different data types: numbers, strings, booleans, etc.

my_list = [1, 2, 3, "apple", True]

Why Use Lists?

➢ Store multiple values in one variable


➢ Add, remove, or change items anytime
➢ Useful for loops, data processing, etc.

Basic Operations :-

fruits = ["apple", "banana", "cherry"]

print(fruits[0]) # apple (access by index)

fruits[0] = "grape" # change item

fruits.append("orange") # add item at end

del fruits[1] # delete item by index

print(fruits) # ['grape', 'cherry', 'orange']


Common List Methods (with Examples)

1. .append(x) – Add item at the end

nums = [1, 2, 3]

nums.append(4)

print(nums) # [1, 2, 3, 4]

2. .insert(i, x) – Insert at specific index

nums = [1, 2, 4]

nums.insert(2, 3)

print(nums) # [1, 2, 3, 4]

3. .pop(i) – Remove item at index (default: last item)

nums = [1, 2, 3]

nums.pop()

print(nums) # [1, 2]

nums.pop(0)

print(nums) # [2]

4. .remove(x) – Remove first occurrence of value

fruits = ["apple", "banana", "apple"]

fruits.remove("apple")

print(fruits) # ['banana', 'apple']

5. .sort() – Sort list (in-place)

nums = [5, 2, 9, 1]

nums.sort()

print(nums) # [1, 2, 5, 9]
6. .reverse() – Reverse the list

nums = [1, 2, 3]

nums.reverse()

print(nums) # [3, 2, 1]

7. .count(x) – Count occurrences

nums = [1, 2, 2, 3, 2]

print(nums.count(2)) # 3

Looping Through a List :-

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

print("I like", fruit)

List Slicing:

a = [10, 20, 30, 40, 50]

print(a[1:4]) # [20, 30, 40]

print(a[::-1]) # Reverse list

List Comprehension:

What is it?

A shortcut way to create a new list using a single line of code.

Without List Comprehension (Normal Way)

squares = []

for x in range(1, 6):

squares.append(x**2)

print(squares)

With List Comprehension (One-Line Way)

squares = [x**2 for x in range(1, 6)]

print(squares)

Output: [1, 4, 9, 16, 25]


It does the same thing but is shorter and cleaner.

List Comprehension with Condition

even = [x for x in range(10) if x % 2 == 0]

print(even)

Output: [0, 2, 4, 6, 8]

This makes a list of even numbers only.

Think Like:

"Take x from 0 to 9 only if x is even, and put it in a list."

Format:

[expression for item in iterable if condition]

Tuples in Python

What is a Tuple?

A tuple is like a list, but you cannot change it once it's created.

person = ("Alice", 25, "Engineer")

Key Features of Tuples:

Feature Meaning

Ordered Keeps items in the same order

Immutable You cannot add, remove, or change items

Faster Faster than lists when reading data

Fixed Data Great for things like coordinates, dates, etc.

Accessing Tuple Elements

Just like a list:

print(person[0]) # Output: Alice


print(len(person)) # Output: 3

Tuple Packing and Unpacking

Packing means putting values into a tuple:

a = 1, 2, 3 # This makes a tuple (1, 2, 3)

Unpacking means taking the values out:

x, y, z = a

print(x) # 1

print(y) # 2

print(z) # 3

Can You Change a Tuple?

No. This will cause an error:

person[1] = 30 # Not allowed

When to Use Tuples?

➢ When your data should never change


➢ When you want faster performance
➢ When grouping simple values together (e.g., (x, y) coordinates)

13. Unpacking Tuple:

student = ("John", 20, "B.Tech")

name, age, course = student

print(f"{name} is {age} years old and studies {course}")

Interesting & Fun Questions

1. Tuple Quiz:

t = (1, 2, [3, 4])

t[2][0] = 99

print(t) # (1, 2, [99, 4]) — Tuple itself is immutable, but its mutable elements can
change.
2. Guess the Output:

list1 = [1, 2, 3]

list2 = [1, 2, 3]

print(set([tuple(list1), tuple(list2)]))

# {(1, 2, 3)} => Because tuples are hashable and duplicates are removed in sets

3. Quiz: Tuple or Not?

a = (1)

b = (1,)

print(type(a)) # <class 'int'>

print(type(b)) # <class 'tuple'>

Sets in Python :-
What is a Set?

A set is:

Unordered: No specific order

Unindexed: No index access (like s[0])

Mutable: You can add or remove items

Unique: No duplicate items allowed

nums = {1, 2, 3, 3, 4}

print(nums) # {1, 2, 3, 4}

Why Use Sets?

To store unique values

Fast membership tests (x in s)

Perform math-like operations: union, intersection, etc.


Common Set Methods :-

1. .add(x) – Add one item

s = {1, 2, 3}

s.add(4)

print(s) # {1, 2, 3, 4}

2. .remove(x) – Remove specific item (error if not present)

s = {1, 2, 3}

s.remove(2)

print(s) # {1, 3}

3. .discard(x) – Remove item (no error if missing)

s = {1, 2}

s.discard(3) # no error

print(s) # {1, 2}

4. .update(iterable) – Add multiple items

s = {1}

s.update([2, 3])

print(s) # {1, 2, 3}

5. .clear() – Remove all items

s = {1, 2}

s.clear()

print(s) # set()

Set Operations (Using Math-Like Symbols)

a = {1, 2, 3}

b = {3, 4, 5}

1. Union (a | b)

Combines all unique elements from both sets.

print(a | b) # {1, 2, 3, 4, 5}
Adds all values, no duplicates.

2. Intersection (a & b)

Finds items common to both sets.

print(a & b) # {3}

Only 3 exists in both.

3. Difference (a - b)

Gets items in a that are not in b.

print(a - b) # {1, 2}

Removes anything from a that's also in b.

4. Symmetric Difference (a ^ b)

Gets items in either set but not both.

print(a ^ b) # {1, 2, 4, 5}

Keeps non-common values only.

Dictionaries in Python :-
What is a Dictionary?

A dictionary is a collection of data in key-value pairs.

student = {"name": "John", "age": 21, "grade": "A"}

Keys must be unique and immutable (like strings or numbers).

Values can be any data type.

Dictionaries are unordered (but preserve order in Python 3.7+).

Mutable: You can change or update them.

Accessing and Modifying

print(student["name"]) # John

student["age"] = 22 # Update value

student["college"] = "ABC" # Add new key-value pair

print(student)

# {'name': 'John', 'age': 22, 'grade': 'A', 'college': 'ABC'}


Dictionary Methods :-

1. .keys() → Get all keys

print(student.keys()) # dict_keys(['name', 'age', 'grade', 'college'])

2. .values() → Get all values

print(student.values()) # dict_values(['John', 22, 'A', 'ABC'])

3. .items() → Get key-value pairs

print(student.items())

# dict_items([('name', 'John'), ('age', 22), ('grade', 'A'), ('college', 'ABC')])

4. .get("key") → Safe access

print(student.get("name")) # John

print(student.get("city")) # None (doesn’t throw an error if key not found)

5. .pop("key") → Remove a key

student.pop("grade")

print(student)

# {'name': 'John', 'age': 22, 'college': 'ABC'}

renaming the key "name" to "first_name".

you can’t directly rename a key, but you can simulate it by:

student = {"name": "John", "age": 21, "grade": "A"}

What student.pop("name") does:

Removes the key "name" from the dictionary.

Returns its value → "John"

So after this:

"name" key is gone

"John" is returned
3. Assign to a new key:

student["first_name"] = "John"

Looping Through a Dictionary

for key, value in student.items():

print(key, ":", value)

Output:

name : John

age : 22

college : ABC

Enumerate:-

enumerate() adds a counter to an iterable and returns each item with its index (which can
start from any number).

Used for looping when you need both index and value.

for i, val in enumerate(['a', 'b'], 1):

print(i, val)

1a

2b
What is a Function in Python ?
Definition:

A function is a block of reusable code that performs a specific task when called.

You define it once and use it many times, which helps keep your code clean and organized.

Why Use Functions?

Benefit Explanation

Avoid
Follow the DRY principle: Don’t Repeat Yourself.
Repetition

Easier Fix a bug in one place, not in multiple lines of repeated


Debugging code.

Modular Code Break big programs into smaller, logical parts (functions).

Better
Makes your code easier to read and understand.
Readability

Use the same function in different parts of the program


Reusability
without rewriting.

Example:

def greet(name):

print(f"Hello, {name}!")

greet("Alice")

greet("Bob")

Output:

Hello, Alice!

Hello, Bob!

The function greet() is defined once and used multiple times.


2. Creating Your Own Function (User-Defined)

Syntax:

def function_name(parameters):

# code block

return result

def: Keyword to define a function

function_name: Any valid name you choose

parameters: Inputs your function can accept

return: Sends back the result (optional)

def greet(name):

return f"Hello, {name}!"

print(greet("Alice")) # Output: Hello, Alice!

What’s Happening:

greet("Alice") calls the function with "Alice" as the argument.

The function returns the string "Hello, Alice!".

What are Function Arguments?

When we define a function in Python, we often want to pass data into it. These
pieces of data are called arguments, and the variables that receive them are called
parameters.

Why do we need them?

Arguments make functions reusable and dynamic. Instead of hardcoding values, we


can pass different inputs and get customized outputs.

Types of Function Arguments in Python


Python supports several types of function arguments to give flexibility when calling
functions:

A. Positional Arguments

Definition:

Arguments passed to a function in the same order as the parameters are defined

def add(a, b):

return a + b

print(add(2, 3)) # Output: 5

How it works:

a gets 2

b gets 3

Returns 5

Why Needed:

Simple and clear when the number of arguments is fixed and known.

Useful when argument order is meaningful.

B. Default Arguments

Definition:

Parameters can be given default values. If no value is passed during function call, the
default is used.

def greet(name="User"):

return f"Hi, {name}!"

print(greet()) # Output: Hi, User!

print(greet("Alice")) # Output: Hi, Alice!

How it works:

If name is not given → uses "User"


If provided (e.g., "Alice") → overrides default

Why Needed:

Makes functions more flexible

Avoids errors from missing arguments

Good for optional settings or fallback values

C. Variable-Length Positional Arguments (*args)

Definition:

Use *args to accept any number of positional arguments. They are stored as a tuple.

def total(*numbers):

return sum(numbers)

print(total(1, 2, 3, 4)) # Output: 10

How it works:

*numbers collects all arguments → (1, 2, 3, 4)

sum(numbers) returns 10

Why Needed:

Useful when number of arguments is unknown

Helps create flexible functions (e.g., logging, calculators)

D. Variable-Length Keyword Arguments (**kwargs)

Definition:

Use **kwargs to accept any number of keyword arguments. They are stored in a
dictionary.

def student_info(**info):

print(info)
student_info(name="John", age=20)

# Output: {'name': 'John', 'age': 20}

How it works:

**info collects named arguments into a dictionary

Why Needed:

Useful when you want to allow optional or named configuration

Great for APIs, forms, or flexible user inputs

Accessing Specific Keys

def student_info(**info):

print("Name:", info.get("name"))

print("Age:", info.get("age"))

student_info(name="Alice", age=22)

Name: Alice

Age: 22

4. return Statement in Python

What it Does:

The return statement is used to send back a value from a function to the caller. It
exits the function and optionally passes a value back.

Basic Syntax

def function_name(parameters):

# some code

return value
Example:

def multiply(x, y):

return x * y

result = multiply(3, 4)

print(result) # Output: 12

Explanation:

multiply(3, 4) → computes 3 * 4 = 12

return 12 sends 12 back to the place where the function was called

result stores that value

print(result) prints 12

Why return is Important

Feature Benefit

Sends output Gives result back to caller

Ends function Control returns to caller line

Enables composition Functions can be chained or reused

Stores value Output can be saved or used further

Key Points

1. return Ends Function

Once return runs, the function stops immediately:

def test():

print("Before return")

return

print("After return") # Never runs


test()

Output:

Before return

2. Returning Multiple Values

Python allows returning multiple values (as a tuple):

def divide_and_remainder(a, b):

return a // b, a % b

quotient, remainder = divide_and_remainder(10, 3)

print(quotient, remainder) # Output: 3 1

3. Returning Nothing

If no return or just return without a value is used, Python returns None by default.

def do_nothing():

pass

print(do_nothing()) # Output: None

4. return vs print

Feature return print

Sends value back Yes No

Used in logic Yes No

Shows on screen No Yes (for display)

Stores result Yes No


5. Lambda Functions
What is a Lambda?

A lambda function is a one-line anonymous function in Python.

It’s used when you need a small function temporarily without formally defining it
using def.

Syntax: lambda arguments: expression

lambda → keyword

arguments → parameters (can be multiple)

expression → single return expression (no return keyword used)

square = lambda x: x * x

print(square(5)) # Output: 25

Explanation:

lambda x: x * x creates an unnamed function that returns x * x

It's assigned to square

Calling square(5) returns 25

Why Use Lambda Functions?

Use Case Why It's Useful

Short, throwaway functions No need to write a full def block

Functional programming tools Works with map(), filter(), sorted()

Cleaner code Makes inline logic readable

Anonymous use No function name required


What Is a Module?
Definition:

A module in Python is simply a file with the .py extension that contains Python
definitions and statements—such as functions, classes, or variables—which can be imported
into other Python files.

Example:

Imagine you have a file named math_utils.py with the following content:

# math_utils.py

def add(a, b):

return a + b

def subtract(a, b):

return a - b

You can now use this file (module) in another Python script:

# main.py

import math_utils

print(math_utils.add(5, 3)) # Output: 8

print(math_utils.subtract(5, 3)) # Output: 2

Importing Modules

1. Import the entire module

import math

print(math.sqrt(16)) # Output: 4.0

2. Import specific function(s)

from math import sqrt

print(sqrt(25)) # Output: 5.0


Why Use Modules?

Using modules in Python brings several advantages:

Benefit Explanation

You can define a function or class once in a module and reuse it


Code Reuse
anywhere.

Better Instead of putting everything in one file, you can split code by
Organization functionality.

Follow the DRY (Don't Repeat Yourself) principle by avoiding duplicate


Avoid Redundancy
code.

Maintainability Code that is modular is easier to test, update, and scale.

Summary

A module is one of the most fundamental building blocks in Python. It helps break your code
into reusable, logical units, making it easier to maintain, test, and scale. Whether you’re
writing a simple script or a large application, modular code is cleaner and more professional.

What Is a Package ?
Definition:

A package in Python is a collection of modules grouped together in a folder. It allows


you to organize code into hierarchical directories to improve structure and scalability.

The presence of __init__.py in the folder tells Python:

“This folder is a package, and its contents can be imported.”

Folder Structure Example:

myapp/

├── mathpkg/ ← This is a package (because of __init__.py)

│ ├── __init__.py ← Makes this folder a package

│ └── basic.py ← A module inside the package


basic.py contents:

# basic.py

def multiply(x, y):

return x * y

How to Use It:

from mathpkg.basic import multiply

print(multiply(2, 5)) # Output: 10

3. Python Standard Library Overview


What Is It?

The Python Standard Library is a massive collection of built-in modules that come
bundled with Python. You don’t need to install anything extra — they’re ready to use!

These modules cover everything from math and file handling to web protocols and
data formats.

Categories & Examples:

Category Example Modules What They Do

Math & math, random, decimal, Perform calculations, generate random


Numbers fractions numbers

Dates & Time datetime, time, calendar Work with dates, times, delays

Read, write, move, or manage files and


File I/O os, shutil, pathlib, io
directories

urllib, http, socket, Handle URLs, network sockets, or open web


Internet
webbrowser pages

Read/write structured data like JSON and


Data Formats json, csv, xml, pickle
CSV

Interact with the OS and system-level


System & OS sys, platform, getpass
settings
Example Use Cases:

Math & Numbers

1. math

import math

print(math.sqrt(25)) # 5.0

print(math.factorial(5)) # 120

print(math.pi) # 3.141592653589793

2. random

import random

print(random.choice(['red', 'blue', 'green'])) # Random color

print(random.randint(1, 10)) # Random number between 1 and 10

Dates & Time

1. datetime

from datetime import datetime

now = datetime.now()

print(now.strftime("%d-%m-%Y"))

2. time

import time

time.sleep(2) # Pauses for 2 seconds

print("Done")

3. calendar

import calendar

print(calendar.month(2025, 6)) # Prints June 2025 calendar


File I/O
1. os

import os

print(os.listdir()) # List files in current directory

2. shutil

import shutil

shutil.copy("file.txt", "backup.txt") # Copy file

3. pathlib

from pathlib import Path

p = Path("example.txt")

print(p.exists()) # True/False

Internet
1. urllib

from urllib.request import urlopen

response = urlopen("https://www.example.com")

print(response.status) # 200

2. http

from http.client import HTTPConnection

conn = HTTPConnection("example.com")

conn.request("GET", "/")

print(conn.getresponse().status) # 200

Data Formats
1. json

import json
print(json.loads('{"x": 1}')) # {'x': 1}

2. csv

import csv

with open('data.csv', mode='w', newline='') as f:

writer = csv.writer(f)

writer.writerow(['name', 'age'])

writer.writerow(['Alice', 30])

System & OS

1. sys

import sys

print(sys.version) # Python version

2. platform

import platform

print(platform.system()) # OS name (e.g., 'Windows', 'Linux')

1. Introduction to File Handling in Python


Files are how we store data permanently on a computer. In Python, you can create, read,
update, and delete files easily using built-in functions.

There are two main types of files you will work with:

Text files: Store data as readable text (letters, numbers, symbols).

Binary files: Store data as bytes (used for images, videos, executables, etc.).

2. Opening Files: File Modes


When opening a file in Python, you must specify the mode. The mode tells Python what
you want to do with the file.
Here are the common file modes:

Mode Meaning

'r' Read only (file must exist).

'w' Write only (creates file or overwrites).

'a' Append (write data at the end).

'r+' Read and write (file must exist).

'w+' Write and read (overwrites existing file).

'a+' Append and read (creates file if not exists).

'rb' Read binary file.

'wb' Write binary file.

3. Reading Text Files


To read the entire content of a file:

with open("example.txt", "r") as file:

content = file.read() # Reads whole file as a string

print(content)

or

f = open("example.txt", "r") # open for reading

print(f.read())

f.close() # always close file

with open(...) automatically closes the file after you are done.

'r' mode means read-only.

file.read() reads the whole file at once.


To read the file line by line:

with open("example.txt", "r") as file:

for line in file:

print(line.strip()) # strip() removes the newline characters

4. Writing to Files
To write new content to a file, use 'w' mode:

with open("example.txt", "w") as file:

file.write("Hello World\n")

file.write("This is a new line\n")

If the file already exists, it will be overwritten.

If the file doesn’t exist, Python will create it.

Use \n to create new lines.

To append data without deleting existing content, use 'a' mode:

with open("example.txt", "a") as file:

file.write("This line will be added at the end.\n")

5. Reading and Writing in the Same File (w+ mode)


If you want to write and then read the same file in one go, use 'w+' mode:

with open("example.txt", "w+") as file:

file.write("Hello World\n")

file.write("This is a new line\n")

# Move the cursor back to the start of the file

file.seek(0)
# Now read the content

content = file.read()

print(content)

Important:

When you write to a file, the file cursor moves to the end. To read from the beginning, you
must move the cursor back using file.seek(0).

If you forget file.seek(0), reading will return an empty string because the cursor is already
at the end.

6. Binary File Operations


Binary files store data in bytes, not text. You must open such files in binary mode ('rb' for
reading, 'wb' for writing).

Example: Writing to a binary file

with open("example.bin", "wb") as file:

file.write(b"Hello in binary") # Note the b'' to indicate bytes

Example: Reading from a binary file

with open("example.bin", "rb") as file:

content = file.read()

print(content) # Output will be bytes, like b'Hello in binary'

7. Practical Example: Copy File Content


You can read content from one file and write it to another easily:

with open("source.txt", "r") as source_file:

content = source_file.read()

with open("destination.txt", "w") as dest_file:

dest_file.write(content)
If destination.txt does not exist, Python will create it.

8. Count Lines, Words, and Characters


Here is a sample function to read a file and count:

Number of lines

Number of words

Number of characters

def count_file_stats(filename):

with open(filename, 'r') as file:

num_lines = 0

num_words = 0

num_chars = 0

for line in file:

num_lines += 1

num_words += len(line.split())

num_chars += len(line)

return num_lines, num_words, num_chars

lines, words, chars = count_file_stats("example.txt")

print(f"Lines: {lines}, Words: {words}, Characters: {chars}")

9. Key Points to Remember


Always use with open(...) to open files. It ensures files close automatically.

Be careful with write modes — 'w' and 'w+' overwrite existing files.
Use file.seek(0) to reset cursor to start if reading after writing.

Use 'rb' and 'wb' for binary files.

Use 'a' or 'a+' to add content without deleting existing data.

Working with Directories and Paths in Python Using os Module

1. Creating a New Directory

To create a new folder (directory) in Python, you use the os module.

import os

# Name of the new directory

new_directory = "package"

# Create the directory in the current working directory

os.mkdir(new_directory)

# Confirm creation

print(f"Directory '{new_directory}' created successfully!")

Explanation:

os.mkdir() creates a folder named "package" inside the current folder where your Python
script is running.

If the folder already exists, this will raise an error, so you may want to handle that in real
projects.

2. Listing All Files and Folders in a Directory

You might want to see all files and folders inside a folder. Use os.listdir() for that.

import os
# List all files and folders in the current directory

items = os.listdir(".")

print("Files and folders in current directory:")

for item in items:

print(item)

Explanation:

"." means current directory.

os.listdir() returns a list of all files and folders inside the specified directory.

3. Joining Paths Correctly with os.path.join

Different operating systems use different symbols for paths (/ on Linux/Mac, \ on Windows).

To avoid errors, always join paths using os.path.join.

import os

folder_name = "folder"

file_name = "file.txt"

# Correct way to join folder and file name into a full path

full_path = os.path.join(folder_name, file_name)

print(f"Full path: {full_path}")

Output example on Windows:

folder\file.txt

On Linux/Mac:

folder/file.txt
4. Getting the Absolute Path

Sometimes you want the complete path of a file/folder, not just relative to current directory.

import os

relative_path = "folder/file.txt"

# Get absolute path

abs_path = os.path.abspath(relative_path)

print(f"Absolute path: {abs_path}")

5. Checking if a File or Directory Exists

Before working on a file/folder, check if it exists:

import os

path = "example1.txt"

if os.path.exists(path):

print(f"The path '{path}' exists.")

else:

print(f"The path '{path}' does not exist.")

6. Checking Specifically if It Is a File or a Directory

Sometimes you want to know if a path points to a file or a folder:

import os

path = "example.txt"

if os.path.isfile(path):

print(f"'{path}' is a file.")

elif os.path.isdir(path):

print(f"'{path}' is a directory.")

else:

print(f"'{path}' is neither a file nor a directory.")


7. Putting It Together: Create File If Not Exists

Here’s how to check if a file exists, and create it if it doesn’t:

import os

filename = "example1.txt"

if os.path.exists(filename):

print(f"File '{filename}' already exists.")

else:

# Create a new file

with open(filename, 'w') as file:

file.write("This is a new file created because it did not exist.\n")

print(f"File '{filename}' created successfully.")

8. Using Current Working Directory

To get the folder where your script is currently running, use:

import os

cwd = os.getcwd()

print(f"Current working directory: {cwd}")

You can combine this with path joining:

import os

cwd = os.getcwd()

folder_name = "package"

file_name = "example.txt"

full_path = os.path.join(cwd, folder_name, file_name)

print(f"Full file path: {full_path}")


Common Python Error Types
1. ZeroDivisionError

Occurs when you divide by zero.

10 / 0 # ZeroDivisionError

2. ValueError

Happens when a function receives the correct data type but an invalid value.

int("abc") # ValueError

3. TypeError

Raised when an operation is applied to an object of inappropriate type.

"abc" + 5 # TypeError

4. IndexError

Accessing an invalid index in a list or tuple.

lst = [1, 2]

print(lst[5]) # IndexError

5. KeyError

Accessing a non-existent key in a dictionary.

d = {"name": "Alice"}

print(d["age"]) # KeyError

6. FileNotFoundError

Trying to open a file that doesn’t exist.

open("missing.txt") # FileNotFoundError
7. NameError

Using a variable that hasn’t been defined.

print(xyz) # NameError

8. AttributeError

Calling an attribute or method that doesn't exist.

x=5

x.append(3) # AttributeError

1. What is Exception Handling?


Exceptions are errors detected during execution.

Exception handling lets you gracefully handle errors without crashing the program.

2. Basic Structure: try-except

try:

# Code that might raise an error

except ErrorType:

# Code to handle the error

try:

result = 10 / int(input("Enter a number: "))

except ZeroDivisionError:

print("Enter denominator greater than zero")

except ValueError:

print("Not a valid number")


3. Generic Exception Handling
Catch all other exceptions using except Exception as e:.

except Exception as e:

print(e)

Why use generic exception handling?

When debugging: Helps catch unexpected errors and print/log them.

As a fallback: If you want to make sure your program doesn't crash and you log
unexpected errors for later analysis.

4. else Block
Runs only if no exception occurs in the try block.

try:

num = int(input("Enter a number: "))

result = 10 / num

except ZeroDivisionError:

print("You can't divide by zero")

except ValueError:

print("Invalid number")

else:

print("The result is:", result)

5. finally Block
Executes no matter what, whether exception occurs or not.

Used to clean up resources (e.g., closing files, DB connections).

try:

num = int(input("Enter a number: "))


result = 10 / num

except Exception as e:

print(e)

else:

print("The result is:", result)

finally:

print("Execution complete")

6. Real-Life Use Case: Database Connection


try:

connection = connect_to_db()

# operations

except ConnectionError:

print("Database connection failed")

finally:

if connection:

connection.close()

print("Connection closed")

7. Best Practices
Use specific exceptions (ValueError, ZeroDivisionError) before generic (Exception).

Always close resources in finally.

Use else for code that should run only when no error occurs.
Working with JSON:

1. Start with Real-Life Use Case

Introduce Scenario:

"Imagine we are building a student management system where we store student records
like name, age, and marks in a file."

2. Explain What JSON Is

JSON = JavaScript Object Notation (but language-independent)

It is used for data storage and transfer

Format is like a Python dictionary or list

3. Show Basic Conversion

Step A: Python dict → JSON string

import json

student = {"name": "Aman", "age": 17, "marks": {"Math": 80, "English": 75}}

json_str = json.dumps(student, indent=4)

print(json_str)

Explain:

dumps() = dict to string

indent=4 = makes it readable

Step B: Save to File

with open("student.json", "w") as f:

json.dump(student, f, indent=4)

Explain:

dump() = dict to file


4. Read from JSON File

with open("student.json", "r") as f:

data = json.load(f)

print(data)

print(data["marks"]["Math"])

Explain:

load() = file to dict

5. Modify JSON Data

data["marks"]["Science"] = 89

with open("student.json", "w") as f:

json.dump(data, f, indent=4)

Explain:

Update dict like normal Python, then write again

Handling Multiple Data

1: Save Multiple Students

import json

students = [

"name": "Aman",

"age": 17,

"marks": {

"Math": 80,

"English": 75,

"Science": 89

}
},

"name": "Riya",

"age": 18,

"marks": {

"Math": 85,

"English": 78,

"Science": 92

with open("student.json", "w") as f:

json.dump(students, f, indent=4)

2: Read and Display Students

with open("student.json", "r") as f:

students = json.load(f)

for student in students:

print("Name:", student["name"])

print("Age:", student["age"])

print("Marks:")

for subject, mark in student["marks"].items():

print(f" {subject}: {mark}")

print("-" * 20)
3: Update a Student (e.g., update Aman's Math mark)

# Load existing data

with open("student.json", "r") as f:

students = json.load(f)

# Update Aman's math marks

for student in students:

if student["name"] == "Aman":

student["marks"]["Math"] = 90 # New value

# Save updated data

with open("student.json", "w") as f:

json.dump(students, f, indent=4)

# Add a New Student

new_student = {

"name": "Karan",

"age": 17,

"marks": {

"Math": 77,

"English": 81,

"Science": 85

with open("student.json", "r") as f:

students = json.load(f)

students.append(new_student)
with open("student.json", "w") as f:

json.dump(students, f, indent=4)

B. Working API Format Data

1. Save Multiple Students as Dictionary

import json

students = {

"Aman": {

"age": 17,

"marks": {

"Math": 80,

"English": 75,

"Science": 89

},

"Riya": {

"age": 18,

"marks": {

"Math": 85,

"English": 78,

"Science": 92

with open("student.json", "w") as f:


json.dump(students, f, indent=4)

2. Read and Display Students

with open("student.json", "r") as f:

students = json.load(f)

for name, data in students.items():

print("Name:", name)

print("Age:", data["age"])

print("Marks:")

for subject, mark in data["marks"].items():

print(f" {subject}: {mark}")

print("-" * 20)

3. Update a Student (e.g., Update Aman's Math Marks)

with open("student.json", "r") as f:

students = json.load(f)

# Update

students["Aman"]["marks"]["Math"] = 90

# Save

with open("student.json", "w") as f:

json.dump(students, f, indent=4)

4. Add a New Student

new_student = {

"age": 17,

"marks": {

"Math": 77,
"English": 81,

"Science": 85

with open("student.json", "r") as f:

students = json.load(f)

# Add new student

students["Karan"] = new_student

# Save

with open("student.json", "w") as f:

json.dump(students, f, indent=4)

NumPy Array :-
1. What is NumPy?

NumPy (Numerical Python) is a powerful Python library used for numerical computing,
providing support for multi-dimensional arrays, mathematical functions, and fast vectorized
operations, backed by optimized C code.

Key Features:

Efficient array handling (ndarray)

Fast operations without loops (vectorized)

Linear algebra, statistics, and more

Foundation for libraries like Pandas, Scikit-learn, TensorFlow, etc.


Difference Between List and NumPy Array:

Feature Python List NumPy Array

Data Type Mixed types allowed Same type (homogeneous)

Performance Slower Faster (compiled in C)

Memory Usage Higher Lower

Operations Manual loops Vectorized (faster)

Functionalities Basic Advanced math & stats

2. Creating NumPy Arrays

A.Using np.array()

import numpy as np

arr1 = np.array([1, 2, 3]) # 1D

arr2 = np.array([[1, 2], [3, 4]]) # 2D

arr3 = np.array([[[1], [2]], [[3], [4]]]) # 3D

B.Using Built-in Functions

np.zeros((2, 3)) # 2x3 array of zeros

np.ones((3, 3)) # 3x3 array of ones

np.full((2, 2), 7) # 2x2 array filled with 7

np.eye(3) # 3x3 Identity matrix

np.arange(0, 10, 2) # [0, 2, 4, 6, 8]

np.linspace(0, 1, 5) # [0. , 0.25, 0.5 , 0.75, 1.] Creates an array of evenly spaced values
over a specified interval.
By default the arry elements will be of float so if you want it in int:

Use the dtype parameter:

arr = np.zeros((2, 3), dtype=int)

print(arr.dtype)

Output:

int64 (or int32 depending on your system/platform)

Why does NumPy convert all elements to strings in this array?

import numpy as np

arr1 = np.array([1, "2", 3])

print(arr1)

Output:

['1' '2' '3']

Explanation:

NumPy arrays require all elements to be of the same data type (dtype).

This is for performance and memory efficiency.

In our list:

[1, "2", 3]

1 → integer (int)

"2" → string

3 → integer (int)

NumPy sees mixed types → upcasts to the most general type, which is string in this
case.

Type Conversion Rules in NumPy (Simplified)

When mixed types are found:


If types include... NumPy converts all to...

int and float float

int and string string

float and string string

Check the dtype:

print(arr1.dtype)

# Output: <U21 (U = Unicode string)

Summary

NumPy auto-converts data types for consistency.

If even one element is a string, all elements become strings.

Tip: To force a specific type:

arr1 = np.array([1, "2", 3], dtype=int) # Will raise an error due to "2" being string

To prevent automatic conversion, keep data types consistent in your input list.

3.Array Attributes

arr = np.array([[1, 2, 3], [4, 5, 6]])

Attribute Example Output Meaning

arr.shape (2, 3) 2 rows, 3 columns

arr.ndim 2 2D array

arr.size 6 6 total elements

arr.dtype int64 Elements are integers


4.Indexing & Slicing

A.Indexing

arr[1, 2] # Element at 2nd row, 3rd column

B.Slicing

arr[0:2, 1:] # Rows 0-1, Columns 1-end

arr[:, 0] # All rows, 1st column

C.Fancy Indexing

arr[[0, 1], [1, 2]] # Selects elements (0,1) and (1,2)

What does arr[[0, 1], [1, 2]] do?

The first list: [0, 1] refers to row indices

The second list: [1, 2] refers to column indices

Now, NumPy pairs up the values element-wise, like this:

Row Index Column Index arr[row, col]

0 1 arr[0, 1] = 2

1 2 arr[1, 2] = 6

D. Boolean Masking

arr[arr > 2] # All elements greater than 2

5. Array Modification

arr[0, 0] = 10 # Set element

arr[:, 1] = 5 # Set entire column to 5

arr[1,:] = 100 # Set rows 2 all coloumns 100


6. Reshaping and Flattening

arr.reshape(3, 2) # Change shape

arr.flatten() # Convert to 1D

arr.T # Transpose

7. Arithmetic Operations in NumPy


A. Element-wise Operations

Element-wise operations apply arithmetic operators to each element pairwise between


two arrays of the same shape.

Assume:

import numpy as np

a = np.array([1, 2, 3])

b = np.array([4, 5, 6])

Now, let’s go through the operations:

1. a + b

Performs element-wise addition:

a + b # Output: array([5, 7, 9])

Explanation:

1+4=5

2+5=7

3+6=9

2. a - b

Element-wise subtraction:

a - b # Output: array([-3, -3, -3])

3. a * b

Element-wise multiplication (not matrix multiplication):

a * b # Output: array([4, 10, 18])


4. a / b

Element-wise division:

a / b # Output: array([0.25, 0.4 , 0.5 ])

5. np.add(a, b)

Same as a + b, but using a function form:

np.add(a, b) # Output: array([5, 7, 9])

6. np.multiply(a, b)

Same as a * b:

np.multiply(a, b) # Output: array([4, 10, 18])

Why use functions like np.add()?


They're useful when you want to pass the operation as a function argument.

Often more readable in complex pipelines.

Some may offer performance benefits in specific contexts (e.g. memory control).

B. Aggregate Functions

These are operations that reduce an array to a single value or summary across a specific
axis.

Assume:

arr = np.array([1, 2, 3, 4])

1. np.sum(arr)

Sum of all elements:

np.sum(arr) # Output: 10

2. np.min(arr)

Minimum element:

np.min(arr) # Output: 1

3. np.max(arr)

Maximum element:
np.max(arr) # Output: 4

4. np.cumsum(arr)

Cumulative sum:

np.cumsum(arr) # Output: array([ 1, 3, 6, 10])

Explanation: [1, 1+2, 1+2+3, 1+2+3+4]

5. np.prod(arr)

Product of all elements:

np.prod(arr) # Output: 24

Explanation: 1 × 2 × 3 × 4 = 24

Bonus: Working with Multi-dimensional Arrays

Assume:

arr2d = np.array([[1, 2], [3, 4]])

You can use aggregate functions along axes:

np.sum(arr2d, axis=0) → sum column-wise: [4, 6]

np.sum(arr2d, axis=1) → sum row-wise: [3, 7]

Statistical Functions

A. Mean (np.mean)

What it is:

Average of all values.

Use case:

To get a general idea of a dataset.

Example:

Average temperature over a week.


B. Median (np.median)

What it is:

Middle value when data is sorted.

Use case:

Best for skewed data (less affected by outliers).

Example:

Median income in a city (not skewed by a few billionaires).

import numpy as np

data = [50, 20, 80]

print(np.median(data)) # Output: 50.0

Even though [50, 20, 80] is not sorted, np.median() sorts it to [20, 50, 80] and returns
the middle: 50.

C. Standard Deviation (np.std)

What it is:

How spread out the data is from the mean.

Use case:

To measure consistency or variability.

Example:

Consistency of a student's test scores.

D. Variance (np.var)

What it is:

Average of squared differences from the mean (std²).

Use case:

To calculate risk or volatility.

Example:

Stock price fluctuation over time.


E. Percentile (np.percentile)

What it is:

Value below which a percentage of data falls.

Use case:

Used in ranking or cutoff decisions.

Example:

Scoring in exams – top 25% students scored above the 75th percentile.

Assume:

arr = np.array([1, 2, 3, 4, 5])

Function Description Output Example

np.mean(arr) Average of all values 3.0

np.median(arr) Middle value 3

np.std(arr) Standard deviation (spread) 1.41 (approx)

np.var(arr) Variance (std²) 2.0

np.percentile(arr, 75) 75th percentile (value at 75% rank) 4.0

arr = np.array([1, 2, 3, 4, 5])

np.mean(arr) # 3.0

np.median(arr) #3

np.std(arr) # 1.4142...

np.var(arr) # 2.0

np.percentile(arr, 75) # 4.0


9. Logical Operations in NumPy

Logical operations let you filter, mask, or make decisions based on conditions applied to
arrays.

Assume:

import numpy as np

data = np.array([1, 2, 3, 4, 5])

A. data[data > 2]

Meaning:

Select elements where condition data > 2 is True.

data[data > 2] # Output: array([3, 4, 5])

Use case:

Filter values greater than 2 (e.g., show test scores above a passing grade).

B. data[(data > 2) & (data < 5)]

Meaning:

Select elements between 2 and 5 (exclusive).

data[(data > 2) & (data < 5)] # Output: array([3, 4])

Use & for AND, | for OR, and enclose conditions in parentheses.

Use case:

Find ages between 20 and 30, prices in a target range, etc.

C. np.where(condition, value_if_true, value_if_false)

Meaning:

Apply conditional replacement.

np.where(data > 3, 1, 0) # Output: array([0, 0, 0, 1, 1])

Explanation:

If data[i] > 3, return 1

Else return 0

Use case:

Convert test scores to pass/fail, label data, or create binary masks.


D. np.any()

What it does:

Returns True if any element in the condition is True.

import numpy as np

arr = np.array([0, 0, 1, 0])

np.any(arr > 0) # Output: True

Use case:

Check if at least one element meets a condition (e.g., "Is any temperature above
freezing?").

E. np.all()

What it does:

Returns True if all elements satisfy the condition.

arr = np.array([2, 3, 4])

np.all(arr > 0) # Output: True

np.all(arr < 4) # Output: False

Use case:

Check if everything meets a rule (e.g., "Did all students pass?").

F. np.logical_and()

What it does:

Combines two boolean conditions element-wise.

arr = np.array([1, 2, 3, 4, 5])

condition = np.logical_and(arr > 2, arr < 5)

print(arr[condition]) # Output: [3 4]

Same as:

arr[(arr > 2) & (arr < 5)]


10. Broadcasting in NumPy
What is Broadcasting?

Broadcasting allows NumPy to perform operations on arrays of different shapes by


automatically expanding the smaller array to match the shape of the larger one — without
copying data.

import numpy as np

a = np.array([[1, 2, 3],

[4, 5, 6]]) # Shape: (2, 3)

b = np.array([1, 2, 3]) # Shape: (3,)

print(a + b)

Output:

[[2 4 6]

[5 7 9]]

What happened?

NumPy broadcasts b across each row of a, like this:

[[1, 2, 3], ← row 1

[4, 5, 6]] ← row 2

[1, 2, 3] ← b is "stretched" to match each row

It becomes:

[[1, 2, 3],

[1, 2, 3]]

Then it adds element-wise.


11. Universal Functions (ufuncs)

What are ufuncs?

Universal Functions (ufuncs) are fast, element-wise operations provided by NumPy.

They work on arrays of any shape and are optimized in C, making them much faster than
Python loops.

Common ufunc examples:

Assume:

import numpy as np

arr = np.array([1, 2, 3, 4])

1. np.sqrt(arr) – Square root

np.sqrt(arr) # Output: [1. 1.41421356 1.73205081 2. ]

2. np.exp(arr) – Exponential (e^x)

np.exp(arr) # Output: [ 2.71828183 7.3890561 20.08553692 54.59815003]

3. np.log(arr) – Natural log (ln)

np.log(arr) # Output: [0. 0.69314718 1.09861229 1.38629436]

Note: np.log(0) will give -infinity(undefined) or a warning.

4. np.sin(arr) – Sine

np.sin(arr) # Output: [0.84147098 0.90929743 0.14112001 -0.7568025 ]

5. np.cos(arr) – Cosine

np.cos(arr) # Output: [0.54030231 -0.41614684 -0.9899925 -0.65364362]

6. np.abs(arr) – Absolute value

arr = np.array([-1, -2, 3])

np.abs(arr) # Output: [1 2 3]
Real-Life Use Cases

Function Use Case

np.sqrt() Physics: compute distances, energy

np.exp() Finance: exponential growth, interest

np.log() Machine learning: log loss, scales

np.sin() Signal processing, physics, animation

np.abs() Handling errors, distance metrics

12. Copy vs View in NumPy

When you assign or manipulate arrays, you need to understand whether you’re working
with a copy (independent) or a view (linked/shared memory).

Example Code:

import numpy as np

a = np.array([1, 2, 3])

b = a.copy() # Creates a new, independent array

c = a.view() # Creates a new object that shares data with 'a'

a[0] = 10

print(b[0]) # Output: 1 → Not affected (separate memory)

print(c[0]) # Output: 10 → Affected (shared memory)

Explanation:

Operation Memory Independent? Affected by change in a?

a.copy() New Yes No

a.view() Shared No Yes


Real-Life Analogy

Copy = Photocopy of a document: change one, the other stays the same.

View = Looking at the same page from a different angle: if one changes, both see it.

13. Iterating Over Arrays in NumPy

There are two main ways to iterate over NumPy arrays:

1. Basic Iteration (Row-wise)

import numpy as np

arr = np.array([[1, 2, 3],

[4, 5, 6]])

for row in arr:

print(row)

Output:

[1 2 3]

[4 5 6]

This iterates row by row.

Each row is a 1D array.

2. Element-wise Iteration with np.nditer()

for x in np.nditer(arr):

print(x)

Output:

This goes through each element one by one, no matter the shape.
When to Use Each

Method What It Does Use When...

for row in arr Iterates over rows You want to process each row

np.nditer(arr) Iterates over elements You need every element (e.g. modify)

Bonus: Modifying Elements with nditer

To modify elements during iteration:

for x in np.nditer(arr, op_flags=['readwrite']):

x[...] = x * 2

What it does:

np.nditer(arr): Creates an iterator to loop over each element of the NumPy array arr,
regardless of its shape.

op_flags=['readwrite']: Allows each element to be both read and modified.

x[...] = x * 2: Doubles each element in-place (modifies the original array).

print(x): Prints each updated element.

[...] means "all of it" — and in nditer, x[...] = value safely updates the actual array
element in-place.

x[...] modifies the actual array element in-place.

Questions For Practice :


Basics & Array Creation

Q1. Create a 1D NumPy array from 0 to 9.

Answer:

arr = np.arange(10)

print(arr) # [0 1 2 3 4 5 6 7 8 9]
Q2. Create a 3x3 NumPy array of all zeros.

Answer:

arr = np.zeros((3, 3))

print(arr)

Q3. Create a 2x4 NumPy array filled with the number 7.

Answer:

arr = np.full((2, 4), 7)

print(arr)

Q4. Create a 4x4 identity matrix.

Answer:

arr = np.eye(4)

print(arr)

Indexing, Slicing & Modification

Q5. Create this array and extract number 7.

[[1 2 3 4]

[5 6 7 8]

[9 10 11 12]]

Answer:

arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

print(arr[1, 2]) # 7

Q6. Replace element 1 with 100.

Answer:

arr[0, 0] = 100

print(arr)
Q7. Slice and get the last 2 rows and last 2 columns.

Answer:

print(arr[1:, 2:]) # [[7 8], [11 12]]

Q8. Extract subarray: [[6, 7], [10, 11]].

Answer:

print(arr[1:3, 1:3])

Array Attributes & Shape

Q9. What are the shape, size and number of dimensions of a 3x2x2 array?

Answer:

arr = np.ones((3, 2, 2))

print(arr.shape) # (3, 2, 2)

print(arr.size) # 12

print(arr.ndim) # 3

Q10. Reshape a 1D array of size 9 into 3x3.

Answer:

arr = np.arange(9).reshape(3, 3)

print(arr)

Q11. Flatten a 2D array.

Answer:

arr = np.array([[1, 2], [3, 4]])

print(arr.flatten()) # [1 2 3 4]

Mathematical & Statistical Operations

Q12. Calculate mean, median, std of [1,2,3,4,5].

Answer:
data = np.array([1, 2, 3, 4, 5])

print(np.mean(data)) # 3.0

print(np.median(data)) # 3.0

print(np.std(data)) # 1.41...

Q13. Normalize the array to mean 0, std 1.

Answer:

normalized = (data - np.mean(data)) / np.std(data)

print(normalized)

Logical & Boolean Operations

Q14. From [1-10], get values > 5.

Answer:

data = np.arange(1, 11)

print(data[data > 5]) # [6 7 8 9 10]

Q15. Get values between 4 and 8 (inclusive).

Answer:

print(data[(data >= 4) & (data <= 8)]) # [4 5 6 7 8]

Q16. Replace all odd values with -1.

Answer:

data[data % 2 != 0] = -1

print(data)

Broadcasting & Vectorized Ops

Q17. Add array [1,2,3] to each row of a 2D array.

Answer:
a = np.array([[10, 20, 30], [40, 50, 60]])

b = np.array([1, 2, 3])

print(a + b)

Universal Functions (ufuncs)

Q18. Apply sqrt, sin, and log on [1,4,9].

Answer:

arr = np.array([1, 4, 9])

print(np.sqrt(arr)) # [1. 2. 3.]

print(np.sin(arr))

print(np.log(arr))

Advanced

Q19. Use np.where() to replace:

values > 5 with 1

values ≤ 5 with 0

Answer:

arr = np.array([2, 6, 4, 9, 1])

print(np.where(arr > 5, 1, 0)) # [0 1 0 1 0]

Q20. Create a 5x5 array of random integers between 1 and 100, and extract the
diagonal.

Answer:

arr = np.random.randint(1, 101, (5, 5))

print(arr)

print(np.diag(arr))
Q21. Find the most frequent element in an array.

Answer:

arr = np.array([1, 2, 3, 1, 2, 1, 4, 2, 2])

counts = np.bincount(arr)

most_frequent = np.argmax(counts)

print(most_frequent) # 2

What is Pandas ?
Pandas is a Python library mainly used for:

Data analysis

Data manipulation

Cleaning and preparing data for machine learning or visualization

It provides two main data structures:

Series → 1D labeled array (like a single column)

DataFrame → 2D labeled table (like an Excel sheet or SQL table)

Think of Pandas as Excel for Python but more powerful.

2. Importing Pandas
Before using pandas, you need to import it:

import pandas as pd

pd is just a short alias we use for convenience.

3. Series – One-Dimensional Data


What is a Series?

A Series is a single column of data with labels (called index).


import pandas as pd

data = pd.Series([10, 20, 30, 40])

print(data)

Output:

0 10

1 20

2 30

3 40

dtype: int64

With Custom Index:

data = pd.Series([10, 20, 30], index=['a', 'b', 'c'])

print(data['b']) # Output: 20

4. DataFrame – Two-Dimensional Table


A DataFrame is like an Excel sheet or a SQL table.

data = {

'Name': ['Alice', 'Bob', 'Charlie'],

'Age': [25, 30, 35],

'City': ['Delhi', 'Mumbai', 'Chennai']

df = pd.DataFrame(data)

print(df)

Output:

Name Age City

0 Alice 25 Delhi
1 Bob 30 Mumbai

2 Charlie 35 Chennai

5. DataFrame Attributes
These attributes help you inspect the structure of a DataFrame:

df.shape # (3, 3) → 3 rows, 3 columns

df.columns # Index(['Name', 'Age', 'City'])

df.index # RangeIndex(start=0, stop=3, step=1)

df.dtypes # Shows data types of each column

df.info() # Summary (columns, data types, memory)

6. Accessing Data
Columns:

df['Name'] # Access a single column

o/p:

0 Alice

1 Bob

2 Charlie

Name: Name, dtype: object

df[['Name', 'City']] # Access multiple columns

o/p:

Name City

0 Alice Delhi

1 Bob Mumbai

2 Charlie Chennai

Rows:
You can access rows using either:

iloc[] – position-based (starts from 0)

loc[] – label-based (uses index values)

Access row by position using iloc[]:

df.iloc[0]

This gives you the first row (position 0):

Name Alice

Age 25

City Delhi

Name: 0, dtype: object

Access row by index label using loc[]:

df.loc[1]

This gives the row where the index = 1 (usually the second row):

Name Bob

Age 30

City Mumbai

Name: 1, dtype: object

Accessing a Specific Cell (row + column)

You can get a single value by combining row and column:

df.loc[0, 'Name']

This means:

0 → row index

'Name' → column name

O/P: 'Alice'

Difference between iloc and loc:


Method Type Example Meaning

iloc Position df.iloc[0] First row (by position)

loc Label df.loc[1] Row with index label = 1

7. Slicing and Filtering

Slice rows:

df[0:2] # First two rows

Filter with condition:

df[df['Age'] > 28] # Rows where Age > 28

8. Modifying Data

Add new column:

df['Salary'] = [50000, 60000, 70000]

Update value:

df.loc[0, 'Age'] = 26

Drop columns/rows:

df.drop(columns='City') # Remove City column

df.drop(index=1) # Remove row at index 1

9. Sorting & Renaming

Sorting:

df.sort_values('Age') # Ascending

df.sort_values('Age', ascending=False) # Descending

Renaming columns:

df.rename(columns={'Name': 'FullName'}, inplace=True)

columns={} → A dictionary where keys are existing column names, and values are the new
names you want.
inplace=True → This applies the change directly to the DataFrame (modifies it in place).

10. Aggregations & Statistics

Common operations:

df['Age'].mean() # Average Age

df['Salary'].sum() # Total Salary

df['Age'].max() # Oldest age

df['Age'].min() # Youngest age

df.describe() # Summary of all numeric columns

11. Handling Missing Values

Check for nulls:

df.isnull()

Drop rows with nulls:

df.dropna()

Fill nulls with 0:

df.fillna(0)

12. Reading & Writing Files

Pandas makes it super easy to load data from files (like CSV and Excel) and also to save your
processed data back into those files.

Reading Files

1. Read from a CSV File:

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

'data.csv' is the file name (it should be in the same folder or give full path).

df is your DataFrame created from that file.

CSV stands for Comma-Separated Values – a very common format for storing tabular data.
If your file has a different delimiter (like ; or \t), you can use:

pd.read_csv('data.csv', delimiter=';')

2. Read from an Excel File:

df = pd.read_excel('data.xlsx')

Reads data from Excel .xlsx file.

Requires the openpyxl or xlrd library installed.

You can also specify the sheet name:

df = pd.read_excel('data.xlsx', sheet_name='Sheet1')

Writing Files

After processing your data, you often need to save it for later use or for sharing.

1. Save to a CSV File:

df.to_csv('output.csv', index=False)

index=False tells pandas not to write row numbers (index) to the file.

This creates a clean CSV without extra column.

If you want to include the index, just write:

df.to_csv('output.csv')

2. Save to an Excel File:

df.to_excel('output.xlsx', index=False)

Saves your DataFrame as an Excel file.

Just like CSV, use index=False to avoid saving row numbers.

You can also specify a sheet name:

df.to_excel('output.xlsx', sheet_name='Employees')
13. GroupBy and Aggregation

What is groupby() in Pandas?

The groupby() function is used to group rows together based on a column value (like 'City'
or 'Department') and then apply some aggregation function (like mean(), sum(), count(),
etc.).

This is very useful for analyzing data category-wise.

Example DataFrame:

import pandas as pd

data = {

'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],

'City': ['Delhi', 'Mumbai', 'Delhi', 'Chennai', 'Mumbai'],

'Salary': [50000, 60000, 55000, 62000, 58000],

'Age': [25, 30, 28, 32, 29]

df = pd.DataFrame(data)

print(df)

Output:

Name City Salary Age

0 Alice Delhi 50000 25

1 Bob Mumbai 60000 30

2 Charlie Delhi 55000 28

3 David Chennai 62000 32

4 Eva Mumbai 58000 29

1. Group by 'City' and find mean:


df.groupby('City').mean()

Output:

Salary Age

City

Chennai 62000.0 32.0

Delhi 52500.0 26.5

Mumbai 59000.0 29.5

This tells you the average Salary and Age of people in each city.

2. Group by 'City' and get total salary:

df.groupby('City')['Salary'].sum()

Output:

City

Chennai 62000

Delhi 105000

Mumbai 118000

Name: Salary, dtype: int64

This shows how much salary is paid in total per city.

3. Group by City and count:

df.groupby('City').count()

Shows how many people are in each city.

Why GroupBy is Useful?

You can use it to:


Compare performance city-wise

Analyze sales region-wise

See total expenses by category

Summarize data based on any common attribute

14. Merging and Joining

Imagine you have two boxes of toys. One has toy names, the other has toy prices. You
want to join them so that every toy has its name and price together.

That’s what merging is!

Box 1: Toy Info (df1)

| ID | Toy |

| -- | ---- |

| 1 | Car |

| 2 | Ball |

| 3 | Doll |

Box 2: Toy Prices (df2)

| ID | Price |

| -- | ----- |

| 1 | 100 |

| 2 | 50 |

| 4 | 80 |

Merge like a Puzzle:

pd.merge(df1, df2, on='ID', how='inner')

It matches the same ID from both tables and joins them.


Types of Merges (Joins)

1. inner join → Only toys that exist in both boxes

Toys with ID 1 and 2 only (because both exist in df1 and df2)

2. left join → Take all from left, and match from right

Takes all toys from df1, even if they don't have price.

3. right join → Take all from right, and match from left

Takes all toys from df2, even if name is missing.

4. outer join → All toys from both, fill gaps with NaN (empty)

Takes everything from both boxes, missing info is filled as NaN.

Example in Python:

import pandas as pd

df1 = pd.DataFrame({

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

'Toy': ['Car', 'Ball', 'Doll']

})

df2 = pd.DataFrame({

'ID': [1, 2, 4],

'Price': [100, 50, 80]

})

# Inner join

1. Inner Join → Only matching IDs

inner_result = pd.merge(df1, df2, on='ID', how='inner')

print(inner_result)

Output:

ID Toy Price
0 1 Car 100

1 2 Ball 50

Only ID 1 and 2 are common in both tables.

2. Left Join → All rows from df1, match from df2

left_result = pd.merge(df1, df2, on='ID', how='left')

print(left_result)

Output:

ID Toy Price

0 1 Car 100.0

1 2 Ball 50.0

2 3 Doll NaN

All rows from df1. No match for ID 3 in df2, so Price is NaN.

3. Right Join → All rows from df2, match from df1

right_result = pd.merge(df1, df2, on='ID', how='right')

print(right_result)

Output:

ID Toy Price

0 1 Car 100

1 2 Ball 50

2 4 NaN 80

All rows from df2. No match for ID 4 in df1, so Toy is NaN.

4. Outer Join → All rows from both, fill missing with NaN
outer_result = pd.merge(df1, df2, on='ID', how='outer')

print(outer_result)

Output:

ID Toy Price

0 1 Car 100.0

1 2 Ball 50.0

2 3 Doll NaN

3 4 NaN 80.0

Includes everything: IDs 1, 2, 3, and 4.

ID 3 has no price → NaN

ID 4 has no toy → NaN

Concatenate – Stick tables together

Stack like LEGO blocks:

pd.concat([df1, df2]) # Stack row by row (default)

Result = df1 on top of df2

Side-by-side stacking:

pd.concat([df1, df2], axis=1) # Stack column by column

Result = df1 on the left, df2 on the right.

15. Apply Function

What does apply() do?

It takes each value in a column and applies a function to it.

Example:

import pandas as pd

df = pd.DataFrame({

'Name': ['Alice', 'Bob', 'Charlie'],

'Salary': [50000, 60000, 70000]

})

Now we want to create a new column Tax which is 10% of Salary.


Use apply() with lambda (a small function):

df['Tax'] = df['Salary'].apply(lambda x: x * 0.1)

x → each value from the Salary column

x * 0.1 → calculate 10% tax

The result is stored in a new column Tax

Output:

Name Salary Tax

0 Alice 50000 5000.0

1 Bob 60000 6000.0

2 Charlie 70000 7000.0

You can also define a custom function:

def calculate_tax(sal):

return sal * 0.15

df['NewTax'] = df['Salary'].apply(calculate_tax)

16. Iteration Over Rows

Why use iterrows()?

You use it when you want to look at or do something with each row individually.

Example:

for index, row in df.iterrows():

print(row['Name'], row['Salary'])

row['Name'] → gives name from each row

row['Salary'] → gives salary from each row

Output:

Alice 50000

Bob 60000

Charlie 70000

Note:
iterrows() is slow for large datasets.

Use apply() when you can — it's faster and cleaner.

Task Use This Why?

Apply function to each value apply() Fast and efficient

Go row by row manually iterrows() When you need full row access

17. Useful Functions

df.head(5) # First 5 rows

df.tail(3) # Last 3 rows

df.sample(2) # Random 2 rows

df['City'].unique() # Unique values

df['City'].value_counts() # Count of each unique value

PRACTICE QUESTIONS:

Q1. Create a Series with numbers from 10 to 50 with a step of 10.

s = pd.Series(range(10, 51, 10))

print(s)

Q2. Create a DataFrame with the given data.

data = {

'Name': ['Kishan', 'Shyam', 'Geeta'],

'Age': [25, 30, 28],


'City': ['Delhi', 'Mumbai', 'Chennai']

df = pd.DataFrame(data)

print(df)

Q3. Access the "Age" column.

print(df['Age'])

Q4. Get the row of the person named "Shyam".

print(df[df['Name'] == 'Shyam'])

Q5. Add a new column called "Salary".

df['Salary'] = [50000, 60000, 70000]

print(df)

Q6. Find the average age.

print(df['Age'].mean())

Q7. Find the person with the maximum salary.

print(df[df['Salary'] == df['Salary'].max()])

Q8. Create a DataFrame with missing values and fill them with 0.
df2 = pd.DataFrame({

'Name': ['A', 'B', 'C'],

'Marks': [90, None, 75],

'Grade': [None, 'B', 'A']

})

df2_filled = df2.fillna(0)

print(df2_filled)

Q9. Drop rows with missing data.

df2_dropped = df2.dropna()

print(df2_dropped)

Q10. Filter rows where age > 26.

print(df[df['Age'] > 26])

Q11. Sort by salary in descending order.

df_sorted = df.sort_values('Salary', ascending=False)

print(df_sorted)

Q12. Add a column “Tax” = 10% of salary.

df['Tax'] = df['Salary'].apply(lambda x: x * 0.1)

print(df)

Q13. Group by "Department" and find average salary.

df3 = pd.DataFrame({

'Name': ['A', 'B', 'C', 'D'],


'Department': ['HR', 'IT', 'HR', 'IT'],

'Salary': [50000, 60000, 55000, 70000]

})

print(df3.groupby('Department')['Salary'].mean())

Q14. Count how many times each city appears.

print(df['City'].value_counts())

Q15. Save DataFrame to CSV.

df.to_csv('my_data.csv', index=False)

Q16. Read CSV and print first 5 rows.

df_csv = pd.read_csv('my_data.csv')

print(df_csv.head())

What is Django:-
Django is a high-level Python web framework that allows rapid development of secure and
maintainable websites. It follows the MVC (Model-View-Controller) pattern, but in Django,
it’s called MTV (Model-Template-View).

Getting Started with Django

Before using Django, we need to create a virtual environment, install Django, and set up a
project.

Step 1: Create Virtual Environment


What is a virtual environment?

A virtual environment is an isolated space where you can install Python libraries
specific to a project without affecting the system-wide Python.

Command:

python -m venv env

This creates a folder named env which contains a fresh Python installation.

Step 2: Activate the Virtual Environment

For Windows:

env\Scripts\activate

For Linux/Mac:

source env/bin/activate

Once activated, your terminal will show (env) before the command line, meaning your
virtual environment is active.

Step 3: Install Django

Command:

pip install django

This installs Django into your virtual environment.

Step 4: Create a Django Project

Command:

django-admin startproject myproject

This creates a folder myproject with the basic Django project structure.

What’s inside the myproject folder ?

manage.py – A command-line tool to interact with your project.

A folder named myproject/ (same as the outer one) containing:


__init__.py – Makes the folder a Python package.

settings.py – Project configuration.

urls.py – URL declarations.

asgi.py and wsgi.py – For deployment.

Step 5: Run the Development Server

Command:

python manage.py runserver

If successful, you’ll see:

Starting development server at http://127.0.0.1:8000/

Now open your browser and go to:

http://127.0.0.1:8000/

What is http://127.0.0.1:8000 ?

127.0.0.1 is the loopback IP address, also called localhost. It points to your own
computer.

:8000 is the port number Django uses by default.

So, http://127.0.0.1:8000 means:

“Run the site from my own computer on port 8000.”


What will you see?

You’ll see the default Django welcome page with a rocket , indicating Django is set up
successfully!

Summary of Commands:

Step Command

Create environment python -m venv env

Activate env\Scripts\activate (Windows) / source env/bin/activate


environment (Mac/Linux)

Install Django pip install django

Start project django-admin startproject myproject

Run server python manage.py runserver

Visit site http://127.0.0.1:8000

Creating a Django App and Displaying a Homepage

What is a Django App ?


An app in Django is a component or module that performs a specific function.

For example: blog, user, payments — each can be an app.

Step 1: Create an App

Inside your project directory:

python manage.py startapp myapp

This creates a new folder myapp/ with files like:

views.py – for logic

models.py – for database

urls.py – (we'll create this manually)

admin.py, apps.py, etc.


Step 2: Register the App in settings.py

Open myproject/settings.py and add 'myapp' in INSTALLED_APPS:

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

...

'myapp', # add this

Step 3: Create urls.py in App Folder

Inside myapp/, create a new file named urls.py and add:

from django.urls import path

from . import views

urlpatterns = [

path('', views.homepage, name='homepage'), # Home URL

Step 4: Include App URLs in Project URLs

Open myproject/urls.py and include your app's URLs:

from django.contrib import admin

from django.urls import path, include # include is needed

urlpatterns = [

path('admin/', admin.site.urls),

path('', include('myapp.urls')), # Connect app URLs

Now the root URL / goes to your app.

Step 5: Create a View Function

In myapp/views.py, create the homepage function:


from django.http import HttpResponse

def homepage(request):

return HttpResponse(" Welcome to the Homepage!")

Step 6: Run the Server

python manage.py runserver

Visit http://127.0.0.1:8000

You should see:

" Welcome to the Homepage!"

Summary of Steps:

Step Command / File

Create app python manage.py startapp myapp

Register app Add 'myapp' in INSTALLED_APPS in settings.py

Create app urls.py Define URL patterns and connect to view

Link app URLs in project urls.py Use include('myapp.urls')

Create view Define function in views.py

Start server python manage.py runserver

You might also like