Mada za sehemu hiiCreating basic programsMada 3
- Performing exploration of basic programming constructs
- Implementing handling of user inputs and outputs
- Using basic libraries for data science
Basic Programming Constructs
Programming is the process of giving a computer a set of instructions to perform a task. To write effective programs, programmers use programming constructs — the basic building blocks that control how a program runs. In this topic, we will explore four fundamental constructs: variables, data types, conditionals, and loops.
A variable is a named storage location in computer memory that holds a value which can change during program execution. Think of a variable as a labeled box where you store information.
Key Points
- Variables have a name that you choose (e.g.,
price,quantity,total) - Variables store data that can be used and modified in your program
- In Python, you create a variable by assigning a value using the
=operator
Worked Example
# Creating variables in Python
price = 5000 # Price of an item in Tanzanian shillings (TSH)
quantity = 3 # Number of items
discount = 0.1 # 10% discount rate
In this example:
priceis a variable storing5000quantityis a variable storing3discountis a variable storing0.1
Data types specify the type of data that a variable can hold. Understanding data types helps the computer process information correctly.
Common Data Types
| Data Type | Description | Example |
|---|---|---|
int (integer) | Whole numbers | 25, 100, -5 |
float | Decimal numbers | 3.14, 1500.50 |
str (string) | Text or characters | "Hello", "Tanzania" |
bool (boolean) | True or False | True, False |
Worked Example
# Variables with different data types
item_name = "Mango" # str - string (text)
price = 500 # int - integer (whole number)
weight = 2.5 # float - decimal number
in_stock = True # bool - boolean (True/False)
print(item_name, price, weight, in_stock)
Conditional statements allow a program to make decisions based on certain conditions. The most common is the if statement.
How If Statements Work
if condition:
# execute this block if condition is True
else:
# execute this block if condition is False
Worked Example
A shopkeeper in Dar es Salaam wants to give a discount if a customer buys more than 10 items:
quantity = 15
price_per_item = 2000
if quantity > 10:
total = quantity * price_per_item * 0.9 # 10% discount
print("Discount applied!")
else:
total = quantity * price_per_item
print("Total payable:", total, "TSH")
Output:
Discount applied!
Total payable: 27000000 TSH
The program checks if quantity > 10. Since it is true (15 > 10), it applies the discount.
Extended Conditionals with elif
score = 75
if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
elif score >= 50:
grade = "C"
else:
grade = "Fail"
print("Your grade is:", grade)
Loops allow a program to repeat a block of code multiple times. This is useful when you need to process many items or perform the same task repeatedly.
4.1 For Loop
A for loop iterates over a sequence (like a list or range of numbers).
# Print numbers 1 to 5
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
4.2 While Loop
A while loop repeats as long as a condition remains True.
# Countdown from 5
count = 5
while count > 0:
print(count)
count = count - 1
print("Go!")
Output:
5
4
3
2
1
Go!
Worked Example
A market vendor in Arusha wants to calculate the total sales for 5 days:
total_sales = 0
for day in range(1, 6):
daily_sale = int(input(f"Enter sales for day {day}: "))
total_sales = total_sales + daily_sale
print("Total weekly sales:", total_sales, "TSH")
When learning programming, you must be able to analyze code for both functionality and errors.
Common Errors to Look For
- Syntax errors — missing colons, parentheses, or quotes
- Indentation errors — code not aligned correctly in Python
- Logic errors — code runs but gives wrong results
- Type errors — using data types incorrectly (e.g., adding text to a number)
Practice: Find the Bug
# This code has an error
price = 1000
tax = 0.18
total = price + tax
if total > 5000:
print("Expensive item")
else
print("Affordable item")
What is wrong? The else statement is missing a colon (:).
Corrected version:
price = 1000
tax = 0.18
total = price + tax
if total > 5000:
print("Expensive item")
else:
print("Affordable item")
- Variables store data that can change during program execution
- Data types define what kind of data a variable holds (int, float, str, bool)
- Conditionals (if/elif/else) let programs make decisions
- Loops (for/while) let programs repeat actions efficiently
- Always check your code for syntax errors, indentation errors, and logic errors
In Tanzania, small business owners use basic programming constructs to manage their shops. For example, a duka owner in Mwanza can write a simple Python program to calculate profit by using variables to store the cost price and selling price, conditionals to check if the profit meets a target, and loops to process daily sales records — all using Tanzanian shillings. This helps them make better decisions about pricing and inventory.
Jinsi utakavyotathminiwaTathmini ya mchakato · Tathmini ya matokeo · Tathmini ya maarifa
Tathmini ya mchakato
- The student should be able to:
- Use of correct syntax for variables, loops, and conditionals.
- Identify andcorrect logical errors in code.
Tathmini ya matokeo
A functional Python script showcasing proper use of variables, conditionals, and loops.
Tathmini ya maarifa
Detailed knowledge of:
Method used: The student should explain:
- Step-by-step explanation of Python basics (syntax, semantics).
Principles: The student should explain the principles of:
- clean and efficient coding practices.
Theories: The student should explain:
- basic concepts and applications of Python programming language
- data types and variables in Python
- flow control (sequential, conditional, iterative).
Circumstantial knowledge:
Detailed knowledge about:
- debugging computer programs.
Swali
Which statement correctly describes what a variable is in programming?
Ingia ili kuwasilisha jibu lako na lihesabiwe katika umahiri wako.
Ingia ili kufanya mazoeziMwalimu
Umekwama? Niulize chochote kuhusu mada hii.
Ingia ili kumuuliza Mwalimu wa AI wa Sonza kuhusu swali hili.
Ingia ili kuulizaMajadiliano
Hakuna maswali bado