Python Programming Tutorial
Start your programming journey with Python - the most beginner-friendly programming language
Why Start with Python?
Python has become the most popular programming language for beginners worldwide, and for good reason. Its simple, readable syntax makes it perfect for those taking their first steps into programming. In Africa, where tech education is rapidly growing, Python offers an ideal entry point into the world of software development.
Python's versatility means you can use it for web development, data analysis, artificial intelligence, automation, and more. Many successful African tech companies, from fintech startups to agricultural platforms, use Python to power their applications.
"Python is the language that gets you thinking like a programmer faster than any other. It's perfect for African developers who want to start solving problems immediately."
- Adaora Onuigbo, Python Developer at Paystack
Setting Up Your Python Environment
Before we start coding, let's set up Python on your computer. Don't worry—it's easier than you might think!
Installing Python
Option 1: Download from Python.org (Recommended)
- Visit python.org
- Click "Download Python 3.x" (latest version)
- Run the installer and check "Add Python to PATH"
- Follow the installation prompts
Option 2: Using Anaconda (Great for Data Science)
- Visit anaconda.com
- Download Anaconda for your operating system
- Install—it comes with Python and many useful packages
Choosing a Code Editor
You'll need a good code editor. Here are some excellent free options:
- VS Code: Most popular, lots of extensions
- PyCharm Community: Designed specifically for Python
- Thonny: Simple and perfect for beginners
- IDLE: Comes built-in with Python
Testing Your Installation
Open your command prompt (Windows) or terminal (Mac/Linux) and type:
python --version
You should see something like "Python 3.9.7" or similar. If you see this, you're ready to start coding!
Your First Python Program
Let's start with the traditional "Hello, World!" program, but with an African twist:
# Your first Python program
print("Hello, Africa!")
print("Sannu, Africa!") # Hausa greeting
print("Sawubona, Africa!") # Zulu greeting
Save this in a file called hello_africa.py and run it by typing python hello_africa.py in your terminal.
Understanding the Code
#creates a comment—text that doesn't run but explains your codeprint()displays text on the screen- Text in quotes ("") is called a string
Python Basics: Variables and Data Types
Variables are containers that store data. In Python, creating variables is simple:
# Variables with African context
student_name = "Amara"
student_age = 22
student_country = "Nigeria"
is_studying_python = True
monthly_allowance = 50000.50 # Nigerian Naira
# Print variables
print("Student:", student_name)
print("Age:", student_age)
print("Country:", student_country)
print("Learning Python:", is_studying_python)
print("Monthly allowance: ₦", monthly_allowance)
Python Data Types
- String (str): Text data like
"Amara" - Integer (int): Whole numbers like
22 - Float: Decimal numbers like
50000.50 - Boolean (bool): True or False values
Working with Numbers: African Examples
Let's practice with numbers using scenarios relevant to African students and entrepreneurs:
# Small business calculations
product_price = 2500 # Price of a phone case in Naira
quantity_sold = 15
total_revenue = product_price * quantity_sold
print(f"Today we sold {quantity_sold} phone cases")
print(f"Each case costs ₦{product_price}")
print(f"Total revenue: ₦{total_revenue}")
# Calculate profit
cost_per_case = 1200
total_cost = cost_per_case * quantity_sold
profit = total_revenue - total_cost
print(f"Total cost: ₦{total_cost}")
print(f"Profit: ₦{profit}")
# Percentage profit
profit_percentage = (profit / total_cost) * 100
print(f"Profit percentage: {profit_percentage:.1f}%")
Python Arithmetic Operators
+Addition-Subtraction*Multiplication/Division**Exponentiation (power)%Modulus (remainder)
Working with Strings
Strings are crucial for handling text data. Let's explore them with African examples:
# Working with African names and languages
first_name = "Kwame"
last_name = "Asante"
full_name = first_name + " " + last_name # String concatenation
print("Full name:", full_name)
print("Name length:", len(full_name))
print("Uppercase:", full_name.upper())
print("Lowercase:", full_name.lower())
# F-strings (modern Python string formatting)
age = 25
country = "Ghana"
message = f"My name is {full_name}, I'm {age} years old and I'm from {country}"
print(message)
# Common African greetings
greetings = ["Habari", "Sawubona", "Sannu", "Bawo"]
for greeting in greetings:
print(f"{greeting}! How are you today?")
Useful String Methods
.upper()- Convert to uppercase.lower()- Convert to lowercase.strip()- Remove whitespace.replace()- Replace parts of the string.split()- Split string into a list
Lists: Storing Multiple Items
Lists let you store multiple items in a single variable. Perfect for managing data:
# African countries list
african_countries = ["Nigeria", "Kenya", "Ghana", "South Africa", "Egypt"]
print("African countries:", african_countries)
print("First country:", african_countries[0])
print("Last country:", african_countries[-1])
print("Number of countries:", len(african_countries))
# Adding to the list
african_countries.append("Morocco")
african_countries.append("Uganda")
print("Updated list:", african_countries)
# Mobile money services in different countries
mobile_money = {
"Kenya": "M-Pesa",
"Uganda": "MTN Mobile Money",
"Ghana": "MTN Mobile Money",
"Nigeria": "Paga",
"Rwanda": "Airtel Money"
}
print("Mobile money in Kenya:", mobile_money["Kenya"])
# Loop through countries
print("\nMobile money services:")
for country, service in mobile_money.items():
print(f"{country}: {service}")
List Operations
.append()- Add item to end.insert()- Add item at specific position.remove()- Remove specific item.pop()- Remove and return item.sort()- Sort the list
Making Decisions with If Statements
If statements let your program make decisions. Let's create a simple grade calculator:
# Student grade calculator (African grading system)
student_score = 85
if student_score >= 80:
grade = "A"
remark = "Excellent!"
elif student_score >= 70:
grade = "B"
remark = "Very Good"
elif student_score >= 60:
grade = "C"
remark = "Good"
elif student_score >= 50:
grade = "D"
remark = "Fair"
else:
grade = "F"
remark = "Fail"
print(f"Score: {student_score}")
print(f"Grade: {grade}")
print(f"Remark: {remark}")
# Multiple conditions
age = 20
has_id = True
is_nigerian = True
if age >= 18 and has_id and is_nigerian:
print("You can register to vote!")
else:
print("You cannot register to vote yet.")
# Checking mobile money limits
transaction_amount = 50000
daily_limit = 100000
account_balance = 75000
if transaction_amount <= account_balance and transaction_amount <= daily_limit:
print("Transaction approved!")
new_balance = account_balance - transaction_amount
print(f"New balance: ₦{new_balance}")
else:
print("Transaction failed - insufficient funds or exceeds daily limit")
Loops: Repeating Actions
Loops let you repeat code multiple times. Very useful for processing data:
For Loops
# Calculate total sales for a week
daily_sales = [12000, 15000, 8000, 20000, 18000, 25000, 22000]
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
total_sales = 0
for i in range(len(daily_sales)):
print(f"{days[i]}: ₦{daily_sales[i]}")
total_sales += daily_sales[i]
print(f"\nTotal weekly sales: ₦{total_sales}")
average_daily_sales = total_sales / len(daily_sales)
print(f"Average daily sales: ₦{average_daily_sales:.2f}")
# Processing student grades
students = ["Adaeze", "Kwame", "Fatima", "Kofi", "Amina"]
scores = [85, 92, 78, 88, 95]
print("\nStudent Results:")
for i in range(len(students)):
if scores[i] >= 80:
status = "Excellent"
elif scores[i] >= 70:
status = "Good"
else:
status = "Needs Improvement"
print(f"{students[i]}: {scores[i]} - {status}")
While Loops
# Savings goal calculator
savings_goal = 500000 # Half a million Naira
current_savings = 0
monthly_savings = 25000
months = 0
print(f"Savings goal: ₦{savings_goal}")
print(f"Monthly savings: ₦{monthly_savings}")
print()
while current_savings < savings_goal:
months += 1
current_savings += monthly_savings
print(f"Month {months}: ₦{current_savings}")
print(f"\nYou'll reach your goal in {months} months!")
Functions: Organizing Your Code
Functions help you organize code into reusable blocks. Let's create functions for common African business calculations:
# Function to convert currencies (simplified example)
def naira_to_dollars(naira_amount):
"""Convert Nigerian Naira to US Dollars"""
exchange_rate = 0.0013 # Simplified rate
dollars = naira_amount * exchange_rate
return dollars
def dollars_to_naira(dollar_amount):
"""Convert US Dollars to Nigerian Naira"""
exchange_rate = 770 # Simplified rate
naira = dollar_amount * exchange_rate
return naira
# Function to calculate mobile money fees
def calculate_mpesa_fee(amount):
"""Calculate M-Pesa transaction fee (simplified)"""
if amount <= 100:
fee = 0
elif amount <= 500:
fee = 5
elif amount <= 1000:
fee = 10
elif amount <= 1500:
fee = 15
elif amount <= 2500:
fee = 25
else:
fee = 35
return fee
# Function to greet in different African languages
def african_greeting(name, language="english"):
"""Greet someone in different African languages"""
greetings = {
"english": f"Hello, {name}!",
"swahili": f"Habari, {name}!",
"hausa": f"Sannu, {name}!",
"yoruba": f"Bawo, {name}!",
"zulu": f"Sawubona, {name}!"
}
return greetings.get(language.lower(), greetings["english"])
# Using the functions
print("Currency Conversion:")
naira_amount = 100000
dollar_equivalent = naira_to_dollars(naira_amount)
print(f"₦{naira_amount} = ${dollar_equivalent:.2f}")
print("\nM-Pesa Fee Calculator:")
transaction_amount = 1200
fee = calculate_mpesa_fee(transaction_amount)
total_cost = transaction_amount + fee
print(f"Sending KES {transaction_amount}")
print(f"Fee: KES {fee}")
print(f"Total cost: KES {total_cost}")
print("\nMultilingual Greetings:")
name = "Amara"
for language in ["english", "swahili", "hausa", "yoruba"]:
greeting = african_greeting(name, language)
print(greeting)
Building a Practical Project: Student Grade Manager
Let's combine everything we've learned to build a simple student grade management system:
# Student Grade Management System
students_data = []
def add_student(name, math, english, science):
"""Add a new student with their scores"""
total = math + english + science
average = total / 3
if average >= 80:
grade = "A"
elif average >= 70:
grade = "B"
elif average >= 60:
grade = "C"
elif average >= 50:
grade = "D"
else:
grade = "F"
student = {
"name": name,
"math": math,
"english": english,
"science": science,
"total": total,
"average": round(average, 2),
"grade": grade
}
students_data.append(student)
print(f"Added {name} to the system")
def display_student(name):
"""Display a specific student's information"""
for student in students_data:
if student["name"].lower() == name.lower():
print(f"\nStudent: {student['name']}")
print(f"Math: {student['math']}")
print(f"English: {student['english']}")
print(f"Science: {student['science']}")
print(f"Total: {student['total']}")
print(f"Average: {student['average']}")
print(f"Grade: {student['grade']}")
return
print(f"Student {name} not found")
def display_all_students():
"""Display all students"""
if not students_data:
print("No students in the system")
return
print("\n" + "="*50)
print("ALL STUDENTS")
print("="*50)
for student in students_data:
print(f"{student['name']:<15} | Average: {student['average']:<6} | Grade: {student['grade']}")
def get_class_statistics():
"""Calculate and display class statistics"""
if not students_data:
print("No students to analyze")
return
total_students = len(students_data)
all_averages = [student["average"] for student in students_data]
class_average = sum(all_averages) / total_students
highest_score = max(all_averages)
lowest_score = min(all_averages)
print(f"\nCLASS STATISTICS")
print(f"Total students: {total_students}")
print(f"Class average: {class_average:.2f}")
print(f"Highest average: {highest_score}")
print(f"Lowest average: {lowest_score}")
# Adding sample students
add_student("Adaeze Okafor", 85, 78, 92)
add_student("Kwame Asante", 72, 85, 80)
add_student("Fatima Ibrahim", 95, 88, 90)
add_student("Kofi Mensah", 68, 75, 72)
add_student("Amina Hassan", 88, 92, 85)
# Display results
display_all_students()
get_class_statistics()
display_student("Fatima Ibrahim")
Working with Files
Let's learn to read and write files—essential for real applications:
# Writing student data to a file
def save_students_to_file():
"""Save all student data to a text file"""
with open("students.txt", "w") as file:
file.write("STUDENT GRADE REPORT\n")
file.write("="*40 + "\n")
for student in students_data:
file.write(f"Name: {student['name']}\n")
file.write(f"Math: {student['math']}, English: {student['english']}, Science: {student['science']}\n")
file.write(f"Average: {student['average']}, Grade: {student['grade']}\n")
file.write("-" * 30 + "\n")
print("Student data saved to students.txt")
# Reading from a file
def read_african_countries():
"""Read a list of African countries from a file"""
countries = []
try:
with open("african_countries.txt", "r") as file:
for line in file:
countries.append(line.strip())
return countries
except FileNotFoundError:
print("File not found. Creating sample file...")
# Create a sample file
sample_countries = ["Nigeria", "Kenya", "Ghana", "South Africa", "Egypt", "Morocco", "Uganda", "Tanzania"]
with open("african_countries.txt", "w") as file:
for country in sample_countries:
file.write(country + "\n")
return sample_countries
# Working with CSV files (great for data analysis)
def create_student_csv():
"""Create a CSV file with student data"""
import csv
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Math", "English", "Science", "Average", "Grade"])
for student in students_data:
writer.writerow([
student["name"],
student["math"],
student["english"],
student["science"],
student["average"],
student["grade"]
])
print("Student data saved to students.csv")
# Use the functions
save_students_to_file()
create_student_csv()
countries = read_african_countries()
print("African countries:", countries[:5]) # Show first 5
Error Handling
Good programs handle errors gracefully. Let's learn the basics:
# Safe number input
def get_safe_number_input(prompt):
"""Get a number from user with error handling"""
while True:
try:
number = float(input(prompt))
return number
except ValueError:
print("Please enter a valid number!")
# Safe division
def safe_divide(a, b):
"""Safely divide two numbers"""
try:
result = a / b
return result
except ZeroDivisionError:
print("Cannot divide by zero!")
return None
except TypeError:
print("Please provide numbers only!")
return None
# File handling with error checking
def read_file_safely(filename):
"""Read a file with proper error handling"""
try:
with open(filename, "r") as file:
content = file.read()
return content
except FileNotFoundError:
print(f"File '{filename}' not found!")
return None
except PermissionError:
print(f"Permission denied to read '{filename}'!")
return None
# Example usage
print("Safe Division Examples:")
print(safe_divide(10, 2))
print(safe_divide(10, 0))
print(safe_divide("10", 2))
Next Steps: Where to Go from Here
Congratulations! You've learned Python fundamentals. Here's your roadmap for continued learning:
Immediate Next Steps (Weeks 1-4)
- Practice Daily: Solve problems on platforms like HackerRank, Codewars, or LeetCode
- Build Projects: Create simple applications like calculators, to-do lists, or data analyzers
- Learn Git: Version control is essential for all developers
- Join Communities: Python Nigeria, PyCon Africa, or local Python meetups
Intermediate Learning (Months 2-6)
- Web Development: Learn Django or Flask for building web applications
- Data Analysis: Master pandas, NumPy, and matplotlib for data science
- APIs: Learn to work with external services and create your own APIs
- Databases: Understand SQL and database integration
Specialization Options
Web Development:
- Django for full-stack development
- FastAPI for modern API development
- HTML, CSS, JavaScript for frontend
Data Science/AI:
- pandas and NumPy for data manipulation
- matplotlib and seaborn for visualization
- scikit-learn for machine learning
- TensorFlow or PyTorch for deep learning
Automation/DevOps:
- Selenium for web automation
- Ansible for infrastructure automation
- Docker for containerization
Building African Solutions with Python
As an African developer, you have unique opportunities to solve local problems:
Project Ideas for African Context
- SMS-based applications: Many Africans still use feature phones
- Mobile money integrations: Payment systems for local businesses
- Agricultural tools: Weather data, crop monitoring, market prices
- Healthcare applications: Appointment systems, health tracking
- Education platforms: Learning tools adapted for local curricula
- Transportation: Route optimization, ride-sharing systems
Resources for African Python Developers
- Python Nigeria: Active community with regular meetups
- PyCon Africa: Annual conference for African Python developers
- Django Girls: Workshops for women learning Django
- PyLadies Africa: Community supporting women in Python
Common Mistakes to Avoid
Learn from common beginner mistakes:
- Not practicing regularly: Code every day, even if just for 30 minutes
- Trying to memorize everything: Focus on understanding concepts
- Not reading error messages: They usually tell you exactly what's wrong
- Skipping the basics: Strong fundamentals are crucial
- Not asking for help: Use online communities when stuck
- Comparing yourself to others: Everyone learns at their own pace
Conclusion: Your Python Journey Begins
Congratulations on completing this Python tutorial! You've learned the fundamental concepts that form the foundation of all programming. From variables and data types to functions and file handling, you now have the tools to start building real applications.
Remember, becoming proficient in Python (or any programming language) is a journey, not a destination. The key is consistent practice and building projects that interest you and solve real problems.
As an African developer, you have the opportunity to create solutions that address unique local challenges while building skills that are valuable globally. Whether you're interested in web development, data science, artificial intelligence, or automation, Python provides a solid foundation for all these paths.
At Axtrivex Technologies, we're committed to supporting African developers on their programming journey. Through our academy programs, mentorship initiatives, and community partnerships, we provide resources and guidance to help you succeed in technology.
Your coding journey starts now. Take what you've learned, start building, keep practicing, and don't be afraid to make mistakes—they're how we learn. The African tech ecosystem needs skilled developers like you to build the solutions that will transform our continent.
Happy coding, and welcome to the world of Python programming!