Structured Programming in Python: Syntax, Logic, and Flow
In Weeks 1 through 7, we explored the electronic hardware, number systems, and micro-architectural cycles that power a computer.
Now, we bridge hardware theory with software reality by programming in Pythonโone of the world's most versatile, expressive, and in-demand programming languages, used globally for artificial intelligence, web development, robotics, and scientific research.
In this lesson, we will master type casting, build dynamic input/output programs, implement multi-way decision branching, and construct counted and conditional loops.
Learning Outcomes
By the end of this lesson, you will be able to:
- Write clean Python code adhering to standard 4-space indentation rules.
- Accept user input and perform Type Casting (
int(),float()). - Construct multi-way decision trees with
if,elif, andelse. - Implement repetition using
forloops andwhileloops.
Key Vocabulary
| Term | Technical Role |
|---|---|
| Syntax | The strict grammar and spelling rules of a programming language. |
| Type Casting | Explicitly converting a value from one data type to another (e.g., converting text "25" to integer 25). |
| Indentation | The whitespace spaces at the beginning of a code line that define block structure in Python. |
for Loop |
A counted loop that iterates over a sequence or range of numbers. |
while Loop |
A conditional loop that repeats as long as a boolean condition remains True. |
Study Notes: Core Python Control Structures
INPUT AND TYPE CASTING:
Keyboard Input: "15" (String) ===( int() )===> 15 (Integer ready for math!)
DECISION STRUCTURE:
if condition_1:
[ Execute Block 1 ]
elif condition_2:
[ Execute Block 2 ]
else:
[ Default Fallback Block ]
COUNTED ITERATION (FOR LOOP):
for i in range(1, 6): <-- Runs for i = 1, 2, 3, 4, 5
print(i * 10)
1. The Critical Rule of input() and Type Casting
When you ask a user for their age using input(), Python captures their keystrokes as a String:
# BROKEN CODE:
age = input("Enter your age: ")
next_year = age + 1 # FAILS! TypeError: cannot add string to integer!
To perform arithmetic, you must type cast the string into an integer:
# CORRECT CODE:
age_str = input("Enter your age: ")
age = int(age_str)
next_year = age + 1
print("Next year you will be:", next_year)
Or concisely in a single line:
2. Multi-Way Decisions: if-elif-else
When evaluating multiple mutual conditions, chain them using elif (short for else-if):
score = int(input("Enter exam score (0-100): "))
if score >= 75:
print("Grade: A - Excellent")
elif score >= 60:
print("Grade: B - Very Good")
elif score >= 50:
print("Grade: C - Credit")
elif score >= 40:
print("Grade: D - Pass")
else:
print("Grade: F - Fail")
3. Repetition: for and while Loops
The for Loop (Counted Repetition):
Use for when you know in advance how many times an action should repeat:
# Print the 5 times multiplication table up to 5 x 6:
for multiplier in range(1, 7):
result = 5 * multiplier
print(f"5 x {multiplier} = {result}")
The while Loop (Conditional Repetition):
Use while when an action should repeat until a condition changes:
# A countdown timer:
count = 5
while count > 0:
print(count)
count = count - 1
print("Blastoff! Rocket launches into orbit!")
Worked Example: A Solar Inverter Energy Budget Calculator
Let us write a complete, practical Python script for a Nigerian home solar installation:
# Solar Energy Budget Calculator
print("=== KINSPIRE SOLAR INVERTER SIZER ===")
fan_watts = int(input("Enter total wattage of fans: "))
light_watts = int(input("Enter total wattage of lights: "))
tv_watts = int(input("Enter total wattage of television: "))
total_load = fan_watts + light_watts + tv_watts
print(f"Total Home Electrical Load: {total_load} Watts")
if total_load > 2000:
inverter_recommendation = "3.5 kVA Inverter (24V System)"
elif total_load > 1000:
inverter_recommendation = "2.0 kVA Inverter (24V System)"
else:
inverter_recommendation = "1.0 kVA Inverter (12V System)"
print(f"Recommended System: {inverter_recommendation}")
Notice: Clear variable names, explicit int() type casting, and structured decision branching!
Practical Class Activity: The Number Guessing Game
Type and run the following interactive Python script on your computer:
secret_number = 7
guess = 0
print("Welcome to the Number Guessing Game!")
print("I am thinking of a secret number between 1 and 10.")
while guess != secret_number:
guess = int(input("Take a guess: "))
if guess < secret_number:
print("Too low! Try a higher number.")
elif guess > secret_number:
print("Too high! Try a lower number.")
else:
print("Congratulations! You found the secret number 7!")
Common Mistakes & Corrections
| Common Mistake | Why It Is Incorrect | Proper Correction |
|---|---|---|
| "Forgetting to type-cast user input before mathematical comparison." | Comparing strings to numbers ('15' > 10) causes runtime TypeError. |
Always wrap numeric input in int() or float(). |
| "Inconsistent indentation (e.g., 2 spaces on line 2 and 5 spaces on line 3)." | Python enforces strict block indentation; mismatched spaces cause IndentationError. |
Always use 4 consistent spaces for indented code blocks. |
Notebook Summary
Copy Into Your Computing Notebook
- Use
input()to accept user input; always type cast numbers usingint()orfloat(). - Decision logic:
if,elif, andelsedefine mutually exclusive execution branches. - Indentation (4 spaces) defines code block membership in Python.
- Use
forloops withrange()for counted iteration; usewhileloops for conditional iteration.