Compiled Practice Assignments
Table of Contents
- Intro to Python & Control Flow
- Loops & Logic
- Functions & Lists
- Dictionaries & Sets
- Object-Oriented Programming (OOP)
- Regular Expressions (Regex)
- Functional Programming
- APIs & HTTP Requests
- SQL & Database Design
- Flask & ORM (Intermediate/Advanced)
- File I/O & Configuration
- Decorators & Context Managers
- AsyncIO & Generators
- Frontend Development (HTML/CSS)
- JavaScript Fundamentals
- Web Interactivity & Frameworks
1. Intro to Python & Control Flow
Solution: Python_Basics/Control_Flow_Solutions.py
Task 1.1: Greeting
- Goal: Write a script that asks for a user’s name and age, then prints a greeting message like:
"Hello, [Name]! You are [Age] years old!"
Task 1.2: Century Age Calculator
- Goal: Calculate the year a person will turn 100.
- Logic:
century_year = current_year + (100 - current_age)
Task 1.3: Simple Conditional
- Goal: Write an if-else statement.
- Prompt: Ask for user input (e.g., “Is it raining?”). If yes, print “Take an umbrella”. If no, print “Enjoy the sun”.
Task 1.4: Comparison Operators Practice
- Goal: Check voting eligibility.
- Logic: If
age >= 18, print “Can vote”. Else, print “Cannot vote”.
Task 1.5: Complex Decisions (Grades)
- Goal: Convert numerical scores to letter grades.
- Logic:
- 90-100: A
- 80-89: B
- 70-79: C
- 60-69: D
- < 60: F
Task 1.6: Exception Handling
- Goal: Write a program that asks for an integer (age).
- Requirement: Use
try/exceptto handle cases where the user types text instead of a number.
2. Loops & Logic
Solution: Python_Basics/Control_Flow_Solutions.py
Task 2.1: Basic While Loop
- Goal: Create a loop that counts from 1 to 5 and prints each number.
Task 2.2: Countdown
- Goal: Create a loop that counts down from 5 to 1, then prints “Blast Off!”.
Task 2.3: Password Checker
- Goal: Create a
whileloop that repeatedly asks the user for a password until they type “secret”.
Task 2.4: Temperature Monitor
- Goal: Create a script that accepts temperature readings from the user until they type ‘done’.
- Output: Print the count of readings, the total, the average, the minimum, and the maximum.
3. Functions & Lists
Solution: Data_Structures/Lists_Dicts_Solutions.py
Task 3.1: Basic Functions
- Define:
greet(name)-> prints “Hello [name]” - Define:
rectangle_area(length, width)-> returns area. - Define:
add(num1, num2)-> returns sum.
Task 3.2: Temperature Converter
- Define:
celcius_to_farenheit(celcius)-> returns converted temp.
Task 3.3: List Statistics
- Goal: Write a function
list_statistics(numbers)that takes a list of numbers and returns a dictionary containing:max: Maximum valuemin: Minimum valueavg: Average valuesum: Sum of values
Task 3.4: List Operations
- Create a list of fruits.
- Add “strawberry” to the end.
- Remove “orange” by value.
- Remove the item at index 1.
- Check if “apple” is in the list.
4. Dictionaries & Sets
Solution: Data_Structures/Lists_Dicts_Solutions.py
Task 4.1: Student Scores
- Data: A dictionary of student names and scores.
- Subtasks:
- Loop through and print all names.
- Loop through and print all scores.
- Print “Name: Score” pairs.
- Use
.get()to safely check for a missing student.
Task 4.2: Inventory System
- Structure: Nested dictionary (Categories -> Items -> Details).
- Subtasks:
- Access and print specific item prices.
- Update stock levels.
- Add new items and categories.
- Calculate the total value of inventory.
Task 4.3: Cleaning Usernames
- Goal: Write a function
clean_usernames(raw_list)that takes a list of strings (some with whitespace/casing issues) and returns a clean list (lowercase, stripped).
Task 4.4: Set Operations
- Scenario: You have two lists of hobbies (e.g.,
wilson_hobbiesandfriend_hobbies). - Subtasks:
- Find common interests (Intersection).
- Find all unique hobbies combined (Union).
- Find hobbies unique to one person (Difference).
5. Object-Oriented Programming (OOP)
Solution: OOP/OOP_Solutions.py
Task 5.1: Student Class
- Attributes:
name,age,grades(list). - Methods:
add_grade(grade)grade_avg(): Returns average.info(): Prints student details.
Task 5.2: User Class (Encapsulation)
- Attributes:
username(public),_password(protected/private). - Methods:
set_password(new_pass): Validates length/characters before setting.get_password(): Returns the password (or a masked version).
Task 5.3: RPG Battle System (Inheritance/Polymorphism)
- Base Class:
Character(name, health, attack_power). - Subclasses:
Warrior(High health, standard attack).Mage(Lower health, high attack,special_attackmethod).EvilWizard(Boss character,regeneratemethod).
- Goal: Simulate a battle loop where characters attack each other until one falls.
6. Regular Expressions (Regex)
Solution: Regex/Regex_Solutions.py
Task 6.1: Basic Patterns
- Find the first word in a text (
\w). - Find a phone number (
\d{3}-\d{4}). - Find all 5-digit IDs (
\d{5}).
Task 6.2: Data Cleaning
- Input: Raw customer feedback with varying spacing and sensitive data.
- Subtasks:
- Remove phone numbers (Replace with “[REDACTED]”).
- Fix multiple spaces (Replace
\s+with" ").
7. Functional Programming
Solution: Functional/Functional_Solutions.py
Task 7.1: Sorting (Lambda)
- Input: List of product dictionaries (
{'name': 'A', 'price': 10}). - Goal: Sort by price (descending) using
sorted()and alambdakey.
Task 7.2: Map
- Input: List of employee dictionaries.
- Goal: Use
map()to create a new list where every employee gets a 7% raise.
Task 7.3: Filter
- Input: List of books (
{'title': 'A', 'rating': 4.5}). - Goal: Use
filter()to find books with a rating >= 4.0.
Task 7.4: List Comprehensions
- Goal: Write a one-liner that takes a list of numbers, keeps only the evens, and doubles them.
8. APIs & HTTP Requests
Solution: APIs/API_Solutions.py
Task 8.1: Basic Fetch
- Goal: Use
requeststo fetch a random dog image fromhttps://dog.ceo/api/breeds/image/randomand print the URL.
Task 8.2: PokeAPI Wrapper
- Goal: Write a function
get_pokemon_data(name)that:- Fetches data from
https://pokeapi.co/api/v2/pokemon/{name}. - Parses JSON to extract Name, ID, HP, and Type.
- Returns a dictionary (or
Noneon error).
- Fetches data from
Task 8.3: Spotify Token (Auth)
- Goal: Implement the Client Credentials Flow to get a Spotify Access Token.
- Steps:
- Base64 encode
client_id:client_secret. - POST to
https://accounts.spotify.com/api/token. - Extract
access_tokenfrom the response.
- Base64 encode
9. SQL & Database Design
Solution: SQL/SQL_Solutions.sql
Task 9.1: DDL (Creating Tables)
- Write SQL to create a
Studentstable (id, name, email) and aCoursestable (id, title, instructor).
Task 9.2: Basic Queries
- Write SQL to select all students named “Alice”.
- Write SQL to update a course title.
- Write SQL to delete a specific record.
10. Flask & ORM (Intermediate/Advanced)
Solution:
Task 10.1: Mechanic Shop API
- Context: Mechanics, Customers, Tickets.
- Subtasks:
- Customer Search: Endpoint to find customer by email (
GET /search?email=...). - Analytics: Endpoint to find the mechanic with the most completed tickets.
- Pagination: Paginate the
GET /ticketsendpoint.
- Customer Search: Endpoint to find customer by email (
Task 10.2: Library/Inventory Logic
- Goal: Implement “Item Definition” vs “Item Instance” pattern.
- Endpoints:
POST /catalog: Create a generic book title.POST /catalog/{id}/add: Add a physical copy of that book.
Task 10.3: Order Processing
- Goal: Implement a checkout flow.
- Flow: Create Order (Pending) -> Add Items -> Checkout (Complete).
Task 10.4: Pet Clinic Appointments
- Goal: Create a CLI or API function to schedule an appointment.
- Logic: Select Pet -> Select Vet -> Choose Date -> Commit to DB.
11. File I/O & Configuration
Solution: Python_Basics/File_Ops_Solutions.py
Task 11.1: Log Analyzer
- Goal: Create a script that reads a “server.log” file line-by-line.
- Action: Count how many lines contain “ERROR”.
- Output: Write a summary report to “log_report.txt”.
Task 11.2: JSON Config Loader
- Goal: Write a function to manage application configuration.
- Subtasks:
- Load
config.json(use defaults if missing). - Update a specific setting (e.g.,
theme: "dark"). - Save the changes back to the file.
- Load
12. Decorators & Context Managers
Solution: Advanced_Python/Decorators_Context_Solutions.py
Task 12.1: Execution Timer Decorator
- Goal: Create a
@timerdecorator. - Behavior: When wrapping a function, it should print “Function [name] took [x] seconds” after execution.
Task 12.2: Custom Context Manager
- Goal: Create a class
FileManagerthat behaves like the built-inopen(). - Requirement: It must print “Opening file…” when entering the
withblock and “Closing file…” when exiting.
13. AsyncIO & Generators
Solution: Advanced_Python/Async_Generators_Solutions.py
Task 13.1: Fibonacci Generator
- Goal: Write a generator function
fib(limit)that yields Fibonacci numbers one by one up to a specified count, rather than returning a list.
Task 13.2: Async API Simulation
- Goal: Create an async function
fetch_data(id)that waits for a random delay. - Action: Use
asyncio.gatherto run three fetches concurrently and print the results when all are done.
14. Frontend Development (HTML/CSS)
Solution: HTML_Profile_Solution.html, CSS_Card_Component_Solution.html, Flexbox_Navbar_Solution.html, Grid_Gallery_Solution.html
Resources: HTML Cheat Sheet, CSS Cheat Sheet, CSS Layout Guide
Task 14.1: Semantic HTML Profile
- Goal: Create a simple “About Me” page (
index.html). - Requirements:
- Use semantic tags:
<header>,<main>,<section>,<footer>. - Include a profile image (
<img>), a bio paragraph (<p>), and a list of hobbies (<ul>).
- Use semantic tags:
Task 14.2: The “Card” Component
- Goal: Style a
<div>to look like a UI card. - CSS Requirements:
- Add
padding,border, and a slightbox-shadow. - Ensure the image inside fits the card width (
max-width: 100%).
- Add
Task 14.3: Flexbox Navbar
- Goal: Create a navigation bar.
- Structure: A container with a logo on the left and links on the right.
- CSS: Use
display: flexandjustify-content: space-between.
Task 14.4: CSS Grid Gallery
- Goal: Create a responsive photo gallery.
- CSS: Use
display: grid,grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)), andgap.
15. JavaScript Fundamentals
Solution: JavaScript_Basics_and_Functions_Solutions.js, JavaScript_Array_Manipulation_Solutions.js, JavaScript_Object_Access_Solutions.js
Resources: JS Basics Cheat Sheet, JS Functions Guide
Task 15.1: Hello World & Variables
- Goal: Create a script (
script.js) that logs “Hello, World!” to the console. - Subtasks:
- Declare a variable
nameusingletand assign it your name. - Use a template literal to log “Hello, [name]!”.
- Run it using
node script.js(if Node is installed) or attach it to an HTML file.
- Declare a variable
Task 15.2: Simple Calculator
- Goal: Write a function
calculate(num1, num2, operation). - Logic:
- If operation is “+”, return sum.
- If “-“, return difference.
- Use a
switchstatement. - Bonus: Convert it to an arrow function.
Task 15.3: Array Manipulation
- Goal: Practice array methods.
- Data:
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - Subtasks:
- Filter out odd numbers (keep only evens).
- Map the remaining numbers to their squares.
- Log the final array.
Task 15.4: Object Access
- Goal: Working with Objects.
- Data:
const car = { make: "Toyota", model: "Corolla", year: 2020, features: ["AC", "Radio", "Bluetooth"] }; - Action:
- Log the
makeandmodelcombined. - Loop through
featuresand log each one. - Add a new property
mileagewith value 50000.
- Log the
16. Web Interactivity & Frameworks
Resources: Bootstrap Cheat Sheet, DOM Manipulation Guide, CSS Cheat Sheet
Task 16.1: Bootstrap Grid & Layout
- Goal: Create a responsive landing page using Bootstrap.
- Requirements:
- Include the Bootstrap CDN in your
<head>. - Create a
navbar. - Create a hero section with a centered
h1andbutton. - Create a 3-column feature section using
.rowand.col-md-4.
- Include the Bootstrap CDN in your
Task 16.2: Color Picker (DOM Events)
- Goal: Build an interactive color switcher.
- UI: A set of
divs with different colors and a large “Canvas”div. - Logic:
- Select all color swatches using
document.querySelectorAll. - Loop through them and add a
clickevent listener. - When clicked, change the background color of the “Canvas” to match the clicked swatch.
- Select all color swatches using
Task 16.3: Local Storage Form
- Goal: Persist user data across page reloads.
- UI: A form with “Username” and “Theme Preference” (Light/Dark).
- Logic:
- Listen for the
submitevent. - Save the values to
localStorage(e.g.,localStorage.setItem('user', ...)). - On page load (
DOMContentLoaded), checklocalStorage. If data exists, pre-fill the form.
- Listen for the
Task 16.4: Advanced CSS Pseudo-Elements
- Goal: Style a button with a “shine” effect or an underline animation.
- CSS:
- Use
::beforeor::afterto create a decorative element. - Use
:hoverto trigger atransformortransition. - Try styling
::first-letterof a paragraph to look like a drop cap.
- Use