0% found this document useful (0 votes)
3 views

Python Unit IV

This study guide covers advanced Python topics including functional programming concepts like lambda functions, list comprehensions, and map/reduce/filter functions. It also introduces the NumPy library for numerical computing, detailing array creation, manipulation, and operations, as well as the Pandas library for data preparation and visualization techniques using Matplotlib. Additionally, it provides insights into GUI programming with Tkinter, including creating user interfaces and handling various widgets.

Uploaded by

yadavdikshit111
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 views

Python Unit IV

This study guide covers advanced Python topics including functional programming concepts like lambda functions, list comprehensions, and map/reduce/filter functions. It also introduces the NumPy library for numerical computing, detailing array creation, manipulation, and operations, as well as the Pandas library for data preparation and visualization techniques using Matplotlib. Additionally, it provides insights into GUI programming with Tkinter, including creating user interfaces and handling various widgets.

Uploaded by

yadavdikshit111
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/ 12

PYTHON UNIT IV STUDY GUIDE

Advanced Python & Libraries - End Semester Exam Preparation

1. FUNCTIONAL PROGRAMMING
Lambda Functions
Lambda functions are small, anonymous functions that can have any number of arguments but can only have
one expression.

Syntax: lambda arguments: expression

Examples:

# Simple lambda function


square = lambda x: x ** 2
print(square(5)) # Output: 25

# Lambda with multiple arguments


add = lambda x, y: x + y
print(add(3, 7)) # Output: 10

# Lambda for finding maximum


max_num = lambda a, b: a if a > b else b
print(max_num(10, 20)) # Output: 20

Explanation: Lambda functions are useful for short, simple operations that don't require a full function
definition.

List Comprehensions
List comprehensions provide a concise way to create lists based on existing lists or ranges.

Syntax: [expression for item in iterable if condition]

Examples:

# Basic list comprehension


squares = [x**2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]

# With condition
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(even_squares) # Output: [4, 16, 36, 64, 100]

# From existing list


names = ['alice', 'bob', 'charlie']
upper_names = [name.upper() for name in names]
print(upper_names) # Output: ['ALICE', 'BOB', 'CHARLIE']

Explanation: List comprehensions are faster and more readable than traditional for loops for creating lists.
Map, Reduce, Filter Functions
Map Function

Applies a function to every item in an iterable.

# Using map with a function


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

# Map with built-in function


strings = ['1', '2', '3', '4']
integers = list(map(int, strings))
print(integers) # Output: [1, 2, 3, 4]

Filter Function

Filters items from an iterable based on a condition.

# Filter even numbers


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6, 8, 10]

# Filter strings by length


words = ['cat', 'elephant', 'dog', 'hippopotamus']
long_words = list(filter(lambda word: len(word) > 3, words))
print(long_words) # Output: ['elephant', 'hippopotamus']

Reduce Function

Applies a function cumulatively to items in an iterable.

from functools import reduce

# Sum of all numbers


numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total) # Output: 15

# Find maximum
maximum = reduce(lambda x, y: x if x > y else y, numbers)
print(maximum) # Output: 5

Explanation: These functions enable functional programming style and are very useful for data processing.

2. NUMPY LIBRARY
Introduction to NumPy
NumPy is a library for numerical computing in Python. It provides support for arrays and mathematical
functions.

import numpy as np
print(np.__version__) # Check NumPy version
Creating One-Dimensional Arrays
import numpy as np

# From a list
arr1 = np.array([1, 2, 3, 4, 5])
print(arr1) # Output: [1 2 3 4 5]

# Using arange
arr2 = np.arange(0, 10, 2)
print(arr2) # Output: [0 2 4 6 8]

# Using linspace
arr3 = np.linspace(0, 1, 5)
print(arr3) # Output: [0. 0.25 0.5 0.75 1.]

# Arrays of zeros and ones


zeros = np.zeros(5)
ones = np.ones(3)
print(zeros) # Output: [0. 0. 0. 0. 0.]
print(ones) # Output: [1. 1. 1.]

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

# Reshape to 2x3
reshaped = arr.reshape(2, 3)
print(reshaped)
# Output:
# [[1 2 3]
# [4 5 6]]

# Reshape to 3x2
reshaped2 = arr.reshape(3, 2)
print(reshaped2)
# Output:
# [[1 2]
# [3 4]
# [5 6]]

Element-wise and Aggregate Operations


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

# Element-wise operations
print(arr + 10) # Output: [11 12 13 14 15]
print(arr * 2) # Output: [2 4 6 8 10]
print(arr ** 2) # Output: [1 4 9 16 25]

# Aggregate operations
print(np.sum(arr)) # Output: 15
print(np.mean(arr)) # Output: 3.0
print(np.max(arr)) # Output: 5
print(np.min(arr)) # Output: 1
print(np.std(arr)) # Output: 1.58... (standard deviation)

Array Indexing and Slicing


arr = np.array([10, 20, 30, 40, 50])

# Indexing
print(arr[0]) # Output: 10 (first element)
print(arr[-1]) # Output: 50 (last element)

# Slicing
print(arr[1:4]) # Output: [20 30 40]
print(arr[:3]) # Output: [10 20 30]
print(arr[2:]) # Output: [30 40 50]

# Boolean indexing
print(arr[arr > 25]) # Output: [30 40 50]

Inserting and Appending Rows/Columns


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

# Insert
inserted = np.insert(arr, 1, 99)
print(inserted) # Output: [1 99 2 3]

# Append
appended = np.append(arr, [4, 5])
print(appended) # Output: [1 2 3 4 5]

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

# Insert row
new_row = np.insert(arr2d, 1, [5, 6], axis=0)
print(new_row)
# Output:
# [[1 2]
# [5 6]
# [3 4]]

# Insert column
new_col = np.insert(arr2d, 1, [7, 8], axis=1)
print(new_col)
# Output:
# [[1 7 2]
# [3 8 4]]

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

# Transpose
transposed = arr.T
print(transposed)
# Output:
# [[1 3]
# [2 4]]

# Flatten
flattened = arr.flatten()
print(flattened) # Output: [1 2 3 4]

# Concatenate
arr2 = np.array([[5, 6], [7, 8]])
concat = np.concatenate([arr, arr2], axis=0)
print(concat)
# Output:
# [[1 2]
# [3 4]
# [5 6]
# [7 8]]

Multi-dimensional Arrays
# Creating 2D array
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2d.shape) # Output: (2, 3)

# Creating 3D array
arr3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(arr3d.shape) # Output: (2, 2, 2)

# Accessing elements in 2D array


print(arr2d[0, 1]) # Output: 2
print(arr2d[1, :]) # Output: [4 5 6] (entire second row)
print(arr2d[:, 2]) # Output: [3 6] (entire third column)

3. PANDAS LIBRARY
Data Preparation and Pre-processing
import pandas as pd

# Reading data from CSV


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

# Basic info about dataset


print(df.head()) # First 5 rows
print(df.tail()) # Last 5 rows
print(df.info()) # Data types and info
print(df.describe()) # Statistical summary
print(df.shape) # Dimensions (rows, columns)

Series and Querying Series


# Creating a Series
data = [10, 20, 30, 40, 50]
series = pd.Series(data, index=['a', 'b', 'c', 'd', 'e'])
print(series)

# Querying Series
print(series['a']) # Output: 10
print(series[series > 25]) # Values greater than 25
print(series.loc['b':'d']) # Slice from 'b' to 'd'

# Series operations
print(series.sum()) # Sum of all values
print(series.mean()) # Average
print(series.max()) # Maximum value

DataFrames: Indexing, Loading, Querying


# Creating DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Tokyo']}
df = pd.DataFrame(data)
print(df)
# Loading from CSV
df = pd.read_csv('file.csv')

# Indexing and Querying


print(df['Name']) # Select column
print(df[['Name', 'Age']]) # Select multiple columns
print(df.loc[0]) # Select row by index
print(df.iloc[0:2]) # Select first two rows

# Conditional querying
young_people = df[df['Age'] < 30]
print(young_people)

# Add new column


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

Handling Missing Values


# Creating DataFrame with missing values
data = {'A': [1, 2, None, 4],
'B': [5, None, 7, 8],
'C': [9, 10, 11, None]}
df = pd.DataFrame(data)

# Check for missing values


print(df.isnull()) # Boolean mask
print(df.isnull().sum()) # Count missing values per column

# Remove missing values


df_dropped = df.dropna() # Drop rows with any missing values
df_dropped_cols = df.dropna(axis=1) # Drop columns with missing values

# Fill missing values


df_filled = df.fillna(0) # Fill with 0
df_filled_mean = df.fillna(df.mean()) # Fill with column mean

# Forward fill and backward fill


df_ffill = df.fillna(method='ffill') # Forward fill
df_bfill = df.fillna(method='bfill') # Backward fill

4. DATA VISUALIZATION (MATPLOTLIB)


Bar Charts, Pie Charts, Scatter Plots
import matplotlib.pyplot as plt

# Bar Chart
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 78]

plt.bar(categories, values)
plt.title('Bar Chart')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()

# Pie Chart
labels = ['Python', 'Java', 'C++', 'JavaScript']
sizes = [40, 30, 20, 10]

plt.pie(sizes, labels=labels, autopct='%1.1f%%')


plt.title('Programming Languages')
plt.show()

# Scatter Plot
x = [1, 2, 3, 4, 5]
y = [2, 5, 3, 8, 7]

plt.scatter(x, y)
plt.title('Scatter Plot')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.show()

Multiple and Subplots


# Multiple plots on same figure
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 2, 3, 4, 5]

plt.plot(x, y1, label='Squared')


plt.plot(x, y2, label='Linear')
plt.legend()
plt.show()

# Subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))

# First subplot
ax1.plot(x, y1)
ax1.set_title('Squared')

# Second subplot
ax2.plot(x, y2)
ax2.set_title('Linear')

plt.tight_layout()
plt.show()

Legends and Styling Plots


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

plt.plot(x, y, color='red', linestyle='--', marker='o', label='Data')


plt.title('Styled Plot', fontsize=16)
plt.xlabel('X axis', fontsize=12)
plt.ylabel('Y axis', fontsize=12)
plt.legend()
plt.grid(True)
plt.show()

# Color and style options


plt.plot(x, y, 'ro--') # Red circles with dashed lines
plt.plot(x, y, color='blue', marker='s', linestyle=':')

Changing Figure Size


# Method 1: Using figure()
plt.figure(figsize=(10, 6))
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()

# Method 2: Using subplots()


fig, ax = plt.subplots(figsize=(8, 5))
ax.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()

# Save figure
plt.savefig('my_plot.png', dpi=300, bbox_inches='tight')

5. GUI PROGRAMMING (TKINTER)


Creating User Interfaces
import tkinter as tk

# Basic window
root = tk.Tk()
root.title("My GUI Application")
root.geometry("300x200")

# Label
label = tk.Label(root, text="Hello, World!")
label.pack()

# Button
def button_click():
print("Button clicked!")

button = tk.Button(root, text="Click Me", command=button_click)


button.pack()

root.mainloop()

Widgets and Layouts


import tkinter as tk

root = tk.Tk()
root.title("Widgets Demo")

# Entry widget
entry = tk.Entry(root)
entry.pack()

# Text widget
text = tk.Text(root, height=5, width=30)
text.pack()

# Using grid layout


label1 = tk.Label(root, text="Name:")
label1.grid(row=0, column=0)

entry1 = tk.Entry(root)
entry1.grid(row=0, column=1)

label2 = tk.Label(root, text="Email:")


label2.grid(row=1, column=0)

entry2 = tk.Entry(root)
entry2.grid(row=1, column=1)

root.mainloop()

Checkboxes, Radio Buttons, List Boxes


import tkinter as tk

root = tk.Tk()

# Checkbox
var1 = tk.BooleanVar()
checkbox = tk.Checkbutton(root, text="Check me", variable=var1)
checkbox.pack()

# Radio buttons
var2 = tk.StringVar()
var2.set("Option1") # Default selection

radio1 = tk.Radiobutton(root, text="Option 1", variable=var2, value="Option1")


radio2 = tk.Radiobutton(root, text="Option 2", variable=var2, value="Option2")
radio1.pack()
radio2.pack()

# Listbox
listbox = tk.Listbox(root)
listbox.insert(1, "Item 1")
listbox.insert(2, "Item 2")
listbox.insert(3, "Item 3")
listbox.pack()

root.mainloop()

Menus and Menu Options


import tkinter as tk

root = tk.Tk()

# Create menubar
menubar = tk.Menu(root)
root.config(menu=menubar)

# File menu
file_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="New")
file_menu.add_command(label="Open")
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit)

# Edit menu
edit_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="Edit", menu=edit_menu)
edit_menu.add_command(label="Cut")
edit_menu.add_command(label="Copy")
edit_menu.add_command(label="Paste")

root.mainloop()

Dialog Boxes
import tkinter as tk
from tkinter import messagebox, filedialog

root = tk.Tk()

# Message box
def show_info():
messagebox.showinfo("Info", "This is an information message")
def show_warning():
messagebox.showwarning("Warning", "This is a warning message")

def show_error():
messagebox.showerror("Error", "This is an error message")

# File dialog
def open_file():
filename = filedialog.askopenfilename()
print(f"Selected file: {filename}")

def save_file():
filename = filedialog.asksaveasfilename()
print(f"Save as: {filename}")

# Buttons
tk.Button(root, text="Show Info", command=show_info).pack()
tk.Button(root, text="Show Warning", command=show_warning).pack()
tk.Button(root, text="Open File", command=open_file).pack()
tk.Button(root, text="Save File", command=save_file).pack()

root.mainloop()

6. DATABASE ACCESS
Create, Insert, Select, Delete, Drop, Update Operations
import sqlite3

# Connect to database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()

# CREATE table
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER,
grade TEXT
)
''')

# INSERT data
cursor.execute("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)",
("Alice", 20, "A"))
cursor.execute("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)",
("Bob", 22, "B"))

# INSERT multiple records


students = [("Charlie", 21, "A"), ("Diana", 19, "B+")]
cursor.executemany("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)",
students)

# SELECT data
cursor.execute("SELECT * FROM students")
all_students = cursor.fetchall()
print("All students:", all_students)

cursor.execute("SELECT name, age FROM students WHERE grade = 'A'")


a_grade_students = cursor.fetchall()
print("A grade students:", a_grade_students)
# UPDATE data
cursor.execute("UPDATE students SET age = ? WHERE name = ?", (21, "Alice"))

# DELETE data
cursor.execute("DELETE FROM students WHERE name = ?", ("Bob",))

# DROP table
# cursor.execute("DROP TABLE students")

# Commit changes and close


conn.commit()
conn.close()

Joins and Database Connectivity


import sqlite3

# Connect to database
conn = sqlite3.connect('school.db')
cursor = conn.cursor()

# Create tables
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
student_id INTEGER PRIMARY KEY,
name TEXT,
class_id INTEGER
)
''')

cursor.execute('''
CREATE TABLE IF NOT EXISTS classes (
class_id INTEGER PRIMARY KEY,
class_name TEXT,
teacher TEXT
)
''')

# Insert sample data


cursor.execute("INSERT INTO classes VALUES (1, 'Math', 'Mr. Smith')")
cursor.execute("INSERT INTO classes VALUES (2, 'Science', 'Ms. Johnson')")

cursor.execute("INSERT INTO students VALUES (1, 'Alice', 1)")


cursor.execute("INSERT INTO students VALUES (2, 'Bob', 2)")
cursor.execute("INSERT INTO students VALUES (3, 'Charlie', 1)")

# INNER JOIN
cursor.execute('''
SELECT students.name, classes.class_name, classes.teacher
FROM students
INNER JOIN classes ON students.class_id = classes.class_id
''')

results = cursor.fetchall()
print("Join Results:")
for row in results:
print(f"Student: {row[0]}, Class: {row[1]}, Teacher: {row[2]}")

# LEFT JOIN
cursor.execute('''
SELECT students.name, classes.class_name
FROM students
LEFT JOIN classes ON students.class_id = classes.class_id
''')

conn.commit()
conn.close()

# Database connectivity with error handling


def connect_database():
try:
conn = sqlite3.connect('database.db')
print("Database connected successfully")
return conn
except sqlite3.Error as e:
print(f"Error connecting to database: {e}")
return None

# Using context manager (recommended)


def safe_database_operation():
try:
with sqlite3.connect('example.db') as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM students")
results = cursor.fetchall()
return results
except sqlite3.Error as e:
print(f"Database error: {e}")
return None

EXAM TIPS:
1. Practice code execution: Run these examples and understand the output
2. Remember syntax: Pay attention to function names and parameters
3. Understand concepts: Know when to use each function/method
4. Error handling: Always consider what could go wrong
5. Import statements: Remember to import required libraries
6. Common patterns: Many operations follow similar patterns across libraries

Good luck with your exam!

You might also like