Introduction to Python Programming
Introduction to Python Programming
In this course, you’ll go from writing your first line of code to building cool projects that’ll make you say,
‘Wow, I did that! 😎’
Whether you’re totally new to coding or just looking to sharpen your Python skills, get ready for an epic
journey filled with coding magic, challenges, and lots of fun moments.
There are several reasons why Python is a great choice for many different types of projects:
1. Easy to learn: Python has a relatively simple syntax, which makes it easier for beginners to learn
compared to other programming languages.
2. Versatile: Python can be used for a wide range of applications, including web development, data
analysis, artificial intelligence, and more.
3. Large and active community: There is a large and active community of Python developers, which
means that there are many resources available for learning and solving problems.
4. Plenty of libraries: Python has a large number of libraries, including NumPy, pandas, and Matplotlib,
which can be used to perform complex tasks with just a few lines of code.
5. Cross-platform compatibility: Python can run on multiple operating systems, including Windows,
macOS, and Linux, making it a good choice for projects that need to be run on multiple platforms.
Install Python
If you don't want to use Thonny, here's how to install and run Python on your computer.
number = 10
In the above example, we assigned the value ‘Power Learn Project’ to the site_name variable. Then, we
printed out the value assigned to site_name.
Note: Python is a type-inferred language, so you don't have to explicitly define the variable type. It
automatically knows that Power Learn Projects is a string and declares the site_name variable as a string.
Here, the value of site_name is changed from ‘Power Learn Project’ to 'I love coding 😊'.
print(a) # prints 5
print(b) # prints 5
print(c) # prints Hello World
snake_case
MACRO_CASE
camelCase
CapsWords
Python is case-sensitive. So num and Num are different variables. For example,
num = 55
Num = 510
print(num) #5
print(Num) #510
Avoid using keywords like if, True, class, etc. as variable names.
More Resources:
1. [Link]
2. [Link]
3. [Link]
4. [Link]
Understanding Python Datatypes
[Link]
In computer programming, data types specify the type of data that can be stored inside a variable. For example,
num = 24
Here, 24 (an integer) is assigned to the num variable. So the data type of num is of the int class.
Since everything is an object in Python programming, data types are actually classes and variables are
instances(object) of these classes.
Integers, floating-point numbers and complex numbers fall under Python numbers category. They are defined as
int, float and complex classes in Python.
We can use the type() function to know which class a variable or a value belongs to.
num1 = 55
num2 = 5.3
print(num1)
print(num2)
Here, we have created a list named languages with 3 string values inside it.
In the above example, we have used the index values to access items from the languages list.
Here, product is a tuple with a string value Xbox and integer value 499.99.
In the above example, we have created string-type variables: name and message with values 'Python' and
'Python for beginners' respectively.
Since sets are unordered collections, indexing has no meaning. Hence, the slicing operator [] does not work.
Here, keys are unique identifiers that are associated with each value.
More Resources:
1. [Link]
2. [Link]
3. [Link]
4. [Link]
[Link]
1. Arithmetic operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Special Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc.
For example,
sub = 10 - 5 # 5
+ addition 5 + 2 = 7
- subtraction 4 - 2 = 2
* multiplication 2 * 3 = 6
** exponentiation ( power) 4 ** 2 = 16
/ float division 4 / 2 = 2
// floor division 10 // 3 = 3
% modulus (remainder) 5 % 2 = 1
+ to add a and b
- to subtract b from a
* to multiply a and b
/ to divide a by b
// to floor divide a by b
% to get the remainder
** to get a to the power b
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x–3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
^= x ^= 3 x=x^3
x=3
:= print(x := 3)
print(x)
Similarly, we can use any other assignment operators according to the need.
Comparison operators compare two values/variables and return a boolean result: True or False. For example
Here, the > comparison operator is used to compare whether a is greater than b or not.
== Equal 2 == 2
!= Not equal 4 != 2
Note: Comparison operators are used in decision-making and loops. We'll discuss more of the comparison
operator and decision-making in later tutorials.
Logical operators are used to check whether an expression is True or False. They are used in decision-making.
For example,
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
More Resources:
1. [Link]
2. [Link]
3. [Link]
Here are some fun and beginner-friendly project ideas you can try at this stage:
Create a program that asks for the user’s name and favorite color, then prints a personalized greeting
like: “Hello, [Name]! Your favorite color, [Color], is awesome!”
Create a multiple-choice quiz with questions about Python, movies, or any fun topic! Display scores at the end
and allow the user to play again. 🏆
Build a program that stores a list of jokes and randomly selects one to display every time the user runs it. Add a
fun twist with jokes about Python or programming! 🐍💡
Session 1
Session 2
Session 3
WEEK-2 Python Built in Data Structures
So far, you have only stored small bits of data in a variable. This was either an integer, Boolean or a string.
But what happens if you need to work with more complex information, such as a collection of data like a list of
people or a list of companies? Data structures are designed for this very purpose.
A data structure allows you to organize and arrange your data to perform operations on them. Python has the
following built-in data structures: List, dictionary, tuple and set. These are all considered non-primitive data
structures, meaning they are classed as objects, we will explore this more.
Along with the built-in data structures, Python allows users to create their own. Data structures such as Stacks,
Queues and Trees can all be created by the user.
Each data structure can be designed to solve a particular problem or optimize a current solution to make it much
more performant.
Mutability refers to data inside the data structure that can be modified. For example, you can either change,
update, or delete the data when needed. A list is an example of a mutable data structure.
An immutable data structure will not allow modification once the data has been set. The tuple is an example of
an immutable data structure.
n Python, lists are used to store multiple data at once. For example,
Suppose we need to record the ages of 5 students. Instead of creating 5 separate variables, we can simply create
a list:
Lists Elements
A list is created in Python by placing items inside [], separated by commas. For example,
A list can have any number of items and they may be of different types (integer, float, string, etc.). For example,
Access Python List Elements
In Python, each item in a list is associated with a number. The number is known as a list index.
We can access elements of an array using the index number (0, 1, 2 …). For example,
Note: The list index always starts with 0. Hence, the first element of a list is present at index 0, not 1.
Here,
Note: When we slice lists, the start index is inclusive but the end index is exclusive.
1. Using append()
The append() method adds an item at the end of the list.
For example,
2. Using extend()
We use the extend() method to add all items of one list to another. For example,
In the above example, we have two lists named prime_numbers and even_numbers. Notice the statement,
In Python, we can use the del statement to remove one or more items from a list. For example,
2. Using remove()
For example:
A list comprehension consists of an expression followed by the for statement inside square brackets.
Here is an example to make a list with each item being increasing by power of 2.
In the above example, we have used the list comprehension to make a list with each item being increased by
power of 2. Notice the code,
Tuples
A tuple in Python is similar to a list. The difference between the two is that we cannot change the elements of a
tuple once it is assigned whereas we can change the elements of a list.
Creating a Tuple
[Link]
A tuple is created by placing all the items (elements) inside parentheses (), separated by commas. The
parentheses are optional, however, it is a good practice to use them.
A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).
We can use the type() function to know which class a variable or a value belongs to.
Here,
("hello") is a string so type() returns str as class of var1 i.e. <class 'str'>
("hello",) and "hello", both are tuples so type() returns tuple as class of var1 i.e. <class 'tuple'>
We can use the index operator [] to access an item in a tuple, where the index starts from 0.
So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside of the tuple index
range( 6,7,... in this example) will raise an IndexError.
The index must be an integer, so we cannot use float or other types. This will result in TypeError.
Likewise, nested tuples are accessed using nested indexing, as shown in the example below.
2. Negative Indexing
The index of -1 refers to the last item, -2 to the second last item and so on. For example,
In the above example,
Here,
1. [Link]
2. [Link]
3. [Link]
4. [Link]
Dictionaries
Python dictionary is an ordered collection (starting from Python 3.7) of items. It stores elements in key/value
pairs. Here, keys are unique identifiers that are associated with each value.
[Link]
If we want to store information about countries and their capitals, we can create a dictionary with country
names as keys and capitals as values.
Note: Here, keys and values both are of string type. We can also have keys and values of different data types.
In the above example, we have created a dictionary named numbers. Here, keys are of integer type and values
are of string type.
For example,
In the above example, we have created a dictionary named capital_city. Notice the line,
Here, we have added a new element to capital_city with key: Japan and value: Tokyo.
Here, we have changed the value associated with the key 112 to "Stan".
If we try to access the value of a key that doesn't exist, we'll get an error.
For example,
The del statement removes the element associated with the key 111. We can also delete the whole dictionary
using the del statement,
We are getting an error message because we have deleted the student_id dictionary and student_id doesn't exist
anymore.
More Resources:
1. [Link]
2. [Link]
Set
A set is a collection of unique data. That is, elements of a set cannot be duplicated.
For example,
Suppose we want to store information about student IDs. Since student IDs cannot be duplicated, we can use a
set.
In Python, we create sets by placing all the elements inside curly braces {}, separated by comma.
A set can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a
set cannot have mutable elements like lists, sets or dictionaries as its elements.
In the above example, we have created different types of sets by placing all the elements inside the curly braces
{}.
Note: When you run this code, you might get output in a different order. This is because the set has no
particular order.
To make a set without any elements, we use the set() function without any argument.
For example,
Here,
Finally we have used the type() function to know which class empty_set and empty_dictionary belong to.
Here, we can see there are no duplicate items in the set as a set cannot contain duplicates.
In Python, we use the add() method to add an item to a set. For example,
In the above example, we have created a set named numbers. Notice the line,
The update() method is used to update the set with items other collection types (lists, tuples, sets, etc).
For example,
Here, all the unique elements of tech_companies are added to the company's set.
For example,
Here, we have used the discard() method to remove 'Java' from the languages set.
Built-in Functions with Set
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used with
sets to perform different tasks.
For example,
Here, we have used the len() method to find the number of elements present in a Set.
We use the | operator or the union() method to perform the set union operation.
For example,
Set Intersection
The intersection of two sets A and B include the common elements between set A and B.
Set Intersection in Python
In Python, we use the & operator or the intersection() method to perform the set intersection operation.
For example,
We use the - operator or the difference() method to perform the difference between two sets.
For example,
In Python, we use the ^ operator or the symmetric_difference() method to perform symmetric difference
between two sets.
For example,
Check if two sets are equal
We can use the == operator to check whether two sets are equal or not.
For example,
In the above example, A and B have the same elements, so the condition
evaluates to True. Hence, the statement print('Set A and Set B are equal') inside the if is executed.
More Resources:
1. [Link]
2. [Link]
Python String & String Methods
In computer programming, a string is a sequence of characters.
For example, "hello" is a string containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
[Link]
For example,
Here, we have created a string variable named string1. The variable is initialized with the string Python
Programming.
In the above example, we have created string-type variables: name and message with values "Python" and "I
love Python" respectively.
Here, we have used double quotes to represent strings but we can use single quotes too.
Access String Characters in Python
We can access the characters in a string in three ways.
Indexing: One way is to treat strings as a list and use index values.
For example,
Negative Indexing: Similar to a list, Python allows negative indexing for its strings.
For example,
Slicing: Access a range of characters in a string by using the slicing operator colon :
For example,
Note: If we try to access an index out of the range or use numbers other than an integer, we will get errors.
For example,
However, we can assign the variable name to a new string.
For example,
For example,
In the above example, anything inside the enclosing triple quotes is one multiline string.
We use the == operator to compare two strings. If two strings are equal, the operator returns True. Otherwise, it
returns False.
For example,
str1 and str2 are not equal. Hence, the result is False.
str1 and str3 are equal. Hence, the result is True.
In Python, we can join (concatenate) two or more strings using the + operator.
In the above example, we have used the + operator to join two strings: greet and name.
For example,
For example,
String Membership Test
We can test if a substring exists within a string or not, using the keyword in.
Suppose we need to include both double quote and single quote inside a string,
Since strings are represented by single or double quotes, the compiler will treat "He said, " as the string. Hence,
the above code will cause an error.
For example,
Here, f'{name} is from {country}' is an f-string.
1. This new formatting syntax is powerful and easy to use. From now on, we will use f-Strings to print strings and
variables.
More Resources:
1. [Link]
2. [Link]
3. [Link]
Weekly Challenge
Tasks:
1. Write a program that accepts user input to create a list of integers. Then, compute the sum of all the
integers in the list.
2. Create a tuple containing the names of five of your favorite books. Then, use a for loop to print each
book name on a separate line.
3. Write a program that uses a dictionary to store information about a person, such as their name, age, and
favorite color. Ask the user for input and store the information in the dictionary. Then, print the
dictionary to the console.
4. Write a program that accepts user input to create two sets of integers. Then, create a new set that
contains only the elements that are common to both sets.
5. Create a program that stores a list of words. Then, use list comprehension to create a new list that
contains only the words that have an odd number of characters.
These tasks should test your understanding of basic concepts related to lists, tuples, dictionaries, and sets in
Python. Good luck!
Session 2
Session 3
Week-3: Control flow & Functions in Python
Conditional statements.
As you start this lesson, make sure you have a good understanding of boolean variables and expressions since
they are building blocks of conditional statements.
Let's break this down to pick a boolean expression in our conditional statement.
“Are you hungry” is the boolean expression here, so the conditional statement is checking if it’s True.
If “are you hungry” == True, the conditional statement will be executed and you will eat.
If [you are hungry], then [eat food]
In computer programming, we use the if statement to run a block code only when a certain condition is met.
1. if statement
2. if...else statement
3. if...elif...else statement
1. Python if Statement
Syntax
[Link]
The if...else statement is used to execute a block of code among two alternatives.
However, if we need to make a choice between more than two alternatives, then we use the if...elif...else
statement.
Here,
Write an if/elif/else statement for a college with a grading system as shown below:
[Link]
Python Loops
In computer programming, loops are used to repeat a block of code. We perform a process of iteration
(repeating tasks).
for loop
while loop
1. Indefinite iteration, where the number of times the loop is executed depends on how many times a condition is
met.
2. Definite iteration, where the number of times the loop will be executed is defined in advance (usually based on
the collection size).
In a for loop, we will know in advance how many times the loop will need to iterate because we will be working
on a collection with a predefined length.
With for loops, on each iteration, we will be able to perform an action on each element of the collection.
[Link]
For example,
five_steps = range(5)
# 0, 1, 2, 3, 4
While Loops
[Link]
The break statement is used to terminate the loop immediately when it is encountered.
While the break control statement will come in handy, there are other situations where we don’t want to end the
loop entirely. What if we only want to skip the current iteration of the loop?
Nested Loops
In Python, loops can be nested inside other loops. Nested loops can be used to access items of lists which are
inside other lists. The item selected from the outer loop can be used as the list for the inner loop to iterate over.
Example code
[Link]
[Link]
[Link]
List comprehensions
List comprehensions in Python provide a concise and elegant way to create and manipulate lists. They offer a
more readable and expressive alternative to traditional loops for generating lists.
A list comprehension is a compact syntax for creating a list by evaluating an expression for each element in an
iterable (like a list or range), optionally filtering elements based on a condition.
Syntax:
Basic Example
# Traditional loop
squares = []
for x in range(5):
[Link](x**2)
# List comprehension
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
Here, is the list of comprehension [x**2 for x in range(5)] creates a list of squares of numbers from 0 to
4.
List comprehensions can be nested to handle complex operations, such as creating a matrix.
1. Transforming Data:
2. Filtering Data:
3. Flattening a List:
While list comprehensions are powerful, they can become hard to read if they are too complex. In such cases,
traditional loops or generator functions may be more appropriate.
List comprehensions are a versatile and efficient tool in Python, enabling you to write cleaner and faster code.
They are ideal for transforming, filtering, or generating lists in a Pythonic way. Start practicing them to enhance
your coding skills!
Python Functions
Functions are a fundamental part of Python programming. They allow you to encapsulate reusable blocks of
code to make programs modular, easier to understand, and maintain.
What is a Function?
A function is a block of code designed to perform a specific task. You define a function once and can use it
multiple times throughout your code.
Syntax:
def function_name(parameters):
"""Optional docstring explaining the function."""
# Code block
return value # Optional return statement
Types of Functions
# Function definition
def greet(name):
"""Greet a person by their name."""
return f"Hello, {name}!"
# Function call
print(greet("Alice")) # Output: Hello, Alice!
1. Positional Arguments:
2. Default Arguments:
def greet(name="Guest"):
return f"Hello, {name}!"
3. Keyword Arguments:
Returning Values
def square(number):
return number ** 2
result = square(4)
print(result) # Output: 16
Python supports anonymous functions using the lambda keyword. They are useful for short, simple functions.
Recursive Functions
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
Conclusion
Functions are a powerful tool that makes your code cleaner, more efficient, and easier to maintain. Mastering
their use is essential for any Python developer. Start experimenting with different types of functions to
understand their versatility!
1. Large Power
Create a method that tests whether the result of taking the power of one number to another number provides an
answer which is greater than 5000. We will use a conditional statement to return True if the result is greater
than 5000 or return False if it is not. In order to accomplish this, we will need the following steps:
1. Define the function to accept two input parameters called base and exponent
2. Calculate the result of base to the power of exponent
3. Use an if statement to test if the result is greater than 5000. If it is then return True. Otherwise, return False
Coding Question
Create a function named large_power() that takes two parameters named base and exponent.
If base raised to the exponent is greater than 5000, return True, otherwise return False
[Link] By Ten
Create a function that determines whether or not a number is divisible by ten. A number is divisible by ten if the
remainder of the number divided by 10 is 0. Using this, we can complete this function in a few steps:
Coding question
Create a function called divisible_by_ten() that has one parameter named num.
The function should return True if num is divisible by 10, and False otherwise. Consider using modulo
operator % to check for divisibility.
Session 2
Session 3
Week 4: File Handling & Exception Handling
[Link]
SHA256&X-Amz-Credential=SCW1GD83Z2RS0PZEWJNW%2F20250923%2Ffr-par%2Fs3%2Faws4_request&X-Amz-Date=20250923T141441Z&X-Amz-Expires=518400&X-Amz-
SignedHeaders=host&X-Amz-Signature=b2c6bebd68fe216b953b6a4fb870909925b62deb42c6257fae849b2060131153
Master Files: Get hands-on with opening, reading, writing, and closing files in Python!
Handle Errors Like a Pro: Learn how to catch and manage errors, ensuring your code runs smoothly even when
things don’t go as planned.
File Handling in Python is the ability to perform various operations on files, like reading from and writing to
them. Files are used to store data permanently (like text documents, images, or spreadsheets). Unlike variables,
which lose their values when a program ends, files provide persistent storage.
Python’s built-in open() function is at the heart of this process, and learning how to handle files can make
your programs more robust, flexible, and useful.
Opening Files 🔓
o Use Python’s open() function to access a file.
o Syntax: open(filename, mode), where:
filename: The name of the file you want to work with.
mode: The mode you want to open the file in.
o Modes include:
'r': Read mode, used for reading files.
'w': Write mode, creates a new file or overwrites an existing one.
'a': Append mode, adds new content without deleting existing data.
'rb', 'wb': Binary modes for non-text files, like images.
Example:
Reading Files 📜
o Python provides multiple ways to read file contents:
.read(): Reads the entire file.
.readline(): Reads a single line at a time.
.readlines(): Reads all lines and returns a list.
o Example:
with open("[Link]", "r") as file: data = [Link]() print(data)
Closing Files 🚪
o Files should be closed after processing to release system resources.
o Python’s with statement automatically handles closing, ensuring efficient resource management.
Exception Handling 🌪️
Errors happen! To make sure your programs are error-proof and user-friendly, Python provides Exception
Handling. It’s the art of catching errors and handling them gracefully.
try:
with open("[Link]", "r") as file:
data = [Link]()
except FileNotFoundError:
print("File not found. Please check the filename.")
finally: Runs no matter what, often used to clean up (like closing a file).
Custom Errors: Create custom exceptions for special cases (e.g., EmptyFileError).
try:
file = open("[Link]", "r")
data = [Link]()
except FileNotFoundError:
print("File not found.")
finally:
[Link]()
Best Practices 📏
Use with for file handling: Auto-close files, preventing potential leaks.
Check file existence before reading/writing, to avoid crashes.
Handle specific exceptions over general ones (e.g., FileNotFoundError instead of Exception).
Document error messages clearly for easier debugging and user support.
File Handling and Exception Handling Recording
(Right click on a link to open on a new tab)
Github Links:
[Link]
[Link]
Session 1 Recording
Session 2 Recording
Session 3 Recording
Create a program that reads a text file, processes its content, and writes the results to a new file.
📌 Task Requirements:
1. Create a file called [Link] and write at least five lines of text into it.
2. Write a Python script to:
o Read the contents of [Link].
o Count the number of words in the file.
o Convert all text to uppercase.
o Write the processed text and the word count to a new file called [Link].
3. Print a success message once the new file is created.
Week 5: Object Oriented Programming
Introduction to OOP: Classes, Objects, Attributes, and Methods (1 hour) 🏫
What’s OOP?
Imagine everything as objects — a car 🚗, a book 📚, or even a cute little puppy 🐶. OOP helps us model
complex systems by treating real-world entities as objects within the program. We assign them classes (their
blueprint), attributes (their characteristics), and methods (their actions)!
Key Concepts:
Class: The blueprint or prototype, like a recipe 🍲! Defines the structure for creating objects.
Object: A specific instance of a class. Think of it as a cake made from that recipe 🎂.
Attributes: Characteristics or properties of an object, like the color of a car.
Methods: Actions or behaviors that the object can perform (e.g., drive() for a car).
# Defining a class
class Car:
color = "red" # Attribute
# Method
def drive(self):
print("The car is driving 🚗")
# Creating an object
my_car = Car()
print(my_car.color)
my_car.drive()
What’s a Constructor? Every time you create a new object, you want it to have its unique attributes (color,
model, etc.). Constructors (__init__ methods) allow each object to start with specific values. It’s like building
a pizza 🍕 with the toppings you want!
Instance Variables
Instance variables are specific to each object and can vary across objects. For example, two Car objects can
have different colors, models, and speeds.
class Car:
Inheritance 👨👩👧👦: Just like humans inherit traits from their parents, classes can inherit attributes
and methods from other classes. This helps reduce code repetition and create a natural hierarchy in your
code!
o Example: Imagine a Vehicle class with general features (like wheels). We can create subclasses like
Car and Bike that inherit those features!
python
class Vehicle:
class Car(Vehicle):
pass
car = Car(4)
print([Link]) # Output: 4
Polymorphism 🦄: Derived classes can behave differently for the same method inherited from a base
class. With polymorphism, a method name can mean different things across multiple classes.
o Example: Imagine a speak() method. Dogs bark(), while cats meow(), even though both use
speak()!
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
# Polymorphism in action
for animal in [Dog(), Cat()]:
print([Link]())
Encapsulation 🔐: This is the practice of keeping attributes and methods private to prevent unwanted
interference from outside the class. It’s like hiding your chocolate stash 🍫 from everyone else!
class SecretStash:
def __init__(self):
self.__chocolates = 10 # Private attribute
def take_chocolate(self):
if self.__chocolates > 0:
self.__chocolates -= 1
print("One chocolate taken!")
else:
print("No chocolates left 😢")
stash = SecretStash()
stash.take_chocolate()
In Summary
OOP allows you to organize code in a way that’s fun, reusable, and efficient! As you practice, imagine
the real-world objects around you and think of how they could become classes in your code. Whether
you’re designing a Smartphone, Pet, or Superhero, OOP gives you the power to build programs that
feel like real-world systems.
Session 1
Session 2
Session 3
Github Link
POOP
Presentation
POOP
CatchUp Session
POOP_CatchUp
Week 6: Python Libraries
🎯 Learning Objectives
A Python library is a collection of pre-written code that you can use to perform common tasks without having to write
everything from scratch.
Think of it like a toolbox. If you're building something, instead of making your own hammer, you just pull one out from
the toolbox!
Python has many built-in libraries (you don’t need to install them).
Example: math
import math
print([Link](16)) # Output: 4.0
print([Link]) # Output: 3.141592653589793
from math
today = [Link]()
print("Today's date is:", today)
now = [Link]()
print("Current time:", [Link]("%H:%M:%S"))
Python has lots of built-in tools (standard library), but sometimes you'll need more. That’s where third-party packages
come in — extra tools made by the community.
pip
PyPI
PyPI (Python Package Index) is the place where all these third-party packages live.
pip automatically pulls packages from PyPI.
You can also visit [Link] to search for packages manually.
requests
scrapy
Twisted
Pillow
lxml
PyYAML
Django, Flask, Pyramid
SQLAlchemy
numpy, scipy, pandas
pytest, tox, coverage, mock
six
Jinija2
cryptography
pylint, flake8, pep8
pymongo, redis, MySQL-Python, psycopg2
Resources:
1. [Link]
Python Standard Library
The Python Standard Library is a collection of built-in modules that come with Python. These modules help you do
common tasks like reading files, working with dates, or handling math — without installing anything extra.
There are many more libraries in Python. We can use a suitable library for our purposes. Hence, Python
libraries play a very crucial role and are very helpful to the developers.
What is NumPy?
🔧 Installing NumPy
pip install numpy
✨ Basic NumPy Example
import numpy as np
# Perform operations
print("Array * 2:", my_array * 2) # Multiply each element by 2
print("Mean:", [Link](my_array)) # Average of the array
print("Square Roots:", [Link](my_array))
🔧 Installing Pandas
pip install pandas
✨ Basic Pandas Example
import pandas as pd
df = [Link](data)
print(df)
# Access column
print("Names:", df['Name'])
# Filter rows
print("Scores above 90:")
print(df[df['Score'] > 90])
📁 Reading CSV Files with Pandas
df = pd.read_csv('[Link]')
print([Link]()) # Show first 5 rows
🧠 What is Matplotlib?
Matplotlib is a library that allows you to create visual representations of your data. It’s especially useful when working
with data in Pandas or NumPy.
🔧 Installing Matplotlib
pip install matplotlib
📈 Basic Line Plot
import [Link] as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
# Create a DataFrame
data = {
'Year': [2021, 2022, 2023],
'Users': [1500, 3000, 5000]
}
df = [Link](data)
🧠 Practice Tasks
Session 1
Session 2
Session 3
Presentation
GitHub Repo
CatchUp Session
Week 7: Basic Data Analysis
Objectives:
What is pandas?
pandas is an open-source Python library that provides high-performance, easy-to-use data structures and data
analysis tools. It is primarily used for working with tabular data in the form of DataFrames. It allows you to
efficiently manipulate, clean, and analyze structured data.
Series: A one-dimensional labeled array that can hold any data type (integers, strings, etc.).
DataFrame: A two-dimensional, size-mutable, potentially heterogeneous tabular data structure with labeled
axes (rows and columns).
Creating DataFrames: You can create a DataFrame by loading data from various formats like CSV,
Excel, or SQL databases. For example:
import pandas as pd
df = [Link](data)
print(df)
Reading Data: pandas allows you to load data from multiple sources, such as:
Manipulating DataFrames:
Basic Filtering: To filter data based on conditions, you can use boolean indexing.
# Get rows where Age is greater than 30
df_filtered = df[df['Age'] > 30]
Multiple Conditions: You can combine multiple conditions using logical operators:
# Get rows where Age is greater than 30 and City is 'New York'
df_filtered = df[(df['Age'] > 30) & (df['City'] == 'New York')]
Sorting Data
o Sorting by Columns: You can sort the DataFrame by a column in ascending or descending
order:
Groupby: pandas groupby method is essential for aggregating data based on one or more columns. For
example:
Summary Statistics: pandas provide several built-in functions to calculate summary statistics:
matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It's
often used for visualizing the results of data analysis. The most common form of visualization is through line
plots, scatter plots, bar plots, and histograms.
Bar Plot:
# Plotting a bar chart for Age by City
[Link]('City')['Age'].mean().plot(kind='bar')
[Link]('City')
[Link]('Average Age')
[Link]('Average Age by City')
[Link]()
Histogram:
# Plotting a histogram for Age
df['Age'].plot(kind='hist', bins=10)
[Link]('Age')
[Link]('Age Distribution')
[Link]()
Scatter Plot:
# Plotting a scatter plot of Age vs. City
[Link](kind='scatter', x='City', y='Age')
[Link]('City vs Age')
[Link]()
Customizing Plots
Best Practices for Working with Data and Basic Data Analysis:
1.
1. Data Cleaning: Before analysis, always ensure the data is clean. This includes handling missing
values ([Link]()), removing duplicates (df.drop_duplicates()), and dealing with
outliers.
2. Efficient Data Access: pandas provides several ways to read large datasets efficiently. For
example, use chunksize to read large CSV files in chunks.
3. Handling Data Types: Ensure the data types of your columns are correct (e.g., using df['Age']
= df['Age'].astype(int)).
4. Documentation: When working on analysis, make sure to document your code and the
reasoning behind each transformation or computation.
Additional Resources:
By completing these exercises and concepts, learners will gain a solid foundation in handling and analyzing
data using pandas and matplotlib. These skills will be essential for performing data-driven tasks like cleaning,
analyzing, and visualizing data.
Session 1
Session 2
Session 3
Presentation
Github Repo
Catchup Session
Catchup Session Repo
🔹 Challenge: Perform basic data analysis on a CSV file and generate insights!
📌 Task Requirements:
1. Download or create a CSV file called sales_data.csv with the following columns:
o Date (YYYY-MM-DD)
o Product
o Quantity Sold
o Revenue ($)
2. Write a Python script to:
o Load the CSV file using pandas.
o Calculate the total revenue.
o Find the best-selling product (based on Quantity Sold).
o Identify the day with the highest sales.
o Save the results to a new file called sales_summary.txt.
3. Print the insights in a user-friendly format.
🎯 Bonus Challenge:
Quantity
Date Product Revenue ($)
Sold
Frameworks save developers from repetitive coding tasks, streamline project architecture, inject security best
practices, and often supercharge productivity by enforcing modular designs and “batteries-included”
philosophies. For learners and developers, understanding the diverse landscape of Python frameworks is crucial
for selecting the right tool for varying technical challenges, resource settings, and organizational needs, whether
building for local SMBs or aiming at international impact.
Below, we examine a carefully selected array of both mainstream and niche Python frameworks, analyzing each
in terms of its purpose, core functionalities, project orientation, practical usage, advantages and limitations, and
recommended scenarios for application. Learners will find guidance on when and why to prefer particular
frameworks considering regional constraints and ambitions.
ORM, admin,
Large, robust, Rapid Enterprise
routing, Heavyweight,
Django Full-stack web database-driven prototyping, apps, data
authentication, less flexible
web apps security, scale platforms
templating
APIs,
URL routing, Lightweight, Few built-ins, APIs, small
microservices,
Flask Microframework templating, modular, manual apps, custom
SPAs,
minimal core flexible integrations projects
prototyping
Async support, type REST APIs, Performance, Steep async AI/ML APIs,
FastAPI High-perf API hints, auto docs, ML/AI, async docs, async- learning, real-time
data validation apps ready minimal core systems
All-in-one file,
Simplicity, Rapid protos,
minimal Small apps, Not scalable,
Bottle Microframework single file, no teaching,
dependencies, easy prototyping, IoT few built-ins
deps scripts
routing
Each of these frameworks receives detailed, paragraph-driven analysis—see sections that follow for deep dives,
practical code examples, and scenario recommendations.
Recommendations for Learners in: How to Choose
For Absolute Beginners and Educators: Start with Bottle for basics, then move to Flask (for hands-on experience
of routing, templates, and coding conventions).
For Database-Driven, Multi-User Web Applications: Django is king due to its maturity, documentation, security,
and scalability.
For Rapid API Development or High-Performance, Real-Time Requirements: FastAPI (modern APIs, async) or
Tornado (low-level real-time control).
For Modular, Evolving Projects: Pyramid or TurboGears—allowing start-small, scale-later approaches, suited for
start-ups or projects with uncertain requirements.
For Data Science, Analytics, Machine Learning: Streamlit for dashboard/data exploration, Dash for interactive
data viz, Panel for advanced workflows, Gradio for ML model demos.
For Learning Modern Python async: FastAPI or Sanic—both offer real concurrency, preparing you for scalable
systems and cloud native architectures.
For IoT, Embedded, or Prototyping: Bottle (ultra-lightweight, single-file deployment).
Conclusion
The breadth of Python frameworks ensures there is “the right tool for every job,” whether you are in a Kenyan
classroom, a Nairobi fintech startup, or a global open-source research team. By understanding the purpose,
strengths, limitations, and ideal use cases of each major framework, learners and developers truly empower
themselves to build not only robust, scalable applications, but also to choose tools that best fit their problem,
knowledge level, and local context.
The path to becoming a skilled Python developer involves not just coding, but learning when and why to
employ (or avoid) each framework. Use this guide as a reference and platform for continued research, as the
Python ecosystem continues to evolve, welcoming newcomers and powering innovation worldwide.
Django
Purpose
Django is a high-level, full-stack web framework championed for rapid development and pragmatic design. It follows the
“batteries-included” philosophy, providing every major component needed for robust database-driven applications,
reducing the need for repetitive code and integrating best practices by default.
Core Functionalities
Object-Relational Mapping (ORM): Seamlessly maps Python classes to database tables, abstracting SQL and
offering database portability.
Automated Admin Interface: Generates a powerful admin backend for CRUD operations.
Routing (URL Dispatcher): Sophisticated, human-readable URL organization.
Authentication & Authorization: Built-in user management, permissions, and group handling.
Templating System: Secure and dynamic HTML rendering.
Security Features: Out-of-the-box CSRF protection, session management, security middleware, and more.
Project Orientation
Django is suited for large-scale, database-driven applications, including social media platforms, financial platforms,
content management systems, and marketplaces. It is particularly effective for rapidly prototyping secure, production-
grade apps that are likely to experience scaling needs over time.
Model Example
def hello_world(request):
return HttpResponse("Hello, Django World!")
urlpatterns = [
path('', hello_world),
]
To run this, the developer would integrate it into Django’s URL configuration and launch the app via python [Link]
runserver after initializing a project.
Advantages
Django’s strengths lie in productivity, security, scalability, and community. Its mature ecosystem and comprehensive
documentation mean developers can quickly build, test, and deploy complex projects without reinventing the wheel.
The admin panel saves weeks of development, the ORM removes much of the hassle of SQL, and baked-in protections
guard against common vulnerabilities. Companies like Instagram, Spotify, and Mozilla illustrate its capacity for
enterprise-grade projects. The vibrant community ensures learners find extensive global resources.
Limitations
As a “heavy” framework, Django can be too opinionated or restrictive for projects requiring greater flexibility. Integrating
non-Django tools or architectures (e.g., advanced async, custom ORMs) involves complex workarounds or re-architecting
parts of the stack. For the simplest microservices, Django’s bulk introduces unnecessary complexity and overhead.
Django is ideal for learners seeking marketable, full-stack web development skills or aiming for
enterprise/organizational freelance opportunities. Its strong documentation and security focus mean beginners build
“correct” structures out of the gate. Use Django for:
Flask is a minimalist, “micro” web framework designed to offer the essentials: routing, request/response
handling, and templating, while staying out of the developer’s way. Its design encourages extensibility—
developers bolt on only what they need, resulting in highly tailored application stacks.
Core Functionalities
Project Orientation
Flask’s sweet spot is small to medium-sized web apps, RESTful APIs, microservices, and quick
prototypes. It is especially favored for projects needing custom application structures or for teaching core web
concepts due to its simplicity.
Model Example
app = Flask(__name__)
@[Link]("/")
def hello_world():
return "Hello, Flask!"
if __name__ == '__main__':
[Link](debug=True)
Advantages
Flask rewards simplicity, flexibility, and control. It puts almost no restrictions on project architecture, so
learners are exposed to “real” web app composition. Its minimalism encourages learning by building—the
developer chooses their ORM, admin, authentication, and more as needed. This modularity is valuable for
educational settings where understanding each moving part is the key goal. The community is robust, and
there’s strong extension support.
Limitations
While freedom is a strength, it is also a potential risk: Flask apps can become difficult to maintain as
complexity grows if there are not strong internal conventions. Many essential features (user management,
admin, form validation) require additional setup and often, extension selection can cause confusion or
incompatibility for beginners. It is rarely the right choice for large, standardized teams or for projects needing
rapid scaling with minimal configuration.
Flask is a superb teaching framework and is also recommended for rapid prototyping, lightweight APIs, or
microservices in start-ups and SMEs. Great use cases include:
Streamlit
Purpose
Streamlit is an open-source Python framework for rapidly turning data scripts into interactive web apps with
only a few lines of code and zero front-end knowledge34. It is purpose-built for data scientists and ML
engineers to share results visually and interactively—no HTML, CSS, or JS required.
Core Functionalities
Interactive Widgets & Components: Sliders, inputs, data tables, and more.
Live Re-running: Instant UI updates as the Python script changes.
Auto Integration with pandas, matplotlib, Plotly: Seamless for data vis.
Simple API: Minimal learning curve for anyone familiar with Python.
Project Orientation
Streamlit is ideal for data exploration tools, ML model prototyping and demos, quick interactive
dashboards, and classroom data science demonstrations.
Model Example
python
import streamlit as st
import pandas as pd
Launch via streamlit run [Link] and view live updates in your browser.
Advantages
Supremely simple and fast for ML/data prototyping. Learners can go from dataset to web app in minutes.
Automatic, responsive UIs are generated for Python functions, aiding collaboration and reproducibility in data
science workflows.
Limitations
Not suitable for general-purpose web development; limited customization of UI and navigation. For production-
grade or highly trafficked apps, performance can suffer. Streamlit is not meant for apps needing complex
authentication or back-end integrations.
For data science students, ML enthusiasts, researchers, and educators, Streamlit is a must-learn. Use
Streamlit to:
For full-stack web apps or standardized UIs, switch to Dash, Flask, or Django.
Dash
Purpose
Dash by Plotly is an open-source Python framework specifically tailored for building data-centric, analytical
web applications with interactive visualizations. It is highly favored in business intelligence, scientific
computation, and enterprise reporting.
Core Functionalities
Project Orientation
Dash is built for interactive dashboards, reporting apps, advanced analytics, data science portals, and
internal business tools.
Model Example
python
import dash
from dash import html
app = [Link](__name__)
[Link] = [Link](children=[
html.H1('Hello Dash!'),
[Link]('Dash: A web application framework for Python.')
])
if __name__ == '__main__':
app.run_server(debug=True)
Advantages
Dash comes equipped with easy linking of interactive charts and UI widgets, facilitating rapid analytical
app development. No need for bespoke web skills—ideal for data-driven organizations. Dash’s Plotly
underpinnings give it unmatched data vis and real-time updates38.
Limitations
Limited UI customization compared to general web frameworks. Advanced layouts or navigation can be
complex, and learning Dash’s callback architecture takes effort. For projects with no analytical component, it’s
overkill.
Data analysts, scientists, and business-savvy developers should use Dash for client dashboards, academic
presentations, NGO data portals, and any scenario where visual analytics are paramount. For mobile-first
or generic web products, use another framework.
FastAPI
Purpose
FastAPI is a modern, high-performance web framework purpose-built for creating APIs with Python 3.8+. It
was designed to leverage asynchronous programming and type hints for developer productivity, speed, and
automatic OpenAPI (“Swagger”) documentation.
Core Functionalities
Project Orientation
FastAPI targets modern RESTful APIs, high-throughput AI/ML model deployment, streaming platforms,
and any application where real-time, concurrent request handling is critical. It is rising quickly as a
favorite for both web developers and data scientists.
Model Example
app = FastAPI()
@[Link]("/")
async def read_root():
return {"Hello": "FastAPI"}
Run the server via uvicorn main:app --reload on [Link] Interactive API documentation
is available at /docs.
Advantages
FastAPI combines performance and developer experience. Its async model enables thousands of concurrent
connections, ideal for financial-tech, IoT, or AI streaming. Built-in data validation reduces runtime bugs, while
OpenAPI docs improve collaboration and client-code generation. It has rapidly grown a vibrant community and
ecosystem, with strong learning materials.
Limitations
Working with async code - especially for those coming from strictly synchronous environments - introduces a
steep learning curve: debugging, testing, and concurrency control are more complex than with traditional
frameworks. FastAPI intentionally omits built-in admin tools, authentication, or ORM layers, requiring
additional frameworks or custom code for such features.
FastAPI is exceptional for learners targeting modern API development, high-concurrency systems, or
AI/ML deployment within the tech scene—for example, in fintech firms, edtech APIs, or government data
innovation. Choose FastAPI for:
Be prepared to learn about asynchronous Python, Pydantic, and relevant deployment techniques.
Pyramid
Purpose
Pyramid is a flexible, “minimal-to-complex” web framework optimizing for developer choice, scalability, and
the freedom to use only those features you need. Known for its “start small, finish big” motto, it enables quick
one-file apps or expansive, enterprise-grade deployments, bridging the gap between microframeworks and full-
stack solutions.
Core Functionalities
Project Orientation
Pyramid fits a broad range of applications—from basic, single-file sites to modular, complex business
systems. It is especially suited to projects where requirements will change and scale, or where integrations with
multiple technologies are vital.
Model Example
def hello_world(request):
return Response('Hello, Pyramid!')
if __name__ == '__main__':
with Configurator() as config:
config.add_route('hello', '/')
config.add_view(hello_world, route_name='hello')
app = config.make_wsgi_app()
server = make_server('[Link]', 6543, app)
server.serve_forever()
Advantages
Pyramid’s prime virtue is adaptability. Beginners or teams can incrementally add complexity as the project
grows—starting with only routing, then layering on templating, ORM, authentication, and deployed
components as needs change. The quality of documentation and cross-platform support are strong attractions.
Pyramid is used by global names such as Mozilla and SurveyMonkey, reflecting its robustness.
Limitations
Compared to Django or Flask, Pyramid’s documentation is less widely referenced and its developer community
is smaller, meaning less third-party tutorials, templates, or out-of-the-box integrations for learners. Setting up
add-ons may require more time and understanding of configuration systems.
Those aiming to build modular, long-lifetime systems or start minimal with room to expand will benefit
from Pyramid. Projects that outgrow Flask can migrate to Pyramid for advanced security, scaling, or
architecture. Great for:
Tornado
Purpose
Tornado is a web framework and asynchronous networking library for Python, specialized in non-blocking
network I/O and high concurrency. It is ideal for projects requiring long-lived connections, such as chat servers,
IoT telemetry ingestion, or WebSocket-powered live dashboards, and is not bound by Python’s traditional
WSGI limitations.
Core Functionalities
Project Orientation
Tornado is well-suited to real-time web services, chat platforms, streaming APIs, high-concurrency IoT
devices, and low-latency fintech or social apps, especially when custom protocols or persistent connections
are required.
Model Example
import [Link]
import [Link]
class MainHandler([Link]):
def get(self):
[Link]("Hello, Tornado!")
def make_app():
return [Link]([
(r"/", MainHandler),
])
if __name__ == "__main__":
app = make_app()
[Link](8888)
[Link]().start()
Advantages
Tornado’s non-blocking design makes it supremely scalable for concurrent workloads. It is one of the few
frameworks that can easily serve real-time web apps and protocols like WebSockets at scale without relying on
additional reverse proxies or asynchronous servers. It is lightweight at its core and is friendly to custom
extensions—useful for Kenya’s growing tech scenes in finance and telco where real-time is a must.
Limitations
Its programming model requires a solid grasp of asynchronous event loops and non-blocking paradigms, which
can be confusing for those used to synchronous frameworks. Not the best fit for standard CRUD apps or when
rich, full-feature features (ORM, admin, auth) are expected. The ecosystem for “classic” web features is
relatively small.
If your project involves live chat, live sports, betting platforms, IoT devices, or interactive fintech
dashboards, Tornado may be ideal. However, general web learners may find Flask or Django easier, and only
“graduate” to Tornado once comfortable with Python’s async/await style and real-time networking.
Bottle
Purpose
Bottle is a compact, minimalistic Python web framework distributed as a single file, with no dependencies other
than the standard library. It is best viewed as a simplified teaching and prototyping tool, as well as a workhorse
in resource-constrained or embedded environments.
Core Functionalities
Project Orientation
Bottle is typically used for small web apps and services, rapid prototyping, embedded web application
teaching, and IoT device UIs. Its lack of architectural or configuration complexity makes it perfect for short,
educational code examples.
Model Example
@route('/hello/<name>')
def index(name):
return template('<b>Hello {{name}}</b>!', name=name)
run(host='localhost', port=8080)
Advantages
Bottle offers supreme simplicity and zero friction. Learning core web concepts (routing, HTTP
requests/responses) becomes trivial. Its single-file distribution is perfect for scripting, small demos, or rapid
deployment in environments with dependency constraints—such as Raspberry Pi hardware labs, schools, and
prototyping workshops.
Limitations
The micro core delivers only essentials. There’s no ORM, authentication, forms, scaffolding, or advanced
middleware support, meaning everything must be built or integrated by hand. For anything larger than small
tools or teaching apps, scaling and maintainability become a challenge.
Bottle is ideal for education, IoT, and resource-constrained environments common in local schools and
workshops. Use it to:
CherryPy
Purpose
CherryPy is an object-oriented, minimalist web framework for Python designed around ordinary Python
classes and methods. With a built-in multi-threaded web server and a focus on “pythonicity,” it makes database-
driven and modular web development possible with relatively little boilerplate.
Core Functionalities
Project Orientation
CherryPy fits database-backed web services, internal business tools, educational OOP web development
projects, and as a core for custom web servers. Its design philosophy emphasizes modifiability—good for
educators and tinkerers.
Model Example
import cherrypy
class HelloWorld(object):
@[Link]
def index(self):
return "Hello World!"
if __name__ == '__main__':
[Link](HelloWorld())
Advantages
CherryPy’s OOP approach is uniquely Pythonic. It allows developers to reuse code, refactor, and compose
complex applications with fewer lines, and the built-in web server simplifies deployment. It is especially well-
suited to situations where in-depth knowledge of Python class design and web integration is beneficial.
Limitations
A steeper learning curve—especially for those with no prior exposure to object-oriented patterns. It is relatively
less popular these days, leading to limited third-party resources and fewer recent plugins. Not much emphasis
on “modern” web features like async or auto-generated docs.
Consider CherryPy for teaching object-oriented web development, small to mid-size database apps, and
projects requiring deep customization. Its clarity helps bridge the gap from scripting to OOP, though for large
commercial projects, Django or Flask are easier to champion.
Falcon
Purpose
Falcon is a lightweight, high-performance web framework designed for rapid building of RESTful APIs and
microservices, focusing on speed, reliability, and correctness at scale. It minimizes framework “magic” and
promotes idiomatic, maintainable Python.
Core Functionalities
Project Orientation
Falcon is meant for mission-critical APIs, scalable backend microservices, cloud API gateways, and
projects where raw performance and predictable latency are vital.
Model Example
import falcon
class HelloWorldResource:
def on_get(self, req, resp):
[Link] = falcon.HTTP_200
[Link] = "Hello, Falcon World!"
app = [Link]()
app.add_route('/hello', HelloWorldResource())
Advantages
Falcon offers best-in-class API performance and code clarity. By focusing on HTTP first principles and
avoiding “auto” behaviors, it is easy to reason about and debug even in very large deployments. Companies like
PayPal and OpenStack rely on Falcon for their critical services.
Limitations
There is little scaffolding—even basic features (templates, ORM, auth) must be handled externally. Not suitable
for beginners or general web apps; it’s built for APIs and expects developers to manage a lot of config and
architecture.
Perfect for API specialists and those building microservice meshes, fintech endpoints, or real-time data
ingestion layers requiring minimal latency and maximum throughput. Avoid as a “first” web framework,
but study it as you move into enterprise, API-first, or cloud native architectures.
Sanic
Purpose
Sanic is an asynchronous Python 3.6+ web framework crafted for speed, offering lightning-fast HTTP and
WebSocket servers out of the box. It leverages Python’s async features and the uvloop event loop for superior
concurrency.
Core Functionalities
Project Orientation
Sanic is well-suited for real-time web apps, chat services, microservices, and any workload needing
extreme concurrency/performance, especially in start-ups and fintech.
Model Example
from sanic import Sanic
from [Link] import text
app = Sanic("HelloSanicApp")
@[Link]("/")
async def hello_world(request):
return text("Hello, world.")
if __name__ == "__main__":
[Link](host="[Link]", port=8000)
Advantages
Sanic’s true async core is built for throughput. It’s the best way for Pythonistas to match [Link]-style real-
time web servers, and its bundled server means easy deployment. Its documentation and community have
matured, and it’s increasingly trusted for low-latency, event-driven architectures.
Limitations
Smaller ecosystem than Flask or Django. Complex apps demand careful management of async patterns and
concurrency. Async debugging is more complex, and integration with frameworks expecting WSGI needs care.
Sanic is great for innovators, real-time notification systems, Kenyan fintech APIs needing scale, or any
deep-tech firm seeking the best in Python async concurrency. Best to tackle after learning Flask or Django,
and after mastering async Python.
Web2py
Purpose
Web2py is an open-source, full-stack framework for agile, secure, database-driven web application
development. Emphasizing simplicity and “out-of-the-box” productivity, it uses a web-based IDE and
prioritizes security and rapid prototyping.
Core Functionalities
Integrated Web IDE: Build, edit, deploy apps from the browser.
Automatic Admin Interface: CRUD admin dashboards for models.
MVC Pattern: Clean separation for manageable projects.
Rich Database Abstraction Layer (DAL): Cross-database queries without SQL.
Integrated Security: Auto input validation, XSS, CSRF protections.
Project Orientation
Web2py is typically used for educational platforms, internal tools, rapid admin-driven database
applications, and small-to-midsize business platforms.
Model Example
Advantages
Web2py is ideal for education, prototyping, and apps needing robust security from day one. Its minimal
configuration, cross-platform nature, and clear embrace of the MVC pattern make it easy for beginners.
Limitations
Web2py is less modern than Django or FastAPI—async support is limited, and its plugin ecosystem is aging. It
is not recommended for new, large-scale production projects; maintainers now recommend py4web for new
work.
Web2py’s ease of use makes it perfect for educational settings, hackathons, and prototypes or “safe”
admin dashboards that won’t need to scale out. For large, public systems, prefer Django or FastAPI.
TurboGears
Purpose
TurboGears is an extensible Python web framework that can operate either as a microframework for small
applications or scale up to a full-stack solution for complex systems. It bridges the flexibility of Flask with the
power of Django, aiming to “scale with you.”
Core Functionalities
Project Orientation
TurboGears works for start-ups, classroom projects, or SaaS companies expecting their stacks to evolve
from MVP prototypes to enterprise platforms.
Model Example
from wsgiref.simple_server import make_server
from tg import MinimalApplicationConfigurator, expose, TGController
class RootController(TGController):
@expose(content_type="text/plain")
def index(self):
return 'Hello World'
config = MinimalApplicationConfigurator()
config.update_blueprint({'root_controller': RootController()})
TurboGears allows flexibility and smooth scaling. Use it as Flask at first, then add admin, ORM, migrations,
etc. as your company or project grows. Its toolchain helps educational settings teach everything from “hello
world” to enterprise complexity in one stack.
Limitations
Somewhat less popular and documented than Django or Flask; the learning curve can be steeper, and the
community is smaller, which may present challenges for new developers.
TurboGears is great for computer science curricula, growing SaaS businesses, startups, or anyone
expecting their web app’s needs to change significantly over time. For a more straightforward entry, begin
with Flask before scaling up.
Panel
Purpose
Panel is an open-source dashboarding and data exploration framework that helps build complex analytics
applications and dashboards in pure Python, often serving as a bridge between Jupyter notebooks and
deployable web solutions.
Core Functionalities
Project Orientation
Panel is a strong fit for advanced dashboards, research data-wrangling tools, Jupyter extension apps, and
enterprise analytics requiring powerful visualization.
Model Example
import panel as pn
def say_hello(name):
return f"Hello, {name}!"
[Link]()
[Link](say_hello, name='World').servable()
Advantages
Panel is the “Swiss army knife” for data science dashboards and interactive exploration. Its PyData
ecosystem compatibility makes it especially valuable for researchers and educators collaborating on real-world
datasets and analyses in Python, with minimal web-dev overhead.
Limitations
Steep learning curve for beginners and more configuration required than Streamlit. Documentation, while
growing, is not as extensive as for Django or Dash.
Panel is best for universities, analytics consulting teams, advanced scientific researchers, or anyone
needing robust data visualization and dashboarding tailored to unique workflows. For simpler or more
straightforward dashboards, prefer Streamlit or Dash.
Gradio
Purpose
Gradio is an innovative, open-source Python framework focused on building user-friendly, interactive web
interfaces for machine learning models, APIs, and functions with minimal effort.
Core Functionalities
Drag-and-Drop ML Demos: UIs generated for Python functions with support for various input/output types.
Multi-modal Components: Handle text, image, audio, video, and more.
Shareable Links: Easy sharing of model demos and tools.
Integration: Seamless with Hugging Face, TensorFlow, PyTorch.
Customizable Layouts: Flexible interfaces for model comparisons, parameter testing.
Project Orientation
Targeted towards machine learning developers, researchers, teachers, or anyone keen on sharing,
demoing, or testing ML models interactively.
Model Example
import gradio as gr
def greet(name):
return "Hello " + name + "!"
if __name__ == "__main__":
demo. Launch()
Advantages
Gradio sets the standard for ML interactivity. It’s the quickest, easiest way to build public-facing demos,
classroom interactive experiments, or input-testing GUIs for models with zero web expertise required. Rapid
adoption in ML research communities attests to its value.
Limitations
Not suitable for general web or dashboard development. Limited for apps with extended navigation, persistent
storage, or complex authentication flows.
Gradio is highly recommended for students, educators, and ML practitioners wanting to showcase or test
models locally or with peers. It’s perfect for hackathons, show-and-tell sessions, and open-data ML
collaborations.
Session 1
Session 2
Session 3
Catchup Session
Project Ideas
You've reached The Grand Finale🏆! This is the ultimate test of your coding journey—a chance to bring all
your hard work, creativity, and skills together. Prepare to leave your mark as we celebrate the incredible
culmination of your bootcamp adventure! 🎉
As a beginner or an intermediate developer, it's okay to admit it might be hard to have a project in mind to work
on. Here are some of the projects that you can work on. These projects are categorized into sectors and levels of
complexity.
SDG 1: No Poverty
Project Ideas:
Guidelines:
Build apps that teach money skills in simple language so families can budget and save.
Use AI to create personalized budgeting tips that match the income and spending habits of poor
households.
Develop crowdfunding platforms where communities can directly support people in need.
Provide microloan platforms with low-interest loans to small businesses to promote self-reliance.
Use maps and data analysis to pinpoint areas with the highest poverty and guide support.
Guidelines:
Create apps that help households and businesses track and reduce food waste.
Build smarter supply chains so food moves faster from farms to tables without loss.
Use AI to provide affordable meal and diet suggestions to improve nutrition.
Develop platforms where restaurants and stores can donate surplus food directly to people in need.
Support farmers with data platforms that give real-time updates on soil, weather, and crops.
SDG 3: Good Health and Well-Being
Project Ideas:
Guidelines:
Build apps that let patients monitor blood sugar, blood pressure, or other chronic conditions easily.
Create telemedicine platforms so rural families can see doctors online without travel.
Use AI chatbots to give friendly mental health support and check-ins.
Design apps that track vaccinations for children and adults, with reminders.
Develop wearables that provide real-time health data for quick response.
Guidelines:
Create low-cost e-learning platforms so every child can learn from anywhere.
Use AI tutors to provide step-by-step lessons tailored to each student’s pace.
Build mobile apps that provide free or cheap books, notes, and resources.
Develop skill-building platforms that train youth for jobs in demand.
Set up virtual classrooms that make remote education interactive and accessible.
Guidelines:
Create apps that show households how much water they use daily.
Build systems to test and monitor water quality instantly.
Develop mobile apps that map the nearest clean water sources.
Use sensors for smart city water management that reduce waste and leaks.
Apply AI to predict droughts and water shortages early.
Guidelines:
Develop apps to show how much energy solar panels produce daily.
Create smart home systems that turn off unused devices automatically.
Provide apps that let households track and compare renewable energy use.
Use AI to help energy providers balance supply and demand efficiently.
Build trading platforms where communities can share and sell renewable energy locally.
Guidelines:
Create AI-based platforms that match job seekers with the right opportunities quickly.
Build freelancer platforms that connect marginalized communities with online work.
Develop mobile apps for learning new skills and certifications to help unemployed youth.
Launch crowdsourced work platforms where small tasks generate income for many.
Provide AI career guidance tools that suggest career paths based on skills and interests.
Guidelines:
Build smart systems that monitor roads, transport, and city infrastructure in real time.
Use IoT devices to track and improve supply chain efficiency.
Apply AI to factories to reduce errors and boost productivity.
Develop low-cost housing using 3D printing for fast and affordable homes.
Create marketplaces for eco-friendly construction materials.
Guidelines:
Build platforms that offer adaptive learning tools for differently-abled learners.
Create apps that let communities propose and vote on local development projects.
Develop tools to track and report income gaps across regions.
Provide online platforms for inclusive hiring and equal workplace opportunities.
Design apps for instant delivery of food, shelter, or aid to those in need.
Guidelines:
Develop smart transport apps that optimize routes, reduce wait times, and lower emissions.
Build platforms for citizens to share ideas and feedback on city planning.
Create apps that help households and cities separate and manage waste better.
Use AI to monitor and reduce air and noise pollution in cities.
Provide platforms that teach and connect people to urban farming practices.
Guidelines:
Guidelines:
Build platforms that make climate data easy to read and understand for everyone.
Create apps that encourage eco-friendly habits like recycling, biking, or saving energy.
Monitor climate indicators (temperature, storms, rainfall) in real time.
Provide trackers for households and businesses to measure and reduce energy use.
Use AI to predict disasters early and guide response plans.
Guidelines:
Guidelines:
Deploy drones to monitor and protect endangered species.
Use AI to spot deforestation early through satellite images.
Build platforms for sustainable farming and land use practices.
Create apps that track and showcase ongoing conservation projects.
Develop tools for predicting and preventing wildfires in forests.
Guidelines:
Build platforms that connect vulnerable people with free or affordable legal support.
Create transparency apps to show how public funds are being spent.
Develop apps where communities can report human rights abuses anonymously.
Provide online spaces that educate and advocate for justice and equality.
Use AI to monitor and improve peacekeeping operations worldwide.
Guidelines:
Build collaborative platforms that connect NGOs, governments, and businesses to work together.
Create crowdfunding platforms that channel funds into sustainable projects globally.
Provide secure data-sharing spaces where NGOs can collaborate transparently.
Use AI to measure and report progress on SDG targets in real time.
Develop platforms for sharing resources, skills, and technology across borders.
[Link]