Basic Python Practice
Practice Topics
1.1 Variables and Data Types
Practice working with different data types and variables.
Task: Data Type Operations
Given two variables of different types, perform various operations:
- Create a string variable with a number inside it
- Create an integer variable
- Convert the string to an integer and add to the integer
- Convert the result to a float and print with 2 decimal places
- Convert the result to a string and add a message
num_str = "42"
num_int = 8
# Convert and add
result = int(num_str) + num_int
# Convert to float and format
result_float = float(result)
print(f"Result: {result_float:.2f}")
Quick Quiz
What will be the output of the following code?
x = 5 y = "10" z = x + int(y) print(z)
1.2 String Operations
Practice string manipulation and formatting.
Task: String Manipulation
Given a string with extra spaces and mixed case:
- Remove leading and trailing whitespace
- Convert to lowercase
- Replace all occurrences of "python" with "Python"
- Split the string into words and count them
- Join the words back with hyphens
text = " hello python world "
# Remove whitespace and lowercase
clean_text = text.strip().lower()
# Replace
replaced = clean_text.replace("python", "Python")
# Split and count
words = replaced.split()
word_count = len(words)
# Join with hyphens
hyphenated = "-".join(words)
1.3 Basic Math Operations
Practice mathematical operations and the math module.
Task: Mathematical Calculations
Perform calculations using basic operators and the math module:
- Calculate the area of a circle with radius 5
- Find the square root of 144
- Round 3.14159 to 2 decimal places
- Find the minimum and maximum of a list of numbers
- Calculate the sum of numbers from 1 to 100
# Area of circle
radius = 5
area = math.pi * radius ** 2
# Square root
sqrt_144 = math.sqrt(144)
# Rounding
rounded = round(3.14159, 2)
# Min and max
numbers = [5, 10, 3, 8, 1]
min_val = min(numbers)
max_val = max(numbers)
# Sum from 1 to 100
total = sum(range(1, 101))
Logic and Control Flow Practice
2.1 Conditional Statements
Practice using if-elif-else statements for decision making.
Task: Grade Calculator
Write a program that converts a numeric score to a letter grade:
- Take a score from 0-100 as input
- Convert to letter grade: A (90-100), B (80-89), C (70-79), D (60-69), F (below 60)
- Handle edge cases (scores outside 0-100 range)
- Add a plus/minus modifier for scores within 2 points of the next grade
if score > 100 or score < 0:
return "Invalid score"
elif score >= 90:
if score >= 98:
return "A+"
elif score <= 92:
return "A-"
else:
return "A"
# Continue with other grades...
Quick Quiz
What will be the output of the following code?
x = 15
if x > 10:
if x > 20:
print("A")
else:
print("B")
else:
print("C")
2.2 Loops
Practice using for and while loops for iteration.
Task: List Operations with Loops
Given two lists of numbers, perform operations using loops:
- List A: [1, 2, 3, 4, 5]
- List B: [10, 20, 30, 40, 50]
- Create a new list with elements from List A multiplied by corresponding elements in List B
- Find the sum of all elements in the new list
- Find the average of the new list
- Use a while loop to find the first element in the new list that's greater than 100
list_b = [10, 20, 30, 40, 50]
# Create new list
new_list = []
for i in range(len(list_a)):
new_list.append(list_a[i] * list_b[i])
# Find sum and average
total = sum(new_list)
average = total / len(new_list)
# Find first element > 100
i = 0
while i < len(new_list) and new_list[i] <= 100:
i += 1
if i < len(new_list):
print(f"First element > 100: {new_list[i]}")
2.3 Logical Operations
Practice using logical operators (and, or, not) to combine conditions.
Task: Data Filtering
Given a list of people with age and salary, filter based on conditions:
- Create a list of dictionaries with name, age, and salary
- Find people who are older than 30 AND earn more than $50000
- Find people who are younger than 25 OR earn less than $30000
- Find people who are NOT in the age range 25-35
- Count how many people meet each condition
{"name": "Alice", "age": 32, "salary": 60000},
{"name": "Bob", "age": 24, "salary": 45000},
# Add more people...
]
# Condition 1: older than 30 AND earn more than $50000
group1 = [p for p in people if p["age"] > 30 and p["salary"] > 50000]
# Condition 2: younger than 25 OR earn less than $30000
group2 = [p for p in people if p["age"] < 25 or p["salary"] < 30000]
# Condition 3: NOT in age range 25-35
group3 = [p for p in people if not (25 <= p["age"] <= 35)]
# Count
count1 = len(group1)
count2 = len(group2)
count3 = len(group3)
Data Structures Practice
3.1 List Operations
Practice working with lists, including slicing, comprehension, and methods.
Task: List Manipulation
Given a list of numbers, perform various operations:
- Create a list of numbers from 1 to 20
- Extract every third number using slicing
- Create a new list with squares of the original numbers
- Filter the original list to keep only even numbers
- Sort the list in descending order
- Remove duplicates from the list
numbers = list(range(1, 21))
# Extract every third number
every_third = numbers[2::3]
# Create squares
squares = [x**2 for x in numbers]
# Filter even numbers
evens = [x for x in numbers if x % 2 == 0]
# Sort descending
sorted_desc = sorted(numbers, reverse=True)
# Remove duplicates
unique = list(set(numbers))
3.2 Dictionary Operations
Practice working with dictionaries, including creation, access, and manipulation.
Task: Student Records
Create and manipulate student records using dictionaries:
- Create a dictionary with student information (name, age, grades)
- Add a new key-value pair for major
- Calculate the average of the grades
- Create a list of student dictionaries
- Find the student with the highest average grade
- Group students by major
student = {"name": "Alice", "age": 20, "grades": [85, 90, 78]}
# Add major
student["major"] = "Computer Science"
# Calculate average
avg = sum(student["grades"]) / len(student["grades"])
# Create list of students
students = [
{"name": "Alice", "age": 20, "grades": [85, 90, 78], "major": "CS"},
{"name": "Bob", "age": 21, "grades": [75, 80, 82], "major": "Math"},
# Add more students...
]
# Find student with highest average
best_student = max(students, key=lambda s: sum(s["grades"])/len(s["grades"]))
# Group by major
by_major = {}
for s in students:
if s["major"] not in by_major:
by_major[s["major"]] = []
by_major[s["major"]].append(s)
3.3 List and Dictionary Combinations
Practice combining lists and dictionaries for more complex data structures.
Task: Sales Data Analysis
Analyze sales data using lists and dictionaries:
- Create a list of sales records with product, quantity, and price
- Calculate total revenue for each product
- Find the product with the highest revenue
- Group sales by month
- Create a summary report with totals and averages
sales = [
{"product": "Laptop", "quantity": 5, "price": 1200, "month": "Jan"},
{"product": "Mouse", "quantity": 10, "price": 25, "month": "Jan"},
# Add more records...
]
# Calculate revenue by product
product_revenue = {}
for sale in sales:
revenue = sale["quantity"] * sale["price"]
if sale["product"] not in product_revenue:
product_revenue[sale["product"]] = 0
product_revenue[sale["product"]] += revenue
# Find highest revenue product
best_product = max(product_revenue.items(), key=lambda x: x[1])
# Group by month
monthly_sales = {}
for sale in sales:
if sale["month"] not in monthly_sales:
monthly_sales[sale["month"]] = []
monthly_sales[sale["month"]].append(sale)
Functions Practice
4.1 Function Basics
Practice creating and using functions with parameters and return values.
Task: Math Functions
Create functions for common mathematical operations:
- Create a function to calculate the area of a rectangle
- Create a function to calculate the factorial of a number
- Create a function to check if a number is prime
- Create a function that returns multiple values (min, max, average)
- Create a function with default parameters
def rectangle_area(width, height):
return width * height
# Factorial
def factorial(n):
if n <= 1:
return 1
return n * factorial(n-1)
# Prime check
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# Multiple return values
def calculate_stats(numbers):
return min(numbers), max(numbers), sum(numbers)/len(numbers)
# Default parameters
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
4.2 Advanced Functions
Practice with lambda functions, recursion, and higher-order functions.
Task: Functional Programming
Use functional programming concepts to solve problems:
- Use lambda functions with map and filter
- Create a recursive function to calculate Fibonacci numbers
- Implement a decorator to time function execution
- Create a higher-order function that takes another function as parameter
- Use list comprehensions with conditional logic
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Recursive Fibonacci
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
# Timer decorator
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end-start:.5f} seconds")
return result
return wrapper
# Higher-order function
def apply_operation(numbers, operation):
return [operation(x) for x in numbers]
# List comprehension with condition
result = [x**2 for x in range(10) if x % 2 == 0]
4.3 Function Applications
Apply functions to solve practical problems.
Task: Data Processing Pipeline
Create a data processing pipeline using functions:
- Create a function to read and parse data from a string
- Create a function to clean and normalize data
- Create a function to transform data
- Create a function to aggregate data
- Chain the functions together to process the data
def parse_data(data_string):
lines = data_string.strip().split('\n')
records = []
for line in lines:
parts = line.split(',')
records.append({
"name": parts[0],
"age": int(parts[1]),
"score": float(parts[2])
})
return records
# Clean data
def clean_data(records):
cleaned = []
for record in records:
if record["age"] > 0 and 0 <= record["score"] <= 100:
cleaned.append(record)
return cleaned
# Transform data
def transform_data(records):
for record in records:
record["grade"] = calculate_grade(record["score"])
return records
# Aggregate data
def aggregate_data(records):
total = len(records)
avg_score = sum(r["score"] for r in records) / total
return {"count": total, "avg_score": avg_score}
# Process pipeline
def process_pipeline(data_string):
parsed = parse_data(data_string)
cleaned = clean_data(parsed)
transformed = transform_data(cleaned)
return aggregate_data(transformed)
Data Science & Machine Learning Preparation
5.1 Data Analysis Basics
Practice basic data analysis techniques using only Python.
Task: Statistical Analysis
Perform statistical analysis on a dataset:
- Calculate mean, median, and mode of a dataset
- Calculate standard deviation and variance
- Find outliers using the IQR method
- Create a frequency distribution
- Calculate correlation between two variables
def mean(data):
return sum(data) / len(data)
# Median
def median(data):
sorted_data = sorted(data)
n = len(sorted_data)
if n % 2 == 0:
return (sorted_data[n//2-1] + sorted_data[n//2]) / 2
else:
return sorted_data[n//2]
# Mode
def mode(data):
counts = {}
for x in data:
counts[x] = counts.get(x, 0) + 1
max_count = max(counts.values())
return [x for x, count in counts.items() if count == max_count]
# Standard deviation
def std_dev(data):
m = mean(data)
variance = sum((x - m) ** 2 for x in data) / len(data)
return variance ** 0.5
# IQR for outliers
def find_outliers(data):
sorted_data = sorted(data)
q1 = sorted_data[len(sorted_data)//4]
q3 = sorted_data[3*len(sorted_data)//4]
iqr = q3 - q1
lower = q1 - 1.5 * iqr
upper = q3 + 1.5 * iqr
return [x for x in data if x < lower or x > upper]
# Correlation
def correlation(x, y):
n = len(x)
sum_x = sum(x)
sum_y = sum(y)
sum_xy = sum(xi * yi for xi, yi in zip(x, y))
sum_x2 = sum(xi ** 2 for xi in x)
sum_y2 = sum(yi ** 2 for yi in y)
numerator = n * sum_xy - sum_x * sum_y
denominator = ((n * sum_x2 - sum_x**2) * (n * sum_y2 - sum_y**2)) ** 0.5
return numerator / denominator
5.2 Data Visualization Preparation
Prepare data for visualization using basic Python.
Task: Data Preparation for Charts
Prepare data for different types of visualizations:
- Prepare data for a bar chart (categories and values)
- Prepare data for a line chart (x and y coordinates)
- Prepare data for a scatter plot (pairs of x and y values)
- Prepare data for a pie chart (categories and percentages)
- Prepare data for a histogram (bin frequencies)
def prepare_bar_chart(data, labels):
return {"labels": labels, "values": data}
# Line chart data
def prepare_line_chart(x_data, y_data):
return {"x": x_data, "y": y_data}
# Scatter plot data
def prepare_scatter_plot(points):
x = [p[0] for p in points]
y = [p[1] for p in points]
return {"x": x, "y": y}
# Pie chart data
def prepare_pie_chart(data):
total = sum(data.values())
percentages = {k: v/total*100 for k, v in data.items()}
return {"categories": list(data.keys()), "percentages": list(percentages.values())}
# Histogram data
def prepare_histogram(data, bin_count):
min_val, max_val = min(data), max(data)
bin_width = (max_val - min_val) / bin_count
bins = [min_val + i * bin_width for i in range(bin_count + 1)]
frequencies = [0] * bin_count
for value in data:
for i in range(bin_count):
if bins[i] <= value < bins[i+1]:
frequencies[i] += 1
break
return {"bins": bins, "frequencies": frequencies}
5.3 Machine Learning Concepts
Implement basic machine learning concepts using only Python.
Task: Simple ML Algorithms
Implement simple machine learning algorithms:
- Implement a simple linear regression from scratch
- Implement k-nearest neighbors classification
- Implement a simple decision tree
- Implement k-means clustering
- Implement a simple neural network
def linear_regression(x, y):
n = len(x)
sum_x = sum(x)
sum_y = sum(y)
sum_xy = sum(xi * yi for xi, yi in zip(x, y))
sum_x2 = sum(xi ** 2 for xi in x)
slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x ** 2)
intercept = (sum_y - slope * sum_x) / n
return lambda x: slope * x + intercept
# K-nearest neighbors
def knn_classify(test_point, training_data, k=3):
distances = []
for point, label in training_data:
dist = sum((a - b) ** 2 for a, b in zip(test_point, point)) ** 0.5
distances.append((dist, label))
distances.sort(key=lambda x: x[0])
nearest = [label for _, label in distances[:k]]
return max(set(nearest), key=nearest.count)
# Simple decision tree
class DecisionNode:
def __init__(self, feature=None, threshold=None, left=None, right=None, value=None):
self.feature = feature
self.threshold = threshold
self.left = left
self.right = right
self.value = value
# K-means clustering
def k_means(data, k, max_iters=100):
# Initialize centroids randomly
centroids = data[:k]
for _ in range(max_iters):
# Assign points to nearest centroid
clusters = [[] for _ in range(k)]
for point in data:
distances = [sum((a - b) ** 2 for a, b in zip(point, centroid)) ** 0.5 for centroid in centroids]
closest = distances.index(min(distances))
clusters[closest].append(point)
# Update centroids
new_centroids = []
for cluster in clusters:
if cluster:
new_centroids.append([sum(dim) / len(cluster) for dim in zip(*cluster)])
else:
new_centroids.append(centroids[clusters.index(cluster)])
centroids = new_centroids
return clusters, centroids
# Simple neural network
import random
class SimpleNeuralNetwork:
def __init__(self, input_size, hidden_size, output_size):
# Initialize weights randomly
self.weights1 = [[random.uniform(-1, 1) for _ in range(input_size)] for _ in range(hidden_size)]
self.weights2 = [[random.uniform(-1, 1) for _ in range(hidden_size)] for _ in range(output_size)]
self.bias1 = [random.uniform(-1, 1) for _ in range(hidden_size)]
self.bias2 = [random.uniform(-1, 1) for _ in range(output_size)]
def sigmoid(self, x):
return 1 / (1 + 2.71828 ** (-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def forward(self, inputs):
# Hidden layer
hidden = []
for i in range(len(self.weights1)):
hidden_sum = sum(inputs[j] * self.weights1[i][j] for j in range(len(inputs))) + self.bias1[i]
hidden.append(self.sigmoid(hidden_sum))
# Output layer
output = []
for i in range(len(self.weights2)):
output_sum = sum(hidden[j] * self.weights2[i][j] for j in range(len(hidden))) + self.bias2[i]
output.append(self.sigmoid(output_sum))
return output
Challenge: Build a Simple ML Model
Combine all the concepts to build a simple machine learning model:
- Generate or load a dataset
- Preprocess the data (cleaning, normalization)
- Split the data into training and testing sets
- Implement a simple algorithm (e.g., linear regression)
- Train the model on the training data
- Test the model on the testing data
- Evaluate the model's performance
import random
def generate_dataset(n_samples):
X = [random.uniform(0, 10) for _ in range(n_samples)]
y = [2 * x + 1 + random.uniform(-1, 1) for x in X]
return X, y
# Normalize data
def normalize(data):
min_val, max_val = min(data), max(data)
return [(x - min_val) / (max_val - min_val) for x in data]
# Split data
def train_test_split(X, y, test_size=0.2):
indices = list(range(len(X)))
random.shuffle(indices)
split_idx = int(len(X) * (1 - test_size))
train_indices = indices[:split_idx]
test_indices = indices[split_idx:]
X_train = [X[i] for i in train_indices]
y_train = [y[i] for i in train_indices]
X_test = [X[i] for i in test_indices]
y_test = [y[i] for i in test_indices]
return X_train, X_test, y_train, y_test
# Train model
X, y = generate_dataset(100)
X_norm = normalize(X)
y_norm = normalize(y)
X_train, X_test, y_train, y_test = train_test_split(X_norm, y_norm)
model = linear_regression(X_train, y_train)
# Test model
predictions = [model(x) for x in X_test]
# Evaluate model
def mse(y_true, y_pred):
return sum((yt - yp) ** 2 for yt, yp in zip(y_true, y_pred)) / len(y_true)
error = mse(y_test, predictions)
print(f"Model MSE: {error:.4f}")
Ready to run.