0% found this document useful (0 votes)
15 views39 pages

Python Programming (BCA-4sem)

This document provides an introduction to Python programming, covering topics such as the Python interpreter, writing code in Jupyter Notebook, importing modules, and basic syntax. It explains key concepts including data types, control flow statements, operators, type casting, and string formatting. Additionally, it emphasizes best practices for writing clean and maintainable code.

Uploaded by

amansilani92
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)
15 views39 pages

Python Programming (BCA-4sem)

This document provides an introduction to Python programming, covering topics such as the Python interpreter, writing code in Jupyter Notebook, importing modules, and basic syntax. It explains key concepts including data types, control flow statements, operators, type casting, and string formatting. Additionally, it emphasizes best practices for writing clean and maintainable code.

Uploaded by

amansilani92
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming

Unit - I

●​ Introduction to Python programming.


●​ Interpreter,
●​ Writing code in Jupyter Notebook with proper indentation and comments.
●​ Importing modules.
●​ Binary operators,
●​ Data types,
●​ Type casting,
●​ Control flow statements,
●​ pass statement,
●​ range function,
●​ ternary expressions,
●​ Output with print(),
●​ user input with input(), and
●​ string formatting.

1. Introduction to Python
➔​ Python is a high-level, interpreted, general-purpose programming language known
for its simplicity and readability. It's widely used in data science, web development,
automation, and scientific computing.
➔​ It is popular because it is:
◆​ Simple and readable
◆​ Cross-platform (Windows, Mac, Linux)
◆​ Has huge libraries (AI, data science, web, automation etc.)

2. Python Interpreter
➔​ Python code is executed by the Python interpreter, which:
◆​ Reads Python code line by line.
◆​ Converts it to bytecode.
◆​ Executes the bytecode.
➔​ Python does not compile into machine code first. Instead, the interpreter executes
code line by line.
➔​ Ways to run Python:
1️⃣ Python shell / terminal
2️⃣ Script file (.py)
3️⃣ Jupyter Notebook

3. Writing code in Jupyter Notebook


➔​ Jupyter runs code in cells and shows output immediately.
➔​ Good practices:
◆​ Use indentation (spaces) — Python depends on it.
◆​ Add comments for readability.
➔​ Example:
# This is a comment
x = 10
if x > 5:
print("Greater") # Proper indentation

1
Python Programming

★​ Jupyter Notebook:
➔​ An interactive web-based environment for writing and running Python code
with proper formatting:

🕯️ Basic Python Syntax:


★​ Comments:
# Single line comment
"""
Multi-line
comment (docstring)
"""
def function():
'''Another style of multi-line comment'''
pass

4. Importing modules
➔​ Modules contain reusable code.
➔​ Example:(1)
import math
print([Link](16))

from math import pi


print(pi)

➔​ Example:(2)
# Import entire module
import math
print([Link](16))

# Import specific functions


from datetime import date
print([Link]())

# Import with alias


import numpy as np
import pandas as pd

🕯️ Operators and Type Casting:


5. Binary Operators
➔​ Operate on two operands:
❖​ Arithmetic: +, -, *, /, //, %, **
❖​ Comparison: ==, !=, >, <, >=, <=
❖​ Logical: and, or, not
❖​ Assignment: =, +=, -=, *=
➔​ Example:(1)
a=5
b=2
print(a + b)

2
Python Programming

➔​ Example:
# Arithmetic operators
a = 10 + 5 # Addition: 15
b = 10 - 5 # Subtraction: 5
c = 10 * 5 # Multiplication: 50
d = 10 / 3 # Division: 3.333...
e = 10 // 3 # Floor division: 3
f = 10 % 3 # Modulus: 1
g = 10 ** 2 # Exponentiation: 100

# Comparison operators
print(10 == 10) # True
print(10 != 5) # True
print(10 > 5) # True
print(10 < 5) # False
print(10 >= 10) # True
print(10 <= 5) # False

# Logical operators
print(True and False) # False
print(True or False) # True
print(not True) # False

6. Data Types
➔​ Common built-ins:
x = 10 # int
y = 3.5 # float
name = "Ram" # str
flag = True # bool
nums = [1,2,3] # list

➔​ Check type:
print(type(x))

➔​ Example:
# Numeric types
integer_num = 10 # int
float_num = 3.14 # float
complex_num = 2 + 3j # complex

# Text type
text = "Hello World" # str

# Boolean type
is_true = True # bool
is_false = False # bool

# Sequence types

3
Python Programming

my_list = [1, 2, 3] # list (mutable)


my_tuple = (1, 2, 3) # tuple (immutable)

# Mapping type
my_dict = {"name": "Alice", "age": 25} # dict

# Set types
my_set = {1, 2, 3} # set (unordered, unique)

7. Type Casting
➔​ Type casting is the process of converting a value from one data type to another (e.g.,
from an integer to a string). This is done using built-in constructor functions like int(),
float(), and str().
➔​ Convert one type to another.
➔​ Example:(1)
a = int("10")
b = float(5)
c = str(25)

➔​ Example:(2)
# Explicit type conversion
x = int(3.14) # Convert to int: 3
y = float(10) # Convert to float: 10.0
z = str(100) # Convert to string: "100"
b = bool(0) # Convert to bool: False

# Checking types
print(type(x)) # <class 'int'>
print(isinstance(y, float)) # True

➔​ Python supports two main types of type conversion:


◆​ Explicit Type Casting: Done manually by the programmer using specific
functions to control the conversion process. This is necessary when
combining incompatible types (like adding a string and a number) and
provides control over potential data loss.
◆​ Implicit Type Conversion: Done automatically by the Python interpreter to
avoid data loss during mixed-type operations (e.g., converting an integer to a
float when they are added together).

8. Control Flow Statements


❖​ Conditional Statements:
★​ if / elif / else
➔​ Example:(1)
age = 18
if age > 18:
print("Adult")
elif age == 18:
print("Just adult")

4
Python Programming

else:
print("Minor")

➔​ Example:(2)
# if-elif-else
grade = 85

if grade >= 90:


print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
else:
print("Fail")

# Nested if
age = 25
if age >= 18:
if age >= 21:
print("Adult with full privileges")
else:
print("Young adult")
else:
print("Minor")

❖​ loops:
★​ for loop
for i in range(5):
print(i)

★​ while loop
i=1
while i <= 3:
print(i)
i += 1

➔​ Example:
# for loop
for i in range(5): # 0 to 4
print(i)

# while loop
count = 0
while count < 5:
print(count)
count += 1

5
Python Programming

# Loop control statements


for i in range(10):
if i == 3:
continue # Skip iteration
if i == 7:
break # Exit loop
print(i)

9. pass statement
➔​ Placeholder (do nothing).
➔​ The pass statement in Python is a null operation; nothing happens when it executes.
Its primary use is as a placeholder in situations where Python's syntax requires a
statement or a code block, but you don't need any actual code to run yet.
➔​ Python does not allow empty code blocks. If you leave a function, loop, or conditional
statement body empty, you will get an IndentationError. The pass statement avoids
this error, allowing you to structure your code and fill in the logic later.
➔​ Example:(1)
if True:
pass

➔​ Example:(2)
# Placeholder for future code
def function_to_implement_later():
pass # Do nothing, prevents syntax error

class EmptyClass:
pass

if condition:
pass # Will implement logic later

10. range() function


➔​ Produces a sequence.
➔​ Example:(1)
range(5) # 0…4
range(2, 6) # 2…5
range(1, 10, 2) # 1,3,5,7,9

➔​ Example:(2)
# range(stop)
range(5) # 0, 1, 2, 3, 4

# range(start, stop)
range(2, 6) # 2, 3, 4, 5

# range(start, stop, step)


range(0, 10, 2) # 0, 2, 4, 6, 8
range(10, 0, -1) # 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

6
Python Programming

11. Ternary Expression


➔​ Single-line if-else.
➔​ In Python, the ternary expression (formally called a conditional expression) provides
a concise way to write an if-else statement in a single line. It is used to assign a value
to a variable or return a value from a function based on a simple condition.
➔​ Example:(1)
result = "Even" if n % 2 == 0 else "Odd"

➔​ Example:(2)
# Traditional if-else
if age >= 18:
status = "Adult"
else:
status = "Minor"

# Ternary expression
status = "Adult" if age >= 18 else "Minor"

# Multiple conditions
grade = "A" if score >= 90 else "B" if score >= 80 else "C”

➔​ Syntax: The syntax is different from the ?: operator found in many other languages
and reads more like natural language.
◆​ Example: value_if_true if condition else value_if_false

➔​ How It Works:
◆​ The condition (a Boolean expression) is evaluated first.
◆​ If the condition is True, the value_if_true is returned/assigned.
◆​ If the condition is False, the value_if_false is returned/assigned.

🕯️Input and Output:


12. Output with print()
➔​ Example:(1)
print("Hello", 10, sep="-", end="!")

➔​ Example:(2)
# Basic printing
print("Hello, World!")

# Multiple items
print("Name:", "Alice", "Age:", 25)

# Changing separator
print("2023", "12", "25", sep="/") # 2023/12/25

# Changing end character


print("Hello", end=" ")

7
Python Programming

print("World!") # Hello World!

# File output
with open("[Link]", "w") as f:
print("Saving to file", file=f)

13. User Input with input()


➔​ Always returns string.
➔​ Example:(1)
name = input("Enter name: ")
age = int(input("Enter age: "))

➔​ Example:(2)
# Basic input
name = input("Enter your name: ")
print(f"Hello, {name}!")

# Input always returns string


age = input("Enter your age: ")
age = int(age) # Convert to int for calculations

# Multiple inputs
values = input("Enter two numbers separated by space: ")
a, b = map(float, [Link]())
print(f"Sum: {a + b}")

14. String formatting


➔​ String formatting in Python is used to create dynamic and well-structured text by
inserting variables and expressions into strings.
➔​ The most modern and recommended method is f-strings (formatted string literals),
but the [Link]() method and the older % operator are also used.
➔​ String formatting allows you to create dynamic strings by combining variables and
values.
➔​ Example:(1)
name = "Amit"
age = 20

print("My name is", name, "and I am", age)


print(f"My name is {name} and I am {age}")
print("My name is {} and I am {}".format(name, age))

➔​ Example:(2)
name = "Alice"
age = 25
height = 5.6

# 1. Old-style formatting (% operator)


print("Name: %s, Age: %d, Height: %.2f" % (name, age, height))

8
Python Programming

# 2. [Link]() method
print("Name: {}, Age: {}, Height: {:.2f}".format(name, age, height))
print("Name: {0}, Age: {1}, Height: {2:.2f}".format(name, age, height))
print("Name: {n}, Age: {a}".format(n=name, a=age))

# 3. f-strings (Python 3.6+ - Recommended)


print(f"Name: {name}, Age: {age}, Height: {height:.2f}")
print(f"Next year age: {age + 1}")

# Formatting numbers
number = 12345.6789
print(f"Comma separated: {number:,.2f}") # 12,345.68
print(f"Percent: {0.25:.2%}") # 25.00%
print(f"Hexadecimal: {255:#x}") # 0xff

★​ How to Format Strings in Python:


➔​ There are five different ways to perform string formatting in Python:
◆​ Formatting with % Operator.
◆​ Formatting with format() string method.
◆​ Formatting with string literals, called f-strings.
◆​ Formatting with String Template Class
◆​ Formatting with center() string method.

​ Practical Example:
# Complete example combining concepts
def calculate_grade():
"""Calculate grade based on score"""

# Get user input


score = float(input("Enter your score (0-100): "))

# Validate input
if not 0 <= score <= 100:
print("Invalid score! Must be between 0 and 100.")
return

# Determine grade using ternary expression


grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70
else "D" if score >= 60 else "F"

# Format and display result


print(f"Score: {score:.1f}")
print(f"Grade: {grade}")

# Additional feedback

9
Python Programming

if grade == "F":
print("You need to improve!")
elif grade == "A":
print("Excellent work!")
else:
print("Good job!")

# Run the function


calculate_grade()

​ Best Practices:
1. Indentation: Always use 4 spaces (not tabs).
2. Comments: Write clear comments explaining why, not what.
3. Naming: Use descriptive variable and function names.
4. Modularity: Break code into reusable functions.
5. Error Handling: Validate user inputs.
6. Formatting: Use f-strings for modern Python code.
7. Readability: Write code that's easy to understand.

10
Python Programming

Unit - II
Data Structures and Sequences in Python
●​ Data Structures and Sequences:
○​ Tuples,
○​ lists (with slicing),
○​ dictionaries, and
○​ sets,
●​ Builtin sequence functions:
○​ len(), sum(), max(), min(),
●​ List operations:
○​ append, remove;
●​ dictionary value access,
●​ Comprehensions for lists, sets, and dictionaries to manage data collections.

🕯️ Data Structures & Sequences:


➔​ A data structure is a way of storing and organizing data so it can be used efficiently.

★​ Introduction to Sequences:
➔​ Sequences are ordered collections of items.
➔​ Python has several built-in sequence types.
➔​ Common operations apply across different sequence types.
➔​ Python provides several built-in sequence types:
◆​ Tuple – fixed (unchangeable) sequence
◆​ List – changeable sequence
◆​ Dictionary – key–value storage
◆​ Set – unordered collection of unique values

1. Tuples:
➔​ A tuple is an ordered, immutable collection.
➔​ Example: t = (10, 20, 30)
✔ Ordered
✔ Allows duplicates
✘ Cannot be changed
➔​ Useful when data should not be modified, e.g., dates, coordinates.
➔​ Access: t[1] # 20

★​ Characteristics:
●​ Immutable (cannot be modified after creation).
●​ Ordered collection.
●​ Can contain heterogeneous data types.
●​ Created using parentheses () or tuple().

➔​ Examples:
# Creating tuples
t1 = (1, 2, 3)
t2 = 4, 5, 6 # Parentheses are optional
t3 = (1,) # Single element tuple (comma required)
t4 = tuple([7, 8, 9])

11
Python Programming

# Accessing elements
print(t1[0]) # 1
print(t1[-1]) # 3 (last element)

# Tuple unpacking
a, b, c = t1 # a=1, b=2, c=3

2. Lists:
➔​ A list is ordered and mutable.
➔​ Example: lst = [5, 10, 15, 20]
➔​ Slicing:
lst[1:3] # [10, 15]
lst[:2] # [5, 10]
lst[2:] # [15, 20]
lst[-1] # 20

★​ Characteristics:
●​ Mutable (can be modified after creation).
●​ Ordered collection.
●​ Created using square brackets [] or list().

★​ Basic Operations:
# Creating lists
lst1 = [1, 2, 3, 4, 5]
lst2 = list(range(5))
lst3 = ['a', 'b', 'c']

# Accessing elements
print(lst1[0]) # 1
print(lst1[-1]) # 5

# Modifying elements
lst1[0] = 10 # lst1 becomes [10, 2, 3, 4, 5]

★​ Slicing:
lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Basic slicing: list[start:stop:step]


print(lst[2:5]) # [2, 3, 4]
print(lst[:5]) # [0, 1, 2, 3, 4]
print(lst[5:]) # [5, 6, 7, 8, 9]
print(lst[::2]) # [0, 2, 4, 6, 8]
print(lst[::-1]) # Reverse: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

# Negative indices in slicing


print(lst[-3:]) # [7, 8, 9]
print(lst[:-3]) # [0, 1, 2, 3, 4, 5, 6]

12
Python Programming

★​ List Methods:
lst = [1, 2, 3]

# append() - adds element at the end


[Link](4) # [1, 2, 3, 4]

# remove() - removes first occurrence of value


[Link](2) # [1, 3, 4]

# Other important methods


[Link](1, 5) # [1, 5, 3, 4] - insert at index
[Link]() # Returns 4, lst becomes [1, 5, 3]
[Link](1) # Returns 5, lst becomes [1, 3]
[Link]([6, 7]) # [1, 3, 6, 7]
[Link]() # Sorts in place
[Link]() # Reverses in place

3. Dictionaries:
➔​ A dictionary stores data as key : value pairs.
➔​ Example: student = {"name": "Riya", "age": 18}
➔​ Access values:
student["name"] # Riya
[Link]("age") # 18
➔​ Keys must be unique.

★​ Characteristics:
●​ Unordered collection of key-value pairs.
●​ Keys must be immutable (strings, numbers, tuples).
●​ Values can be of any type.
●​ Created using curly braces {} or dict().

★​ Operations:
# Creating dictionaries
d1 = {'name': 'Alice', 'age': 25, 'city': 'NYC'}
d2 = dict(name='Bob', age=30)
d3 = dict([('name', 'Charlie'), ('age', 35)])

# Accessing values
print(d1['name']) # Alice
print([Link]('age')) # 25
print([Link]('salary', 0)) # 0 (default if key doesn't exist)

# Modifying/Adding
d1['age'] = 26 # Update value
d1['salary'] = 50000 # Add new key-value pair

# Dictionary methods

13
Python Programming

keys = [Link]() # dict_keys(['name', 'age', 'city', 'salary'])


values = [Link]() # dict_values(['Alice', 26, 'NYC', 50000])
items = [Link]() # dict_items([('name', 'Alice'), ...])

# Removing elements
del d1['city'] # Remove key 'city'
age = [Link]('age') # Removes and returns value

4. Sets:
➔​ A set is an unordered collection of unique items.
➔​ Example:
s = {1, 2, 3, 3}
print(s) # {1, 2, 3}
➔​ Good for:
◆​ removing duplicates.
◆​ mathematical operations (union, intersection).

★​ Characteristics:
●​ Unordered collection of unique elements.
●​ Mutable (but elements must be immutable).
●​ Created using curly braces {} or set().
●​ Supports mathematical set operations.

★​ Operations:
# Creating sets
s1 = {1, 2, 3, 4, 5}
s2 = set([4, 5, 6, 7, 8])
s3 = set() # Empty set (NOT {} which creates empty dict)

# Set operations
union = s1 | s2 # {1, 2, 3, 4, 5, 6, 7, 8}
intersection = s1 & s2 # {4, 5}
difference = s1 - s2 # {1, 2, 3}
symmetric_diff = s1 ^ s2 # {1, 2, 3, 6, 7, 8}

# Set methods
[Link](6) # {1, 2, 3, 4, 5, 6}
[Link](3) # {1, 2, 4, 5, 6}
[Link](10) # No error if element not present

🕯️ Built-in Sequence Functions:


➔​ Python includes several built-in functions that operate on various sequence types
such as lists, tuples, strings, and range objects.
➔​ These functions allow for common operations like checking length, finding
minimum/maximum values, and ordering elements.
➔​ Here are some of the most useful built-in functions for sequences:
◆​ len(seq): Returns the number of items in a sequence.
●​ Example: len([1, 2, 3]) returns 3.

14
Python Programming

◆​ min(seq): Returns the smallest item in a sequence.


●​ Example: min([3, 1, 2]) returns 1.
◆​ max(seq): Returns the largest item in a sequence.
●​ Example: max([3, 1, 2]) returns 3.
◆​ sum(seq): Returns the sum of all items in a sequence (numeric types only).
●​ Example: sum([1, 2, 3]) returns 6.

➔​ Example:(1)
data = [1, 2, 3, 4, 5]

# len() - returns length


length = len(data) #5

# sum() - returns sum of elements


total = sum(data) # 15

# max() - returns maximum value


maximum = max(data) #5

# min() - returns minimum value


minimum = min(data) #1

# Works with other sequences too


print(sum((1, 2, 3))) # 6 (with tuple)
print(max({1, 3, 2})) # 3 (with set)

➔​ Example:(2)
nums = [5, 10, 15]
len(nums) # 3
sum(nums) # 30
max(nums) # 15
min(nums) # 5

🕯️ Introduction to List Operations in Python:


➔​ The list is a data structuring method that allows storing the integers or the characters
in an order indexed by starting from 0.
➔​ List operations are the operations that can be performed on the data in the list data
structure.
➔​ A few of the basic list operations used in Python programming are extend(), insert(),
append(), remove(), pop(), slice, reverse(), min() & max(), concatenate(), count(),
multiply(), sort(), index(), clear(), etc.
➔​ Some of the most widely used list operations in Python include the following:

1. append()
➔​ The append() method adds elements at the end of the list. This method can
only add a single element at a time. You can use the append() method inside
a loop to add multiple elements.
➔​ Example:

15
Python Programming

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']


[Link](4)
[Link](5)
[Link](6)
for i in range(7, 9):
[Link](i)
print(myList)

●​ Output: [ 1, 2, 3, ‘EduCBA’ , ‘makes learning fun!’ , 4, 5, 6, 7, 8 ]

2. remove()
➔​ The remove() method removes an element from the list. Only the first
occurrence of the same element is removed in the case of multiple
occurrences.
➔​ Example:
myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']
[Link]('makes learning fun!')
print(myList)

●​ Output: [ 1, 2, 3, ‘EduCBA’ ]

🕯️ Dictionary Value Access:


➔​ Python dictionaries, known as "dict", are efficient key/value hash tables represented
by key:value pairs within curly braces {}.
➔​ Values in a dictionary can be accessed or set using square brackets with the key,
and "in" or the . get() method can check for key existence.
➔​ A dictionary in Python is a useful way to store data in pairs, where each key is
connected to a value. To access an item in the dictionary, refer to its key name inside
square brackets.
➔​ Example:
a = {"Geeks": 3, "for": 2, "geeks": 1}

#Access the value assosiated with "geeks"


x = a["geeks"]
print(x)
●​ Output: 1
➔​ You can access the items of a dictionary by referring to its key name, inside square
brackets.

🕯️ Comprehensions:
➔​ Python, comprehension is a concise way to create a new list, set, or dictionary based
on an existing iterable object.
➔​ Comprehensions are more concise and readable than traditional looping constructs
such as for and while loops, and they can often be more efficient as well.
➔​ Comprehensions in Python provide a concise and efficient way to create new
sequences from existing ones.
➔​ They enhance code readability and reduce the need for lengthy loops.

16
Python Programming

★​ Why do we need Comprehensions:


○​ Encourages Modular Thinking: Promotes writing logic in smaller, reusable
expressions.
○​ Widely Used in Real-World Code: Found in data science, web development
and automation scripts.
○​ Easier Debugging & Testing: Fewer lines reduce the surface area for bugs.
○​ Seamless with Other Python Features: Integrates well with functions like
zip(), enumerate() and lambda.

★​ Types of Comprehensions in Python:


➔​ Python offers different types of comprehensions to simplify creation of data structures
in a clean, readable way. Let’s explore each type with simple examples.

1. List Comprehensions:
➔​ List comprehensions allow for the creation of lists in a single line, improving efficiency
and readability. They follow a specific pattern to transform or filter data from an
existing iterable.
➔​ Syntax: [expression for item in iterable if condition]
Where:
expression: Operation applied to each item.
item: Variable representing the element from the iterable.
iterable: The source collection.
condition (optional): A filter to include only specific items.

➔​ Example:(1)
# Basic syntax: [expression for item in iterable if condition]

# Create list of squares


squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# With condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]

# Nested comprehensions
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

➔​ Example(2): squares = [x*x for x in range(5)]

2. Set Comprehensions:
➔​ Set Comprehensions are similar to list comprehensions but result in sets,
automatically eliminating duplicate values while maintaining a concise syntax.
➔​ Syntax: {expression for item in iterable if condition}
Where:
expression: The operation applied to each item.

17
Python Programming

iterable: The source collection.


condition (optional): Filters elements before adding them.

➔​ Example:(1)
# Similar to list comprehensions but with curly braces

unique_squares = {x**2 for x in range(-5, 6)}


# {0, 1, 4, 9, 16, 25}

# Remove duplicates from list


numbers = [1, 2, 2, 3, 4, 4, 5]
unique = {x for x in numbers}
# {1, 2, 3, 4, 5}

➔​ Example(2): unique = {x % 3 for x in range(6)}

3. Dictionary Comprehensions:
➔​ Dictionary Comprehensions are used to construct dictionaries in a compact form,
making it easy to generate key-value pairs dynamically based on an iterable.
➔​ Syntax: {key_expression: value_expression for item in iterable if condition}
Where:
key_expression: Determines the dictionary key.
value_expression: Computes the value.
iterable: The source collection.
condition (optional): Filters elements before adding them.

➔​ Example:(1)
# Syntax: {key_expr: value_expr for item in iterable if condition}

# Create dictionary of squares


square_dict = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Swap keys and values


original = {'a': 1, 'b': 2, 'c': 3}
swapped = {value: key for key, value in [Link]()}
# {1: 'a', 2: 'b', 3: 'c'}

# With condition
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

➔​ Example(2): table = {x: x*x for x in range(4)}

★​ Managing Data Collections:


➔​ Choosing the Right Data Structure
◆​ Tuples: When data shouldn't change (coordinates, RGB values)
◆​ Lists: For ordered, modifiable collections

18
Python Programming

◆​ Dictionaries: For key-value associations (like JSON data)


◆​ Sets: For unique elements and mathematical operations

❖​ Benefits:
➢​ shorter
➢​ faster
➢​ more readable

​ Practical Examples:
# Example 1: Student records
students = [
{'id': 1, 'name': 'Alice', 'grades': [85, 90, 78]},
{'id': 2, 'name': 'Bob', 'grades': [92, 88, 95]}
]

# Calculate average using comprehensions


averages = {s['name']: sum(s['grades'])/len(s['grades'])
for s in students}

# Example 2: Inventory management


inventory = {
'apple': {'price': 0.5, 'quantity': 100},
'banana': {'price': 0.3, 'quantity': 150}
}

# Get total value


total_value = sum(item['price'] * item['quantity']
for item in [Link]())

​ Key Points to Remember:


1. Mutability: Lists and dictionaries are mutable; tuples and strings are immutable.
2. Ordering: Lists and tuples maintain order; sets and dictionaries (Python 3.6+) do
too but shouldn't be relied upon for sets.
3. Uniqueness: Sets enforce uniqueness of elements.
4. Performance: Sets and dictionaries offer O(1) lookups on average.
5. Comprehensions: Provide concise and readable ways to create collections.

​ Common Use Cases:


●​ Configuration data: Tuples or dictionaries.
●​ Data processing: Lists with comprehensions.
●​ Unique items collection: Sets.
●​ Database-like records: List of dictionaries.
●​ Caching/memoization: Dictionaries.

19
Python Programming

Unit - III
Functions, Generators & NumPy
●​ Defining functions,
●​ namespaces, scope,
●​ local functions,
●​ multiple return values,
●​ Anonymous (lambda) functions,
●​ partial argument application,
●​ generators,
●​ NumPy: Ndimensional arrays,
●​ arithmetic operations,
●​ indexing, slicing,
●​ pseudorandom number generation, and
●​ array operations (sum, mean).

1. Defining Functions
➔​ A function is a block of reusable code that performs a specific task.
➔​ Syntax:
def function_name(parameters):
statement
return value
➔​ Example:(1)
def add(a, b):
return a + b

result = add(5, 3)
print(result)

➔​ Example:(2)
def function_name(parameters):
"""Docstring (optional)"""
# Function body
return value

# Example:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"

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


print(greet("Bob", "Hi")) # Hi, Bob!

2. Namespaces
➔​ A namespace is a container that holds names of variables, functions, and objects.

★​ Types of Namespaces:
1. Local Namespace – inside a function
2. Global Namespace – outside all functions
3. Built-in Namespace – predefined names in Python

20
Python Programming

➔​ Example:
x = 10 # global namespace
def show():
y = 5 # local namespace
print(y)

3. Scope
➔​ Scope defines where a variable can be accessed.

★​ Types of Scope:
○​ Local Scope
○​ Global Scope

➔​ Example:
x = 20

def test():
print(x) # global variable accessible

test()

4. Local Functions (Nested Functions)


➔​ A function defined inside another function.
➔​ Example:(1)
def outer():
def inner():
print("Inner Function")
inner()

outer()

➔​ Example:(2)
def outer_function(x):
def inner_function(y):
return y * 2
return inner_function(x) + 5

result = outer_function(10) # 25

5. Multiple Return Values


➔​ Python allows returning multiple values using tuples.
➔​ Example:(1)
def calculate(a, b):
return a+b, a-b, a*b

sum, diff, mul = calculate(10, 5)


print(sum, diff, mul)

21
Python Programming

➔​ Example:(2)
def get_coordinates():
x = 10
y = 20
z = 30
return x, y, z # Returns a tuple

# Unpacking
a, b, c = get_coordinates()

6. Anonymous (Lambda) Functions


➔​ A lambda function is a small, unnamed function.
➔​ Lambda functions, (or anonymous functions), are small, unnamed functions defined
with the lambda keyword. They allow you to create simple functions concisely. The
expression is evaluated and returned. Lambda functions can have any amount of
arguments, but only one expression.
➔​ Lambda Functions are anonymous functions means that the function is without a
name. As we already know def keyword is used to define a normal function in
Python. Similarly, lambda keyword is used to define an anonymous function in
Python.
➔​ Syntax: lambda arguments: expression
➔​ Example:(1)
square = lambda x: x * x
print(square(4))

➔​ Example:(2)
# Syntax: lambda arguments: expression
square = lambda x: x ** 2
add = lambda a, b: a + b

# Commonly used with map/filter


numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16]

7. Partial Argument Application


➔​ Partial functions in Python is a function that is created by fixing a certain number of
arguments of another function. Python provides a built-in module called functools that
includes a function called partial that can be used to create partial functions. The
partial function takes a callable (usually another function) and a series of arguments
to be pre-filled in the new partial function.
➔​ Partial functions allow us to fix a certain number of arguments of a function and
generate a new function.
➔​ Using [Link] to fix some arguments of a function.
➔​ Example:(1)
from functools import partial

def multiply(x, y):


return x * y

22
Python Programming

double = partial(multiply, 2)
print(double(5))

➔​ Example:(2)
from functools import partial

def power(base, exponent):


return base ** exponent

# Fix exponent to 2
square = partial(power, exponent=2)
print(square(5)) # 25

# Fix base to 2
power_of_two = partial(power, base=2)
print(power_of_two(3)) # 8

★​ How do you implement a partial function in Python:


➔​ Partial functions support both positional and keyword arguments to be used as fixed
arguments.
➔​ Example:(1)
➢​ In this example, we use default values to implement the partial function. The
default values start replacing variables from the left. In the example, we have
pre-filled our function with some constant values of a, b, and c. And g() just
takes a single argument i.e. the variable x.

from functools import partial

# A normal function
def f(a, b, c, x):
return 1000*a + 100*b + 10*c + x

# A partial function that calls f with


# a as 3, b as 1 and c as 4.
g = partial(f, 3, 1, 4)

# Calling g()
print(g(5))

➢​ Output: 3145

➔​ Example:(2)
➢​ In the example, we have used pre-defined value constant values in which we
have assigned the values of c and b and add_part() takes a single argument
i.e. the variable a.

from functools import *

23
Python Programming

# A normal function
def add(a, b, c):
return 100 * a + 10 * b + c

# A partial function with b = 1 and c = 2


add_part = partial(add, c = 2, b = 1)

# Calling partial function


print(add_part(3))

➢​ Output: 312

★​ Uses of partial functions:


●​ Integration with Libraries: Partial functions can be used to customize the behavior
of third-party functions or methods by providing partial arguments and can be used to
integrate it with other libraries.
●​ Simplifying Callbacks: Partial functions can be used to create specialized callback
handlers by fixing some callback-specific parameters and providing a cleaner
interface for the rest of the code.
●​ Parameter Fixing: Partial functions can be very useful when we have a function with
multiple parameters and we frequently want to use it with some parameters fixed.
Instead of repeatedly passing those fixed parameters, we can create a partial
function and call it with the remaining arguments.
●​ Reducing Duplication: If we are using the same arguments for a function in various
places, creating a partial function with those fixed arguments can help to reduce code
duplication and maintenance efforts.
●​ Default Arguments: Python's built-in [Link] can be used to set default
values for function arguments.
●​ Reusability of code: Partial functions can be used to derive specialized functions
from general functions and therefore help us to reuse our code.

8. Generators
➔​ Generators produce values one at a time using yield.
➔​ In Python, a generator is a function that returns an iterator that produces a sequence
of values when iterated over.
➔​ Generators are useful when we want to produce a large sequence of values, but we
don't want to store all of them in memory at once.
➔​ Example:(1)
def numbers():
for i in range(3):
yield i

for num in numbers():


print(num)

➔​ Example:(2)

24
Python Programming

# Generator function
def count_up_to(n):
i=1
while i <= n:
yield i # Pauses here
i += 1

# Generator expression
squares = (x**2 for x in range(10))

# Usage
for num in count_up_to(5):
print(num) # 1, 2, 3, 4, 5

★​ Advantages:
➢​ Saves memory.
➢​ Faster execution

9. NumPy: N-Dimensional Arrays


➔​ An ndarray is a (usually fixed-size) multidimensional container of items of the same
type and size. The number of dimensions and items in an array is defined by its
shape , which is a tuple of N non-negative integers that specify the sizes of each
dimension.
➔​ ndarray is a short form for N-dimensional array which is a important component of
NumPy. It’s allows us to store and manipulate large amounts of data efficiently. All
elements in an ndarray must be of same type making it a homogeneous array. This
structure supports multiple dimensions which makes it ideal for handling complex
datasets like those used in scientific computing or data analysis. With this we can
perform fast and memory efficient operations on data.
➔​ NumPy is used for numerical computing.

★​ Creating Array:
import numpy as np

arr = [Link]([1, 2, 3, 4])


print(arr)

★​ 2-D Array:
arr2 = [Link]([[1,2],[3,4]])

➔​ Example:
import numpy as np

# Creating arrays
arr1 = [Link]([1, 2, 3]) # 1D
arr2 = [Link]([[1, 2], [3, 4]]) # 2D
arr3 = [Link]((3, 3)) # 3x3 zeros

25
Python Programming

arr4 = [Link]((2, 3)) # 2x3 ones


arr5 = [Link](10) # [0, 1, ..., 9]
arr6 = [Link](3, 3) # Random 3x3

10. Arithmetic Operations in NumPy


➔​ Arithmetic operations are used for numerical computation and we can perform them
on arrays using NumPy. With NumPy we can quickly add, subtract, multiply, divide
and get power of elements in an array. NumPy performs these operations even with
large amounts of data.
➔​ Example:(1)
a = [Link]([1,2,3])
b = [Link]([4,5,6])

print(a + b)
print(a * b)

➔​ Example:(2)
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])

# Element-wise operations
print(a + b) # [5 7 9]
print(a - b) # [-3 -3 -3]
print(a * b) # [4 10 18]
print(a / b) # [0.25 0.4 0.5]
print(a ** 2) # [1 4 9]

# Matrix multiplication
mat1 = [Link]([[1, 2], [3, 4]])
mat2 = [Link]([[5, 6], [7, 8]])
print([Link](mat1, mat2))
# [[19 22]
# [43 50]]

11. Indexing and Slicing


➔​ String indexing allows you to access individual characters in a string using their
position (index), while slicing lets you extract a range of characters.
➔​ Indexing uses square brackets with a single number text[0] , while slicing uses a
range text[start:end] or text[start:end:step] .
➔​ Example:(1)
arr = [Link]([10,20,30,40,50])

print(arr[1])
print(arr[1:4])

➔​ Example:(2)
arr = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

26
Python Programming

# Indexing
print(arr[0, 1]) #2
print(arr[2, 2]) #9

# Slicing
print(arr[0:2, :]) # First two rows
# [[1 2 3]
# [4 5 6]]

print(arr[:, 1:3]) # Last two columns


# [[2 3]
# [5 6]
# [8 9]]

# Boolean indexing
mask = arr > 5
print(arr[mask]) # [6 7 8 9]

12. Pseudorandom Number Generation


➔​ The random module in Python uses the Mersenne Twister algorithm as its core
pseudorandom number generator (PRNG) [6]. This algorithm is well-known for its
high speed and excellent statistical properties, making it a widely used PRNG in
general-purpose applications.
➔​ Pseudo Random Number Generator(PRNG) refers to an algorithm that uses
mathematical formulas to produce sequences of random numbers. PRNGs generate
a sequence of numbers approximating the properties of random numbers. A PRNG
starts from an arbitrary starting state using a seed state. Many numbers are
generated in a short time and can also be reproduced later, if the starting point in the
sequence is known. Hence, the numbers are deterministic and efficient.
➔​ Example:(1)
[Link](1)
random_nums = [Link](1, 10, 5)
print(random_nums)

➔​ Example:(2)
# Random module
[Link](42) # For reproducibility

# Uniform distribution [0, 1)


rand_nums = [Link](5)

# Integers in range
random_ints = [Link](0, 10, size=5)

# Normal distribution
normal_nums = [Link](loc=0, scale=1, size=5)

# Random choice

27
Python Programming

choices = [Link]([1, 2, 3, 4, 5], size=3)

# Shuffle
arr = [Link](10)
[Link](arr)

★​ Why do we need PRNG:


➔​ With the advent of computers, programmers recognized the need for a means of
introducing randomness into a computer program. However, surprising as it may
seem, it is difficult to get a computer to do something by chance as computer follows
the given instructions blindly and is therefore completely predictable. It is not possible
to generate truly random numbers from deterministic thing like computers so PRNG
is a technique developed to generate random numbers using a computer.

★​ Characteristics of PRNG:
●​ Efficient: PRNG can produce many numbers in a short time and is advantageous for
applications that need many numbers
●​ Deterministic: A given sequence of numbers can be reproduced at a later date if the
starting point in the sequence is [Link] is handy if you need to replay
the same sequence of numbers again at a later stage.
●​ Periodic: PRNGs are periodic, which means that the sequence will eventually repeat
itself. While periodicity is hardly ever a desirable characteristic, modern PRNGs have
a period that is so long that it can be ignored for most practical purposes

★​ Applications of PRNG:
➔​ PRNGs are suitable for applications where many random numbers are required and
where it is useful that the same sequence can be replayed easily. Popular examples
of such applications are simulation and modeling applications. PRNGs are not
suitable for applications where it is important that the numbers are really
unpredictable, such as data encryption and gambling.

13. Array Operations (Sum, Mean)


➔​ sum() is a NumPy function used to calculate the sum of array elements. It can sum
values across the entire array or along a specific axis. It also allows controlling the
output data type, initial value, and shape of the result.
➔​ Example:(1)
arr = [Link]([5,10,15,20])

print([Link](arr))
print([Link](arr))

➔​ Example:(2)
arr = [Link]([[1, 2, 3], [4, 5, 6]])

# Aggregations
print([Link](arr)) # 21
print([Link](arr)) # 3.5
print([Link](arr)) #1

28
Python Programming

print([Link](arr)) #6
print([Link](arr)) # Standard deviation
print([Link](arr)) # Variance

# Axis-wise operations
print([Link](arr, axis=0)) # Column sums: [5 7 9]
print([Link](arr, axis=1)) # Row sums: [6 15]

# Other useful operations


print([Link](arr)) # Cumulative sum
print([Link](arr)) # Sort each row
print([Link](arr)) # Unique elements

❖​ KEY DIFFERENCES TO REMEMBER:

Feature Python List NumPy Array

Memory More memory Memory efficient

Speed Slower Faster (C backend)

Operations Element-wise loops Vectorized operations

Data Type Can be mixed Homogeneous

29
Python Programming

Unit - IV
Pandas (Series, DataFrames & Data Handling)

●​ Series,
●​ DataFrames, reading CSV files,
●​ DataFrame operations: head(), tail(), info(), shape, reshape(), columns,
●​ Handling Missing Data: isnull(), dropna(),
●​ Statistical Functions: mean(), sum(), describe(), value_counts(), corr(),
●​ Data Selection and Indexing: loc, iloc,
●​ Apply Function: apply,
●​ Data Filtering and Sorting: Data filtering, sorting,
●​ Basic Data Cleaning: basic data cleaning.

❖​ Pandas:
➔​ Pandas, a powerful Python library used for data analysis and manipulation.
➔​ It mainly works with two data structures: Series and DataFrame.
➔​ [NOTE: This unit helps students understand how to efficiently manage, analyze, and
clean real-world data using Pandas, which is essential for data science, machine
learning, and software development.]

1. Series
➔​ A Series is a one-dimensional labeled array that can hold data like integers, floats,
strings, or Python objects. Each value in a Series has an index.
➔​ Example use: storing marks of students or daily temperature values.
➔​ Creating Series:
import pandas as pd
import numpy as np

# From list
s1 = [Link]([1, 3, 5, [Link], 6, 8])

# From dictionary
s2 = [Link]({'A': 10, 'B': 20, 'C': 30})

# With custom index


s3 = [Link]([10, 20, 30], index=['a', 'b', 'c'])

2. DataFrame
➔​ A DataFrame is a two-dimensional data structure similar to a table or spreadsheet. It
consists of rows and columns, where each column can contain different data types.
DataFrames are widely used for handling large datasets.
➔​ Creating DataFrames:
# From dictionary
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['NYC', 'LA', 'Chicago']
})

30
Python Programming

# From list of lists


data = [[1, 'Alice', 25], [2, 'Bob', 30]]
df = [Link](data, columns=['ID', 'Name', 'Age'])

3. Reading CSV Files


➔​ CSV (Comma Separated Values) files are commonly used for storing tabular data.
Pandas provides a simple function read_csv() to load data into a DataFrame. Once
loaded, the data can be easily explored, filtered, and analyzed.
➔​ Example:
# Basic reading
df = pd.read_csv('[Link]')
# With parameters
df = pd.read_csv('[Link]',
header=0, # Row number for header
sep=',', # Separator
encoding='utf-8', # File encoding
na_values=['NA', 'N/A', '']) # Values to treat as NaN

4. Basic DataFrame Operations


●​ head(): Displays the first 5 rows of the DataFrame (or a specified number).
●​ tail(): Displays the last 5 rows.
●​ info(): Shows data types, number of non-null values, and memory usage.
●​ shape: Returns the number of rows and columns in the form (rows, columns).
●​ reshape(): Changes the structure of the data (mainly used with NumPy arrays, but
conceptually important for data formatting).
●​ columns: Displays or modifies column names of the DataFrame.

➔​ Basic Inspection:
[Link](3) # First n rows (default 5)
[Link](3) # Last n rows (default 5)
[Link]() # Summary of DataFrame
[Link] # Returns (rows, columns)
[Link] # Column names
[Link] # Data types of each column
[Link]() # Statistical summary

5. Handling Missing Data


●​ isnull(): Detects missing (NaN) values and returns True or False.
●​ dropna(): Removes rows or columns that contain missing values.
➔​ Example:
[Link]() # Boolean mask of missing values
[Link]().sum() # Count missing values per column
[Link]() # Drop rows with missing values
[Link](axis=1) # Drop columns with missing values
[Link](subset=['Column1']) # Drop rows with NaN in specific column
[Link](0) # Fill missing values with 0
[Link]([Link]()) # Fill with column means

31
Python Programming

6. Statistical Functions
●​ mean(): Calculates the average of values in a column.
●​ sum(): Calculates the total sum of values.
●​ describe(): Provides a summary of statistics such as count, mean, standard
deviation, min, and max.
●​ value_counts(): Counts unique values in a column and shows their frequency.
●​ corr(): Finds the correlation between numerical columns, useful for understanding
relationships in data.

➔​ Example:
[Link]() # Column-wise mean
[Link]() # Column-wise sum
[Link]() # Minimum values
[Link]() # Maximum values
[Link]() # Standard deviation
[Link]() # Median values
[Link]() # Count non-null values
[Link]() # Correlation matrix
df['Column'].value_counts() # Frequency of unique values

7. Data Selection and Indexing


●​ loc[]: Used for selecting data by label (row and column names).
●​ iloc[]: Used for selecting data by integer index positions.

➔​ Example:
# Column selection
df['Column'] # Single column (returns Series)
df[['Col1', 'Col2']] # Multiple columns (returns DataFrame)

# Label-based indexing with loc


[Link][row_label] # Single row by label
[Link][row_label, 'Column'] # Specific cell
[Link][start:end] # Slice of rows
[Link][:, ['Col1', 'Col2']] # All rows, specific columns

# Position-based indexing with iloc


[Link][0] # First row
[Link][0, 1] # First row, second column
[Link][0:5] # Rows 0 to 4
[Link][:, 0:2] # All rows, first 2 columns

8. Apply Function
➔​ The apply() function is used to apply a custom function to rows or columns of a
DataFrame. This is helpful for data transformation and feature creation.

32
Python Programming

➔​ Example:

# Using apply()
df['New_Col'] = df['Column'].apply(lambda x: x*2)
df['Category'] = df['Age'].apply(lambda x: 'Young' if x < 30 else 'Adult')

# Vectorized operations (faster)


df['New_Col'] = df['Column'] * 2

9. Data Filtering and Sorting


●​ Filtering: Selecting specific rows based on conditions (e.g., students with marks
above 60).
●​ Sorting: Arranging data in ascending or descending order using sort_values().

➔​ Data Filtering:
# Boolean indexing
df[df['Age'] > 25] # Simple condition
df[(df['Age'] > 25) & (df['City'] == 'NYC')] # Multiple conditions
df[df['Name'].[Link]('Al')] # String contains
df[df['Column'].isin(['A', 'B', 'C'])] # Value in list

➔​ Sorting:
df.sort_values('Age') # Sort by column
df.sort_values('Age', ascending=False) # Descending order
df.sort_values(['Col1', 'Col2']) # Sort by multiple columns
df.sort_index() # Sort by index

10. Basic Data Cleaning


➔​ Data cleaning involves handling missing values, correcting incorrect data, removing
duplicates, and formatting columns properly to make the dataset ready for analysis.
➔​ Example:
# Complete data cleaning workflow
def clean_data(df):
# 1. Remove duplicates
df = df.drop_duplicates()

# 2. Handle missing values


df['Column'] = df['Column'].fillna(df['Column'].median())

# 3. Remove outliers
Q1 = df['Column'].quantile(0.25)
Q3 = df['Column'].quantile(0.75)
IQR = Q3 - Q1
df = df[~((df['Column'] < (Q1 - 1.5 * IQR)) |
(df['Column'] > (Q3 + 1.5 * IQR)))]

33
Python Programming

# 4. Standardize text columns


df['Name'] = df['Name'].[Link]().[Link]()

# 5. Reset index
df = df.reset_index(drop=True)

return df

➔​ Reshaping Data:
# Pivot tables
pivot = df.pivot_table(values='Value',
index='Date',
columns='Category',
aggfunc='mean')

# Melt (unpivot)
melted = [Link](df, id_vars=['ID'],
value_vars=['Jan', 'Feb', 'Mar'],
var_name='Month',
value_name='Sales')

# Stack/Unstack
stacked = [Link]() # Move column labels to index
unstacked = [Link]() # Move index labels to columns

34
Python Programming

Unit-V
Data Visualization, Libraries, Error Handling, File I/O & Flask

●​ Data Visualization using Matplotlib: Line plots, bar plots, histograms, scatter plots,
subplots, custom labels.
●​ Overview of Scientific Libraries: Scikitlearn, SciPy, NetworkX.
●​ Error handling: NameError, TypeError, ValueError with try, except, finally.
●​ File I/O: reading/writing text files.
●​ Web development with Flask.

1. Data Visualization using Matplotlib


➔​ Data visualization helps in understanding patterns, trends, and relationships in data.
Python mainly uses the Matplotlib library for plotting graphs.

(a) Line Plot


➔​ A line plot displays data points connected by straight lines. It is used to show trends
over time.
➔​ Uses: Growth analysis, performance tracking.
➔​ Example: Temperature vs Days.
➔​ Example (Matplotlib):
import [Link] as plt

x = [1, 2, 3, 4]
y = [10, 20, 25, 30]

[Link](x, y)
[Link]("X Axis")
[Link]("Y Axis")
[Link]("Line Plot Example")
[Link]()

(b) Bar Plot


➔​ A bar plot represents categorical data with rectangular bars.
➔​ Used to compare values between categories.
➔​ Uses: Comparison between categories.
➔​ Example: Marks of students in different subjects.
➔​ Example:
import [Link] as plt

subjects = ["Math", "Sci", "Eng"]


marks = [85, 90, 78]

[Link](subjects, marks)
[Link]("Bar Plot")
[Link]()

35
Python Programming

(c) Histogram
➔​ A histogram shows the frequency distribution of numerical data.
➔​ Uses: Data distribution analysis.
➔​ Example: Age distribution of people.
➔​ Example:
import [Link] as plt

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


[Link](data, bins=5)
[Link]("Histogram")
[Link]()

(d) Scatter Plot


➔​ A scatter plot displays points based on two variables.
➔​ Display relationship between two variables.
➔​ Uses: Relationship between variables.
➔​ Example: Height vs Weight.
➔​ Example:
import [Link] as plt

x = [1, 2, 3, 4]
y = [5, 7, 6, 8]

[Link](x, y)
[Link]("Scatter Plot")
[Link]()

(e) Subplots
➔​ Subplots allow multiple plots in a single figure.
➔​ Uses: Comparing multiple visualizations together
➔​ Example:
import [Link] as plt

[Link](1, 2, 1)
[Link]([1, 2, 3], [4, 5, 6])
[Link]("Plot 1")

[Link](1, 2, 2)
[Link]([1, 2, 3], [3, 7, 5])
[Link]("Plot 2")

[Link]()

(f) Custom Labels


➔​ Labels improve readability of graphs.
➔​ Custom labels include:
◆​ Title

36
Python Programming

◆​ X-axis label
◆​ Y-axis label
◆​ Legend
➔​ These improve readability and understanding of graphs.

2. Overview of Scientific Libraries

(a) Scikit-learn
➔​ Scikit-learn is a machine learning library used for:
◆​ Classification
◆​ Regression
◆​ Clustering
◆​ Model evaluation
➔​ It provides simple and efficient tools for data analysis and predictive modeling.
➔​ Example: from sklearn.linear_model import LinearRegression

(b) SciPy
➔​ SciPy is used for scientific and mathematical computations.
➔​ Main features:
◆​ Linear algebra
◆​ Integration
◆​ Optimization
◆​ Statistics
◆​ Signal and image processing

(c) NetworkX
➔​ NetworkX is used to create and analyze graphs and networks.
➔​ Applications:
◆​ Social networks
◆​ Computer networks
◆​ Transportation systems

3. Error Handling in Python


➔​ Errors may occur during program execution. Python handles errors using try,
except, and finally.
➔​ Used to prevent program crash and handle errors properly.
➔​ Syntax:
try:
x = int(input("Enter number: "))
print(10 / x)
except NameError:
print("Variable not defined")
except TypeError:
print("Wrong type")
except ValueError:
print("Invalid value")
finally:
print("Execution completed")

37
Python Programming

★​ Common Errors:
●​ NameError: When a variable is not defined
●​ TypeError: When an operation is applied to incompatible data types
●​ ValueError: When a function receives an argument of correct type but invalid value

★​ Error Handling Structure:


●​ try block contains risky code
●​ except block handles the error
●​ finally block executes always (used for cleanup)

4. File Input and Output (File I/O)


➔​ File handling allows programs to store and retrieve data permanently.

❖​ Reading Text Files


➔​ Used to read data from files using different modes.
➔​ Example:
file = open("[Link]", "r")
print([Link]())
[Link]()

❖​ Writing Text Files


➔​ Used to write or append data into files.
➔​ Example:
file = open("[Link]", "w")
[Link]("Hello Python")
[Link]()

★​ Common file modes:


●​ r – read
●​ w – write
●​ a – append

5. Web Development with Flask


➔​ Flask is a lightweight Python web framework used to develop web applications.

★​ Basic Flask App:


from flask import Flask
app = Flask(__name__)

@[Link]("/")
def home():
return "Welcome to Flask Web App"

[Link]()

38
Python Programming

★​ Features:
●​ Simple and flexible
●​ Built-in development server
●​ URL routing
●​ Template support

★​ Uses:
●​ Creating web applications
●​ APIs
●​ Small to medium-scale projects

Summary:
●​ Plots → Data visualization using Matplotlib
●​ Scikit-learn → Machine Learning
●​ SciPy → Scientific computing
●​ NetworkX → Graph analysis
●​ try-except-finally → Error handling
●​ File I/O → Read/write files
●​ Flask → Python web framework

39

You might also like