0% found this document useful (0 votes)
3 views52 pages

Python

The document provides a comprehensive introduction to Python programming, covering basic concepts such as printing, functions, lists, and conditions. It includes practical examples and drills for hands-on practice, along with an overview of plotting using Matplotlib and data manipulation with NumPy. Additionally, it highlights the importance of functions for code reusability and organization.

Uploaded by

chirantan.moodi
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)
3 views52 pages

Python

The document provides a comprehensive introduction to Python programming, covering basic concepts such as printing, functions, lists, and conditions. It includes practical examples and drills for hands-on practice, along with an overview of plotting using Matplotlib and data manipulation with NumPy. Additionally, it highlights the importance of functions for code reusability and organization.

Uploaded by

chirantan.moodi
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

Warm up with Python

CL249
Try the following
1.
print(“Hello World”)

2. To print a number or any variable


x=9
print(f”x = {x}”)
Print(“x = ”, x)
3. Boolean
4>3
Functions
A function is a reusable block of code that performs a single, specific task. It is like a
recipe or an automated machine

•Inputs (Parameters): Ingredients you feed into the machine.


•Process: The instructions inside the machine that do the work.
•Output (Return Value): The finished product handed back to you.

def function_name(parameter1, parameter2):


# Code block (indented)
result = parameter1 + parameter2
return result
Functions

def greet(name):
print(“Hello ”, name)

To Run:
name = “Anita”
greet(name)
More Examples
def greet_user(name):

#Generates a personalized greeting message.


greeting = f"Hello, {name}! Welcome to Python class.“
return greeting
Calling the function:
message1 = greet_user("Aditi") Output: Hello, Aditi! Welcome to Python class.
message2 = greet_user(“Tanmay")
print(message1) Output: Hello, Tanmay! Welcome to Python class.
print(message2)
Conditions- Functions
Check if a number is divisible by 11
def check_eleven(x):
To Run it:
# set result to False
result = False
if (x%11)==0: x=22
print(f”{x} is divisible by 11”)
result = check_eleven(x)
result = True
else:
print(f”{x} is not divisible by 11”)
return result
Why Use Functions?
• Avoid Repetition (DRY - Don't Repeat Yourself): Write code once, use
it as many times as you want.
• Organization: Break a complex program down into smaller,
manageable pieces. Easier to debug if you are dealing with smaller
pieces.
• Readability: Named functions act like self-documenting steps.
Drill 1.1

• Write a code to check if a number is even or odd. Use a function


Lists
# Creating a list of fruits
fruits = ["apple", "banana", "cherry", "date"]
# Accessing elements by index
first_item = fruits[0]
#Output: 'apple’
last_item = fruits[-1]
# (negative index counts from the end)
# Slicing a subset of the list [start:stop]
subset = fruits[1:3] # ['banana', 'cherry']
Access to items in lists
numbers = [10, 20, 30, 40, 50] # Last item using negative index (-1
# First item (Index 0) starts from the end)
first = numbers[0] last = numbers[-1]
print(first) # Output: 10 print(last) # Output: 50
# Third item (Index 2) # Second to last item
third = numbers[2] second_last = numbers[-2]
print(third) # Output: 30 print(second_last) # Output: 40
More examples: shorthand operations on all
items in the list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Double every number
doubled = [x * 2 for x in numbers]
# Keep only even numbers
evens = [𝑥 for 𝑥 in numbers if 𝑥%2 == 0 ]
print("Doubled:", doubled)
# Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
print("Evens:", evens)
# Output: [2, 4, 6, 8, 10]
Drill 1.2
Given a list of scores, count how many students scored 70 or above.
# Sample scores
student_scores = [85, 62, 70, 95, 45, 78, 69, 100]
Convert between variable type
𝑎 = "12” :What type is 𝑎 ?

To check type:
𝑡𝑦𝑝𝑒 𝑎

Now change it to integer:


𝑎 = 𝑖𝑛𝑡(𝑎)

Check again
Drill 1.3
name = "Alice“
age_str = "21“
gpa = 3.8
is_student = True
# TODO: Convert age_str to an integer
# TODO: Calculate age next year
# TODO: Print the converted age and its type
Drill 1.4

Write a function safe_divide(a, b) that takes two


numbers and returns 𝑎/𝑏.

If 𝑏 is 0, return "Cannot divide by zero" instead of


throwing an error.
For loops

for i in range(0,5):
print(f”Iteration {i}”)

for i in range(0,5):
print(”Iteration “,i)

Drill 1.5: Write a function to print the multiplication table of 5


Drill 1.6
# Sample dataset of Celsius recordings
celsius_readings = [12.5, -3.0, 0.0, 25.4, -10.2, 18.1]

1. Filter out any temperature that falls below freezing < 0°𝐶).
2. Convert the remaining temperatures to Fahrenheit using the
formula:
3. 𝐹 = 𝐶 × 1.8 + 32
4. Return a new list containing the converted temperatures
rounded to 1 decimal place.
Drill 1.7

Calculate 𝑒 𝑥 using series expansion-


𝑥2 𝑥3
1 + 𝑥 + + + ⋯.
2! 3!
You need a function to calculate factorial 𝑛! And a function for power
Plotting
import [Link] as plt # 4. Add labels, grid, and reference axes
import numpy as np [Link]('Plot of y = 2x + 3', fontsize=14)
#1. Generate x values (100 [Link]('x', fontsize=12)
#evenly spaced numbers from -
#10 to 10) [Link]('y', fontsize=12)
x = [Link](-10, 10, 100) [Link](0, color='black', linewidth=0.8,linestyle='--’)
# 2. Define the function #x-axis line
#y = 2x + 3 [Link](0, color='black', linewidth=0.8, linestyle='--
’)
y=2*x+3
# y-axis line
# 3. Create the plot
[Link](True, linestyle=':', alpha=0.7)
[Link](figsize=(8, 5))
[Link](fontsize=12)
[Link](x, y, label='y = 2x + 3',
color='blue', linewidth=2) # 5. Show the plot
[Link]()
Plotting with python
Matplotlib
- (basic)

Low-level precision
control. Ideal for exact
layout customizations,
Seaborn
custom multi-panel
High-level statistical library built
figures, and scientific More-
on Matplotlib. Integration with Plotly ….
graphics.
Pandas DataFrames and elegant
default visual themes.
Matplotlib Concepts
Pyplot Module: standard import
import [Link] as plt
provides a stateful interface for plotting.

Figure vs Axes: The Figure acts as the


canvas; Axes represent individual subplot
regions containing data elements.

Essential Charts: Create line plots with


[Link]() and scatter plots with [Link]()
effortlessly.
Plot Annotations: Add clarity using [Link](),
[Link](), and [Link]().
Parts of a Matplotlib Figure

Figure Canvas: Top-level container holding all axes, titles, legends, colorbars,
and nested subplots.

Axes & Axis Objects: The plotting space where data points live, managing ticks,
limits, scale, and grid lines.
Custom Styling: Configure markers, line styles, transparency (alpha), and
colormaps for maximum visual impact.

High-Res Export: Save graphics to PNG, SVG, or PDF formats using


[Link]('[Link]', dpi=300).
Setup & Data Generation
What Happens Here?

• Libraries: pyplot gives us standard


import [Link] as plt
plotting routines, while numpy handles
import numpy as np
array calculations efficiently.
#1. Generate x values
x = [Link](-10, 10, 100) • [Link](-10, 10, 100): Creates an

# 2. Define the function array of 100 numerical points equally


y=2*x+3 spaced from -10 to +10.

• Vectorized Operation: y = 2 * x + 3
evaluates the formula across all 100 values
simultaneously without needing a slow
Python loop.
Key Parameters Breakdown
# 3. Create the plot
[Link](figsize=(8, 5)) • [Link](figsize=(8, 5)): Initializes a new figure
canvas with an aspect dimension ratio of 8
[Link](x, y, label='y = 2x + 3', color='blue', linewidth=2)
inches wide by 5 inches tall.
• [Link](x, y): Maps array x to the horizontal
axis and array y to the vertical axis.
• label='y = 2x + 3': Assigns a text label
stored for the legend box.

• color='blue', linewidth=2: Sets the line


color and increases thickness for
readability.
Adding Context & Reference Lines

• [Link]() & Labels: Clarify what dataset is


being presented with custom font sizing.
• [Link](): Draws a dashed background
grid ('--') with 70% opacity (alpha=0.7) to
help gauge values.
• [Link](0) & [Link](0): Draws
# 4. Add labels, grid, and reference axes thin black reference axes through (0,0)

[Link]('Plot of y = 2x + 3', fontsize=14) highlight origin intercepts.


[Link]('x', fontsize=12)
[Link]('y', fontsize=12)
[Link](0, color='black’, linewidth=0.8, linestyle='--’)
[Link](0, color='black', linewidth=0.8, linestyle='--’)
Legend & Final Display

[Link]() [Link]()

Scans all active plot elements for Displays the completed figure window
defined label strings and automatically or inline rendering in Jupyter
builds a clean legend box inside the plot Notebooks and frees memory
bounds. resources.
Plotting
import [Link] as plt # 4. Add labels, grid, and reference axes
import numpy as np [Link]('Plot of y = 2x + 3', fontsize=14)
#1. Generate x values (100 [Link]('x', fontsize=12)
#evenly spaced numbers from -
#10 to 10) [Link]('y', fontsize=12)
x = [Link](-10, 10, 100) [Link](0, color='black', linewidth=0.8,linestyle='--’)
# 2. Define the function #x-axis line
#y = 2x + 3 [Link](0, color='black', linewidth=0.8, linestyle='--
’)
y=2*x+3
# y-axis line
# 3. Create the plot
[Link](True, linestyle=':', alpha=0.7)
[Link](figsize=(8, 5))
[Link](fontsize=12)
[Link](x, y, label='y = 2x + 3',
color='blue', linewidth=2) # 5. Show the plot
[Link]()
Numpy for functions. Plot a sinusoidal function

import numpy as np
import [Link] as plt Practice: Try changing the plot,
x = [Link](0, 10, 100) change the type of line, color,
add axis labels, change font size.
y = [Link](x) Try plotting [Link](x)
[Link](x, y)
[Link]('x’) Eg-# Red dashed line ('r' for red,
'--' for dashed)
[Link]('sin(x)’)
[Link](x, y, 'r--’)
[Link]('Sine Wave’) Or green circles
[Link]() [Link](x, y, 'g:o')
Drill 1.8
Plot 𝑦 = 𝑥 ∗∗ 2 or 𝑦 = cos(𝑥)
Use. 𝑛𝑝. cos(𝑥)
Choose the range of x values.
Random numbers
import random
[Link](0,1)
print([Link](0,1))

num = [Link](0,100)
print(num)
Drill 1.9
Write the Vibonacci series

Fibonacci series- 1,1,2,3,5,8,13 etc.


Each term is the sum of the previous two terms

In Vibonacci series- use a random number to decide if you want to


add or subtract
Plot it as a function of iteration.
What is NumPy?

The ndarray Object Blazing Fast Performance Vectorized Operations


The core building block is the N- Written under the hood in C, NumPy Apply mathematical functions across
dimensional array. Unlike standard arrays use continuous memory layouts, entire datasets at once (e.g., y = 2 * x +
Python lists, all elements must share the performing mathematical operations up 3) without writing tedious for loops.
same data type for maximum efficiency. to 100x faster than raw Python loops.
# Add an element [Link](5) print(a)

Arrays, Numpy arrays


import array as arr #Accessing
# Create an array of integers print(a[2])
a = [Link]('i', [1, 2, 3]) #index starts at 0
# Access elements
print(a[0])
#Append an element
[Link](5)
print(a)
Numpy arrays
“””
import numpy as np Basic operations on
Numpy Arrays
# create a numpy array from a list
“””
arr = [Link]([1,2,3])

#Multi-dimensional array a = [Link]([1, 2, 3])


b = [Link]([4, 5, 6])
mat = [Link]([[1,2,3],[4,5,6]]) print(a + b) # [5 7 9]
print(mat) print(a * 2) # [2 4 6]
print([Link]) print(a ** 2) # [1 4 9]
print([Link])
Zero Array, Empty Array
import numpy as np
arr = [Link](5)
print(arr)
barr = [Link](5)
print(barr)
carr = [Link](5,dtype=int)
print(carr)
NumPy in Action
Key Operations Explained

• [Link](...): Converts a Python list into a


high-performance ndarray.
import as

# 1. Create 1D and 2D arrays


• [Link](start, stop, num): Generates
array 10 20 30 40
linspace 0 1 5 num evenly spaced numbers over a

# 2. Vectorized arithmetic specified interval.


2

# 3. Built-in statistics
• Element-wise Math: arr1 ** 2 squares
mean
max
every single number individually: [100, 400,
900, 1600].
• Fast Aggregations: Functions like [Link]() calculate
summary stats across millions of values instantly.
Drill 1.10

•Create a Python list of numbers and print each element by index.

•Make a NumPy array from [1][2][4], print its dtype, and add 1 to every element.

•Create a 2D NumPy array (3x3) filled with zeros, then fill its diagonal with ones.
Series vs. DataFrames

Pandas Series Pandas DataFrame

A 1-Dimensional labeled array capable of holding any data type A 2-Dimensional tabular data structure with labeled axes (rows
(integers, strings, floats). and columns).
Think of it as a single column in a spreadsheet, accompanied by Think of it as an entire Excel spreadsheet or SQL table built
a explicit row index. right into Python.
Pandas in Action
Step-by-Step Breakdown

• Dict to DataFrame: Keys become column


headers ('Name', 'Age', 'Score'), and list
values populate the columns.
import as

# 1. Create a DataFrame from a dict • Indexing: Rows are automatically


'Name' 'Alice' 'Bob' 'Charlie'
assigned integer index IDs starting at 0.
'Age' 25 30 35
'Score' 88.5 92.0 95.5

DataFrame
• Expressive Filtering: df[df['Score'] > 90]

# 2. Filter rows conditionally


filters the table to return only records
'Score' 90
where Score exceeds 90 (Bob and Charlie).
NumPy vs. Pandas Comparison

Feature NumPy Pandas

Primary Object ndarray (N-dimensional array) DataFrame & Series

Data Types Homogeneous (single type per array) Heterogeneous (mixed column types)

Best Used For Linear algebra, matrix math, raw computations Tabular data analysis, CSV/SQL importing, cleaning

Indexing Integer-based positions arr[0, 1] Named columns & custom row labels df['Score']
Drill 1.11
Array Creation & Shapes
[Link] a 1D NumPy array with numbers from 10 to 49
(inclusive).
[Link] this array into a 5x8 matrix.
[Link] the array's shape, data type, and total number of
elements.
# Drill 1.11
arr = [Link](10, 50)
matrix = [Link](5, 8)
print("Shape:", [Link])
print("Dtype:", [Link])
print("Size:", [Link])
#Also try
print([Link][0])
print([Link][0])
Drill 1.12
Given the matrix:

import numpy as np
matrix = [Link]([ [5, 10, 15, 20], [25, 30, 35, 40], [45, 50,
55, 60]])

•Extract the element 35.


•Extract the second column ([10, 30, 50]).
•Extract the bottom-right 2x2 sub-matrix ([[35, 40], [55, 60]]).

# Drill 1.12
matrix = [Link]([ [5, 10, 15, 20], [25, 30, 35, 40], [45, 50, 55, 60] ])
print("Element 35:", matrix[1, 2])
print("Second column:", matrix[:, 1])
print("Bottom-right 2x2:\n", matrix[1:, 2:])
Drill 1.13: Masking & Vectorization
[Link] an array of 20 random integers between 1 and 100 using
[Link]().
[Link] all values greater than 50 using a boolean mask.
[Link] all values less than or equal to 50 with -1.

# Drill 1.13
[Link](42)
# For reproducible output
data = [Link](1, 101, size=20)
print("Over 50:", data[data > 50])
data[data <= 50] = -1
print("Modified:", data)
# To convert array into numpy array
data=[Link](data)
Basic File Handling

A step-by-step introduction to reading text files, writing data, and loading


multi-column files into Pandas DataFrames.

Common Access Modes:


Read Mode
Write Mode
Append Mode
Files
# Syntax:
file_object = open('[Link]', 'mode')

Mode – ‘r’, ‘w’, ‘a’


Other modes are also available.
Reading a File in Python
Key Reading Concepts
open(filename, 'r'): Opens file in Read
mode (`'r'`).

# Method 1: Using 'with' (Recommended)


with open '[Link]' 'r' as The with statement: Automatically
read
print closes the file when done, preventing
# Method 2: Reading line by line resource leaks.
with open '[Link]' 'r' as
for in
print strip

read(): Reads the entire file as a single


string.
for line in file: Iterates line-by-line, ideal
for memory efficiency on large files.
Writing & Appending to Files
Write Modes Explained

Write Mode ('w'): Creates a new file or

# Overwriting / Creating a new file


completely overwrites the existing file.
with open '[Link]' 'w' as
write "Hello, Python!\n" Append Mode ('a'): Adds new data to the end of
write "Writing line two."
the file without deleting existing text.
# Appending to an existing file
with open '[Link]' 'a' as
write "\nAdding a new line!" \n Character: Adds a new line break after your
text string.

Automatic Creation: Both 'w' and 'a' create


the file if it doesn't exist yet.
Read a single column file
def read_single_column_file(filepath, has_header=True):
with open(filepath, 'r', newline='') as file:
reader = [Link](file)
if has_header:
header = next(reader)
# Skip header
data = [row[0] for row in reader]
return data

# Example usage: filepath = 'your_file.txt’


# Set has_header to True if file has a header, False otherwise
data = read_single_column_file(filepath, has_header=True)
print(data)
Loading CSV Files into DataFrames

Why Use Pandas for Files?


Handles Headers: Automatically treats
the first row as column titles (e.g., ID,
import as
Name, Grade).
# Load a multi-column CSV file
read_csv '[Link]'
Data Type Detection: Automatically
# Inspect the dataset
print head parses numbers, strings, and dates into
# Access specific columns correct formats.
'Name'
'Grade' Multi-Column Support: Easily manages
thousands of rows and columns with
minimal memory overhead.
Handy read_csv() Parameters

Parameter Example Usage Description

sep or delimiter pd.read_csv('[Link]', sep='\t') Specify custom separators like tabs (\t) or semicolons (;).

usecols pd.read_csv('[Link]', usecols=['Name', 'Age']) Load only specific columns to save memory.

header pd.read_csv('[Link]', header=None) Use when file has no column names (assigns 0, 1, 2...).

index_col pd.read_csv('[Link]', index_col='ID') Set a specific column as the DataFrame index.


Exporting DataFrames to Files

import as

# Sample DataFrame creation

'Name' 'Alice' 'Bob'


'Age' 21 22
'Major' 'CS' 'Math'

DataFrame

# Save back to a multi-column CSV


to_csv 'output_data.csv' False
Resources for further learning:

•NumPy official beginner guide

•GeeksforGeeks NumPy basics

Codecademy & W3Schools for hands-on tutorials

You might also like