Exercise 9.1: Sum of Two Numbers
Description : Write a program that takes two numbers as input from the user and calculates their sum.
Syllabus Coverage : Problem-solving process (understanding the problem, defining inputs and outputs, implementation).
Aim : Introduce students to basic input/output operations and simple arithmetic computations in Python.
1 2 3 4 5 | # Python Code num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) sum_result = num1 + num2 print(f"The sum of {num1} and {num2} is {sum_result}") |
Exercise 9.2: Largest of Three Numbers
Description : Write a program that takes three numbers as input and determines the largest among them.
Syllabus Coverage : Control structures (selection using if-elif-else
).
Aim : Teach students how to use conditional statements to solve decision-making problems.
1 2 3 4 5 6 7 8 9 10 11 12 13 | # Python Code num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) num3 = float(input("Enter the third number: ")) if num1 >= num2 and num1 >= num3: largest = num1 elif num2 >= num1 and num2 >= num3: largest = num2 else: largest = num3 print(f"The largest number is {largest}") |
Exercise 9.3: Factorial of a Number
Description : Write a program that calculates the factorial of a given number using a loop.
Syllabus Coverage : Control structures (repetition using for
or while
loops).
Aim : Introduce students to iterative programming and mathematical computations.
1 2 3 4 5 6 7 8 9 10 11 12 | # Python Code num = int(input("Enter a number to calculate its factorial: ")) factorial = 1 if num < 0: print("Factorial is not defined for negative numbers.") elif num == 0: print("The factorial of 0 is 1.") else: for i in range(1, num + 1): factorial *= i print(f"The factorial of {num} is {factorial}") |
Exercise 9.4: Multiplication Table
Description : Write a program that generates the multiplication table of a given number up to 10.
Syllabus Coverage : Repetition control structure (for
loop).
Aim : Reinforce the concept of loops and formatting output.
1 2 3 4 5 6 | # Python Code num = int(input("Enter a number to generate its multiplication table: ")) print(f"Multiplication Table for {num}:") for i in range(1, 11): print(f"{num} x {i} = {num * i}") |
Exercise 9.5: Check if a Number is Prime
Description : Write a program that checks whether a given number is prime or not.
Syllabus Coverage : Nested control structures (loops and conditionals).
Aim : Teach students how to combine loops and conditionals to solve complex problems.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | # Python Code num = int(input("Enter a number to check if it's prime: ")) if num <= 1: print(f"{num} is not a prime number.") else: is_prime = True for i in range(2, int(num ** 0.5) + 1): if num % i == 0: is_prime = False break if is_prime: print(f"{num} is a prime number.") else: print(f"{num} is not a prime number.") |
Exercise 9.6: Simple Calculator
Description : Write a program that acts as a simple calculator. The user should input two numbers and an operator (+, -, *, /), and the program should perform the corresponding operation.
Syllabus Coverage : Modularization (using functions), selection control structures.
Aim : Introduce students to modular programming and function usage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | # Python Code def calculator(): num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) operator = input("Enter the operator (+, -, *, /): ") if operator == '+': result = num1 + num2 elif operator == '-': result = num1 - num2 elif operator == '*': result = num1 * num2 elif operator == '/': if num2 != 0: result = num1 / num2 else: return "Division by zero is not allowed." else: return "Invalid operator." return f"The result is {result}" print(calculator()) |
Exercise 9.7: Fibonacci Series
Description : Write a program that generates the Fibonacci series up to a given number of terms.
Syllabus Coverage : Repetition control structure (for
loop), sequence generation.
Aim : Teach students how to generate sequences using loops and lists.
1 2 3 4 5 6 7 8 9 | # Python Code n = int(input("Enter the number of terms for the Fibonacci series: ")) fibonacci_series = [0, 1] for i in range(2, n): next_term = fibonacci_series[-1] + fibonacci_series[-2] fibonacci_series.append(next_term) print(f"Fibonacci series up to {n} terms: {fibonacci_series}") |
Exercise 9.8: Search for a Number in a List
Description : Write a program that searches for a given number in a list using sequential search.
Syllabus Coverage : Searching techniques (sequential search).
Aim : Introduce students to searching algorithms and their implementation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # Python Code numbers = [10, 20, 30, 40, 50] search_num = int(input("Enter the number to search: ")) found = False for num in numbers: if num == search_num: found = True break if found: print(f"{search_num} is found in the list.") else: print(f"{search_num} is not found in the list.") |
Exercise 9.9: Bubble Sort
Description : Write a program that sorts a list of numbers using the bubble sort algorithm.
Syllabus Coverage : Sorting techniques (bubble sort).
Aim : Teach students how to implement sorting algorithms.
1 2 3 4 5 6 7 8 9 | # Python Code numbers = [64, 34, 25, 12, 22, 11, 90] for i in range(len(numbers)): for j in range(0, len(numbers) - i - 1): if numbers[j] > numbers[j + 1]: numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j] print(f"Sorted list: {numbers}") |
Exercise 9.10: File Handling – Reading and Writing
Description : Write a program that reads data from a file, modifies it, and writes it back to another file.
Syllabus Coverage : File handling (basic file operations).
Aim : Introduce students to file input/output operations in Python.
1 2 3 4 5 6 7 8 9 10 11 | # Python Code # Create a file named 'input.txt' with some text before running this program with open('input.txt', 'r') as file: content = file.read() modified_content = content.upper() # Convert text to uppercase with open('output.txt', 'w') as file: file.write(modified_content) print("File processing complete. Check 'output.txt'.") |
Exercise 9.11: File Handling – Reading and Writing
Description : Write a program that reads data from a file, modifies it, and writes it back to another file.
Syllabus Coverage : File handling (basic file operations).
Aim : Introduce students to file input/output operations in Python.
1 2 3 4 5 6 7 8 9 10 11 | # Python Code # Create a file named 'input.txt' with some text before running this program with open('input.txt', 'r') as file: content = file.read() modified_content = content.upper() # Convert text to uppercase with open('output.txt', 'w') as file: file.write(modified_content) print("File processing complete. Check 'output.txt'.") |
Exercise 9.12: Managing Data in Databases
Description : Write a program that connects to a SQLite database, creates a table, inserts data, retrieves data, and updates or deletes records.
Syllabus Coverage : Managing data in databases (connecting, retrieving, adding, modifying, and deleting data).
Aim : Teach students how to interact with databases using SQL queries embedded in Python.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | # Python Code import sqlite3 # Connect to a database (or create it) conn = sqlite3.connect('example.db') cursor = conn.cursor() # Create a table cursor.execute(''' CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER ) ''') # Insert data cursor.execute("INSERT INTO students (name, age) VALUES ('Alice', 20)") cursor.execute("INSERT INTO students (name, age) VALUES ('Bob', 22)") # Retrieve data cursor.execute("SELECT * FROM students") rows = cursor.fetchall() print("Data in the table:") for row in rows: print(row) # Update data cursor.execute("UPDATE students SET age = 21 WHERE name = 'Alice'") # Delete data cursor.execute("DELETE FROM students WHERE name = 'Bob'") # Commit changes and close connection conn.commit() conn.close() print("Database operations completed.") |
Exercise 9.13: Sequential Search
Description : Write a program that searches for a given number in a list using sequential search.
Syllabus Coverage : Searching techniques (sequential search).
Aim : Introduce students to searching algorithms and their implementation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # Python Code numbers = [10, 20, 30, 40, 50] search_num = int(input("Enter the number to search: ")) found = False for num in numbers: if num == search_num: found = True break if found: print(f"{search_num} is found in the list.") else: print(f"{search_num} is not found in the list.") |
Exercise 9.14: Bubble Sort
Description : Write a program that sorts a list of numbers using the bubble sort algorithm.
Syllabus Coverage : Sorting techniques (bubble sort).
Aim : Teach students how to implement sorting algorithms.
1 2 3 4 5 6 7 8 9 | # Python Code numbers = [64, 34, 25, 12, 22, 11, 90] for i in range(len(numbers)): for j in range(0, len(numbers) - i - 1): if numbers[j] > numbers[j + 1]: numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j] print(f"Sorted list: {numbers}") |
Exercise 9.15: Working with Strings
Description : Write a program that takes a string as input and performs the following operations:
- Convert the string to uppercase.
- Count the number of vowels in the string.
- Reverse the string.
Syllabus Coverage : Primitive data types (strings), operators, and basic string manipulation.
Aim : Introduce students to string handling and manipulation techniques in Python.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | # Python Code string = input("Enter a string: ") # Convert to uppercase uppercase_string = string.upper() # Count vowels vowels = "aeiouAEIOU" vowel_count = sum(1 for char in string if char in vowels) # Reverse the string reversed_string = string[::-1] print(f"Uppercase: {uppercase_string}") print(f"Number of vowels: {vowel_count}") print(f"Reversed string: {reversed_string}") |
Exercise 9.16: Using Lists
Description : Write a program that creates a list of numbers, finds the largest and smallest numbers, and calculates the average.
Syllabus Coverage : Data structures (lists).
Aim : Teach students how to work with lists and perform common operations like finding min, max, and average.
1 2 3 4 5 6 7 8 9 10 11 12 13 | # Python Code numbers = [10, 20, 30, 40, 50] # Find largest and smallest numbers largest = max(numbers) smallest = min(numbers) # Calculate average average = sum(numbers) / len(numbers) print(f"Largest number: {largest}") print(f"Smallest number: {smallest}") print(f"Average: {average}") |
Exercise 9.17: Using Tuples
Description : Write a program that creates a tuple of student names and prints the names in alphabetical order.
Syllabus Coverage : Data structures (tuples).
Aim : Introduce students to tuples and their immutability.
1 2 3 4 5 6 7 8 9 | # Python Code students = ("Alice", "Bob", "Charlie", "David") # Sort the tuple sorted_students = sorted(students) print("Student names in alphabetical order:") for name in sorted_students: print(name) |
Exercise 9.18: Using Dictionaries
Description : Write a program that uses a dictionary to store student names and their marks. The program should allow the user to add new students and display all students with their marks.
Syllabus Coverage : Data structures (dictionaries).
Aim : Teach students how to use dictionaries to store and retrieve key-value pairs.
1 2 3 4 5 6 7 8 9 10 11 12 | # Python Code students = {} # Add students students["Alice"] = 85 students["Bob"] = 90 students["Charlie"] = 78 # Display all students print("Student Marks:") for name, marks in students.items(): print(f"{name}: {marks}") |
Exercise 9.19: Writing Functions
Description : Write a program that defines a function to calculate the area of a circle. The user should input the radius, and the function should return the area.
Syllabus Coverage : Sub-programs (functions).
Aim : Introduce students to writing reusable functions.
1 2 3 4 5 6 7 8 9 | # Python Code import math def calculate_area(radius): return math.pi * radius ** 2 radius = float(input("Enter the radius of the circle: ")) area = calculate_area(radius) print(f"The area of the circle is {area:.2f}") |
Exercise 9.20: Nested Loops
Description : Write a program that prints a multiplication table from 1 to 10 using nested loops.
Syllabus Coverage : Control structures (nested loops).
Aim : Teach students how to use nested loops for complex tasks.
1 2 3 4 5 6 | # Python Code print("Multiplication Table:") for i in range(1, 11): for j in range(1, 11): print(f"{i} x {j} = {i * j}") print() # Print a blank line after each row |
Exercise 9.21: Exception Handling
Description : Write a program that asks the user to input two numbers and divides them. Handle the case where the user tries to divide by zero.
Syllabus Coverage : Error handling.
Aim : Introduce students to exception handling in Python.
1 2 3 4 5 6 7 8 9 10 | # Python Code try: num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) result = num1 / num2 print(f"The result of {num1} / {num2} is {result}") except ZeroDivisionError: print("Error: Division by zero is not allowed.") except ValueError: print("Error: Please enter valid numbers.") |
Exercise 9.22: File Reading and Writing
Description : Write a program that reads a text file, counts the number of words, and writes the word count to another file.
Syllabus Coverage : File handling (reading and writing).
Aim : Teach students how to read from and write to files.
1 2 3 4 5 6 7 8 9 10 11 | # Python Code # Create a file named 'input.txt' with some text before running this program with open('input.txt', 'r') as file: content = file.read() word_count = len(content.split()) with open('output.txt', 'w') as file: file.write(f"Word count: {word_count}") print("Word count written to 'output.txt'.") |
Exercise 9.23: Connecting to a Database
Description : Write a program that connects to a SQLite database, creates a table, inserts data, and retrieves it.
Syllabus Coverage : Managing data in databases.
Aim : Introduce students to database connectivity using Python.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | # Python Code import sqlite3 # Connect to a database (or create it) conn = sqlite3.connect('example.db') cursor = conn.cursor() # Create a table cursor.execute(''' CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER ) ''') # Insert data cursor.execute("INSERT INTO students (name, age) VALUES ('Alice', 20)") cursor.execute("INSERT INTO students (name, age) VALUES ('Bob', 22)") # Retrieve data cursor.execute("SELECT * FROM students") rows = cursor.fetchall() print("Data in the table:") for row in rows: print(row) # Commit changes and close connection conn.commit() conn.close() |
Exercise 9.24: Sequential Search
Description : Write a program that searches for a given number in a list using sequential search.
Syllabus Coverage : Searching techniques (sequential search).
Aim : Introduce students to searching algorithms.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # Python Code numbers = [10, 20, 30, 40, 50] search_num = int(input("Enter the number to search: ")) found = False for num in numbers: if num == search_num: found = True break if found: print(f"{search_num} is found in the list.") else: print(f"{search_num} is not found in the list.") |
Exercise 9.25: Bubble Sort
Description : Write a program that sorts a list of numbers using the bubble sort algorithm.
Syllabus Coverage : Sorting techniques (bubble sort).
Aim : Teach students how to implement sorting algorithms.
1 2 3 4 5 6 7 8 9 | # Python Code numbers = [64, 34, 25, 12, 22, 11, 90] for i in range(len(numbers)): for j in range(0, len(numbers) - i - 1): if numbers[j] > numbers[j + 1]: numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j] print(f"Sorted list: {numbers}") |
Below are additional Python exercises that align with the syllabus and provide practical, hands-on coding experience. These exercises focus on key concepts such as file handling , database connectivity , data structures , functions , and algorithms . Each exercise includes a description, syllabus coverage, aim, and Python code
Exercise 9.26: Working with Files
Description : Write a program that reads a text file line by line and counts the number of lines, words, and characters in the file.
Syllabus Coverage : File handling (basic file operations).
Aim : Teach students how to process files and extract useful information.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | # Python Code filename = input("Enter the filename: ") try: with open(filename, 'r') as file: lines = file.readlines() num_lines = len(lines) num_words = sum(len(line.split()) for line in lines) num_chars = sum(len(line) for line in lines) print(f"Number of lines: {num_lines}") print(f"Number of words: {num_words}") print(f"Number of characters: {num_chars}") except FileNotFoundError: print(f"Error: The file '{filename}' was not found.") |
Exercise 9.27: Using Dictionaries for Frequency Count
Description : Write a program that reads a text file and calculates the frequency of each word in the file using a dictionary.
Syllabus Coverage : Data structures (dictionaries).
Aim : Introduce students to dictionaries for counting and organizing data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | # Python Code filename = input("Enter the filename: ") try: with open(filename, 'r') as file: text = file.read().lower() # Convert text to lowercase words = text.split() word_count = {} for word in words: word = word.strip('.,!?()[]{}"\'') # Remove punctuation if word: word_count[word] = word_count.get(word, 0) + 1 print("Word Frequencies:") for word, count in word_count.items(): print(f"{word}: {count}") except FileNotFoundError: print(f"Error: The file '{filename}' was not found.") |
Exercise 9.28: Recursive Functions
Description : Write a program that calculates the factorial of a number using recursion.
Syllabus Coverage : Sub-programs (functions), recursion.
Aim : Teach students how to write recursive functions.
1 2 3 4 5 6 7 8 9 10 11 | # Python Code def factorial(n): if n == 0 or n == 1: return 1 return n * factorial(n - 1) num = int(input("Enter a number to calculate its factorial: ")) if num < 0: print("Factorial is not defined for negative numbers.") else: print(f"The factorial of {num} is {factorial(num)}") |
Exercise 9.29: Sorting a List of Dictionaries
Description : Write a program that sorts a list of dictionaries based on a specific key.
Syllabus Coverage : Data structures (lists, dictionaries), sorting techniques.
Aim : Introduce students to sorting complex data structures.
1 2 3 4 5 6 7 8 9 10 11 12 13 | # Python Code students = [ {"name": "Alice", "age": 25}, {"name": "Bob", "age": 22}, {"name": "Charlie", "age": 28} ] # Sort by age sorted_students = sorted(students, key=lambda x: x["age"]) print("Students sorted by age:") for student in sorted_students: print(student) |
Exercise 9.30: Connecting to a Database and Querying Data
Description : Write a program that connects to a SQLite database, creates a table, inserts data, and retrieves it using SQL queries.
Syllabus Coverage : Managing data in databases.
Aim : Reinforce students’ understanding of database connectivity and SQL queries.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | # Python Code import sqlite3 # Connect to a database (or create it) conn = sqlite3.connect('school.db') cursor = conn.cursor() # Create a table cursor.execute(''' CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, grade TEXT ) ''') # Insert data cursor.execute("INSERT INTO students (name, grade) VALUES ('Alice', 'A')") cursor.execute("INSERT INTO students (name, grade) VALUES ('Bob', 'B')") # Retrieve data cursor.execute("SELECT * FROM students WHERE grade = 'A'") rows = cursor.fetchall() print("Students with grade A:") for row in rows: print(row) # Commit changes and close connection conn.commit() conn.close() |
Exercise 9.31: Binary Search Algorithm
Description : Write a program that implements the binary search algorithm to find a target value in a sorted list.
Syllabus Coverage : Searching techniques (binary search).
Aim : Teach students an efficient searching algorithm.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | # Python Code def binary_search(arr, target): low, high = 0, len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: return mid elif arr[mid] < target: low = mid + 1 else: high = mid - 1 return -1 numbers = [10, 20, 30, 40, 50] target = int(input("Enter the number to search: ")) index = binary_search(numbers, target) if index != -1: print(f"{target} found at index {index}.") else: print(f"{target} not found in the list.") |
Exercise 9.32: Handling JSON Data
Description : Write a program that reads a JSON file, modifies its contents, and writes the updated data back to the file.
Syllabus Coverage : File handling (JSON).
Aim : Introduce students to working with JSON data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | # Python Code import json # Sample JSON file content: {"name": "Alice", "age": 25} filename = 'data.json' # Read JSON file with open(filename, 'r') as file: data = json.load(file) # Modify data data['age'] += 1 # Write updated data back to JSON file with open(filename, 'w') as file: json.dump(data, file, indent=4) print("Data updated successfully.") |
Exercise 9.33: Generating Random Numbers
Description : Write a program that generates a list of random numbers and finds the largest and smallest numbers.
Syllabus Coverage : Primitive data types, control structures.
Aim : Teach students how to use the random
module and perform basic operations.
1 2 3 4 5 6 7 8 9 10 11 12 | # Python Code import random # Generate a list of 10 random numbers between 1 and 100 numbers = [random.randint(1, 100) for _ in range(10)] largest = max(numbers) smallest = min(numbers) print(f"Generated numbers: {numbers}") print(f"Largest number: {largest}") print(f"Smallest number: {smallest}") |
Exercise 9.34: Simulating a Simple Banking System
Description : Write a program that simulates a simple banking system where users can deposit, withdraw, and check their balance.
Syllabus Coverage : Control structures, functions, data structures.
Aim : Provide a real-world application of Python programming concepts.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | # Python Code def deposit(balance, amount): return balance + amount def withdraw(balance, amount): if amount > balance: print("Insufficient funds.") return balance return balance - amount def main(): balance = 0 while True: print("\n1. Deposit") print("2. Withdraw") print("3. Check Balance") print("4. Exit") choice = input("Enter your choice: ") if choice == '1': amount = float(input("Enter the amount to deposit: ")) balance = deposit(balance, amount) print(f"Deposited {amount}. New balance: {balance}") elif choice == '2': amount = float(input("Enter the amount to withdraw: ")) balance = withdraw(balance, amount) print(f"Withdrew {amount}. New balance: {balance}") elif choice == '3': print(f"Current balance: {balance}") elif choice == '4': print("Exiting...") break else: print("Invalid choice. Please try again.") main() |
Python is an incredibly versatile programming language that can be used for a wide range of applications beyond the scope of your syllabus. Below are some additional, advanced, or creative ideas that you can explore using Python, which go beyond the topics covered in your Grade 13 ICT syllabus. These ideas will help you deepen your understanding of Python and its real-world applications:
1. Web Scraping
What You Can Do : Extract data from websites for analysis or automation.
- Example Use Case : Scrape news articles, product prices, or social media posts.
- Libraries :
BeautifulSoup
,requests
,Selenium
. - Code Example :
1 2 3 4 5 6 7 8 9 10 11 | import requests from bs4 import BeautifulSoup url = "https://example.com" response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # Extract all headings headings = soup.find_all('h1') for heading in headings: print(heading.text) |
2. Data Analysis and Visualization
What You Can Do : Analyze datasets and create visualizations like graphs, charts, and heatmaps.
- Example Use Case : Analyze sales data, student performance, or weather patterns.
- Libraries :
pandas
,matplotlib
,seaborn
,plotly
. - Code Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 | import pandas as pd import matplotlib.pyplot as plt # Load data data = {'Months': ['Jan', 'Feb', 'Mar'], 'Sales': [200, 250, 300]} df = pd.DataFrame(data) # Plot plt.plot(df['Months'], df['Sales']) plt.title("Monthly Sales") plt.xlabel("Months") plt.ylabel("Sales") plt.show() |
3. Machine Learning
What You Can Do : Build predictive models for classification, regression, clustering, etc.
- Example Use Case : Predict house prices, classify emails as spam or not, or recommend products.
- Libraries :
scikit-learn
,tensorflow
,keras
. - Code Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 | from sklearn.linear_model import LinearRegression import numpy as np # Sample data X = np.array([[1], [2], [3], [4]]) # Features y = np.array([2, 4, 6, 8]) # Target # Train model model = LinearRegression() model.fit(X, y) # Predict print(model.predict(<button class="citation-flag" data-index="5">)) # Output: [10] |
4. Automation Scripts
What You Can Do : Automate repetitive tasks like file organization, email sending, or report generation.
- Example Use Case : Organize files into folders based on their extensions.
- Libraries :
os
,shutil
,smtplib
. - Code Example :
1 2 3 4 5 6 7 8 | import os import shutil # Organize files by extension folder_path = "/path/to/folder" for filename in os.listdir(folder_path): if filename.endswith(".txt"): shutil.move(os.path.join(folder_path, filename), "/path/to/txt_folder") |
5. Building APIs
What You Can Do : Create RESTful APIs to serve data or interact with applications.
- Example Use Case : Build an API to fetch weather data or user information.
- Libraries :
Flask
,FastAPI
. - Code Example :
1 2 3 4 5 6 7 8 9 10 | from flask import Flask, jsonify app = Flask(__name__) @app.route('/api/data', methods=['GET']) def get_data(): return jsonify({"message": "Hello, World!"}) if __name__ == '__main__': app.run(debug=True) |
6. Game Development
What You Can Do : Create simple games like Tic-Tac-Toe, Snake, or Pong.
- Example Use Case : Develop a text-based adventure game or a graphical game.
- Libraries :
pygame
. - Code Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import pygame pygame.init() # Screen setup screen = pygame.display.set_mode((400, 300)) pygame.display.set_caption("Simple Game") running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.fill((0, 0, 0)) # Black background pygame.display.flip() pygame.quit() |
7. Chatbots
What You Can Do : Build conversational agents for customer support or personal assistants.
- Example Use Case : Create a chatbot to answer FAQs or provide recommendations.
- Libraries :
nltk
,chatterbot
,transformers
. - Code Example :
1 2 3 4 5 6 7 8 9 10 11 | from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer # Create chatbot chatbot = ChatBot('MyBot') trainer = ChatterBotCorpusTrainer(chatbot) trainer.train("chatterbot.corpus.english") # Interact response = chatbot.get_response("Hello") print(response) # Output: Hi there! |
8. Image Processing
What You Can Do : Manipulate images (resize, crop, apply filters) or perform object detection.
- Example Use Case : Build a face detection system or watermark images.
- Libraries :
Pillow
,opencv-python
. - Code Example :
1 2 3 4 5 6 7 8 | from PIL import Image, ImageFilter # Open image image = Image.open("example.jpg") # Apply blur blurred_image = image.filter(ImageFilter.BLUR) blurred_image.save("blurred_example.jpg") |
9. Natural Language Processing (NLP)
What You Can Do : Process and analyze text data (sentiment analysis, summarization).
- Example Use Case : Analyze customer reviews or summarize long documents.
- Libraries :
nltk
,spaCy
,transformers
. - Code Example :
1 2 3 4 5 6 7 | from textblob import TextBlob text = "I love this product! It's amazing." blob = TextBlob(text) # Sentiment analysis print(blob.sentiment) # Output: Sentiment(polarity=0.5, subjectivity=0.6) |
10. IoT Integration
What You Can Do : Control IoT devices (lights, fans, sensors) using Python.
- Example Use Case : Build a smart home system or monitor environmental data.
- Libraries :
RPi.GPIO
(for Raspberry Pi),pyserial
. - Code Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) try: while True: GPIO.output(18, GPIO.HIGH) # Turn LED on time.sleep(1) GPIO.output(18, GPIO.LOW) # Turn LED off time.sleep(1) except KeyboardInterrupt: GPIO.cleanup() |
11. Blockchain Basics
What You Can Do : Simulate a basic blockchain or cryptocurrency system.
- Example Use Case : Create a simple blockchain for educational purposes.
- Libraries :
hashlib
. - Code Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import hashlib import json class Block: def __init__(self, index, timestamp, data, previous_hash): self.index = index self.timestamp = timestamp self.data = data self.previous_hash = previous_hash self.hash = self.calculate_hash() def calculate_hash(self): block_string = json.dumps(self.__dict__, sort_keys=True).encode() return hashlib.sha256(block_string).hexdigest() # Create genesis block genesis_block = Block(0, "01/01/2023", "Genesis Block", "0") print(genesis_block.hash) |
12. GUI Applications
What You Can Do : Build desktop applications with graphical user interfaces.
- Example Use Case : Create a calculator, to-do list, or file manager.
- Libraries :
tkinter
,PyQt
,Kivy
. - Code Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import tkinter as tk def greet(): label.config(text="Hello, World!") # Create window window = tk.Tk() window.title("Simple GUI") # Add widgets button = tk.Button(window, text="Click Me", command=greet) button.pack() label = tk.Label(window, text="") label.pack() window.mainloop() |
13. Networking
What You Can Do : Build networked applications like chat servers or file transfer systems.
- Example Use Case : Create a simple chat server and client.
- Libraries :
socket
. - Code Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import socket # Server server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(('localhost', 12345)) server_socket.listen(1) print("Waiting for connection...") connection, address = server_socket.accept() print(f"Connected to {address}") data = connection.recv(1024) print(f"Received: {data.decode()}") connection.sendall(b"Message received") connection.close() |
14. Cryptography
What You Can Do : Encrypt and decrypt messages for secure communication.
- Example Use Case : Build a password manager or secure messaging app.
- Libraries :
cryptography
. - Code Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 | from cryptography.fernet import Fernet # Generate key key = Fernet.generate_key() cipher_suite = Fernet(key) # Encrypt message = b"Secret message" encrypted_message = cipher_suite.encrypt(message) # Decrypt decrypted_message = cipher_suite.decrypt(encrypted_message) print(decrypted_message.decode()) # Output: Secret message |