Python Unit IV
Python Unit IV
1. FUNCTIONAL PROGRAMMING
Lambda Functions
Lambda functions are small, anonymous functions that can have any number of arguments but can only have
one expression.
Examples:
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.
Examples:
# 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]
Explanation: List comprehensions are faster and more readable than traditional for loops for creating lists.
Map, Reduce, Filter Functions
Map Function
Filter Function
Reduce Function
# 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.]
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 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)
# 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]
# 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)
3. PANDAS LIBRARY
Data Preparation and Pre-processing
import pandas as pd
# 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
# Conditional querying
young_people = df[df['Age'] < 30]
print(young_people)
# 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]
# 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()
# 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()
# Save figure
plt.savefig('my_plot.png', dpi=300, bbox_inches='tight')
# 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!")
root.mainloop()
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()
entry1 = tk.Entry(root)
entry1.grid(row=0, column=1)
entry2 = tk.Entry(root)
entry2.grid(row=1, column=1)
root.mainloop()
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
# Listbox
listbox = tk.Listbox(root)
listbox.insert(1, "Item 1")
listbox.insert(2, "Item 2")
listbox.insert(3, "Item 3")
listbox.pack()
root.mainloop()
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"))
# SELECT data
cursor.execute("SELECT * FROM students")
all_students = cursor.fetchall()
print("All students:", all_students)
# DELETE data
cursor.execute("DELETE FROM students WHERE name = ?", ("Bob",))
# DROP table
# cursor.execute("DROP TABLE students")
# 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
)
''')
# 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()
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