Control Structures - SSS 2 Note
CONTROL STRUCTURES
Class: SSS 2
Term: Second Term
Week: 4
Topic: Control Structures
Duration: 80 Minutes (Double Period)
Learning Objectives
By the end of the lesson, students should be able to:
- Use
if-elsestatements to make decisions in simple programs. - Apply loops to repetitive tasks.
- Create and use simple functions.
- Apply control structures to solve simple programming problems.
1. Introduction to Control Structures
In programming, instructions are written to tell a computer what to do. Some programs execute instructions one after another, while others must make decisions, repeat actions or perform a particular task whenever it is needed.
For example, a school program may need to determine whether a student has passed an examination. A counting program may need to display numbers from 1 to 10. A calculator may need to perform the same calculation whenever a user supplies new values.
2. Decision-Making Using If-Else Statements
Programs often need to make decisions based on values, scores, ages or other conditions. In Python, the if statement checks a condition, while else provides an alternative when that condition is false.
2.1 The If Statement
An if statement executes its indented block only when its condition is true.
score = 75
if score >= 50:
print("You passed.")
Output:
You passed.
The program checks whether the score is at least 50. Since 75 is greater than 50, the message is displayed.
2.2 The If-Else Statement
An if-else statement provides two alternative paths.
score = 42
if score >= 50:
print("You passed.")
else:
print("You did not pass.")
Output:
You did not pass.
Because the score is below 50, Python executes the instructions under else.
2.3 The If-Elif-Else Structure
When a program must choose from more than two possibilities, Python provides elif, meaning "else if".
score = 78
if score >= 70:
print("Grade A")
elif score >= 60:
print("Grade B")
elif score >= 50:
print("Grade C")
else:
print("Below grade C")
Output:
Grade A
Python checks the conditions from top to bottom and executes the first block whose condition is true. The grade boundaries in this example are illustrative.
2.4 Important Rules for If-Else Statements
- A condition normally uses comparison operators such as
==,>,<,>=or<=. - A colon (
:) follows the condition. - The instructions inside each block must be indented correctly.
- The
elseblock executes when the precedingifcondition is false and no earlierelifcondition has been satisfied.
if, else or elif block must be indented.
3. Introduction to Loops
Loops reduce the need to write the same instruction many times. They are useful for counting, processing lists, displaying repeated messages and performing calculations on several values.
3.1 The For Loop
A for loop repeats instructions for each item in a sequence. It is commonly used when the items or number of repetitions are known.
for number in range(1, 6):
print(number)
Output:
1
2
3
4
5
The function range(1, 6) generates the numbers 1 to 5. The ending value, 6, is not included.
3.2 The While Loop
A while loop repeats a block of instructions as long as its condition remains true.
count = 1
while count <= 5:
print(count)
count = count + 1
Output:
1
2
3
4
5
The variable count begins at 1. After each repetition, it increases by 1. When it reaches 6, the condition becomes false and the loop stops.
3.3 Difference Between For and While Loops
| For Loop | While Loop |
|---|---|
| Iterates through a sequence or range of values. | Repeats while a condition is true. |
| Often suitable when the sequence or number of repetitions is known. | Often suitable when repetition depends on a changing condition. |
| Example: displaying numbers from 1 to 5. | Example: repeating an action until a condition becomes false. |
3.4 Avoiding Infinite Loops
An infinite loop occurs when a loop continues without reaching its stopping condition. In a while loop, this can happen when the condition remains true because the relevant variable is never updated.
4. Functions and Their Importance
Functions help programmers organize a program into smaller, manageable parts. Instead of rewriting the same instructions, a programmer can define a function once and call it whenever it is needed.
4.1 Importance of Functions
- Code reuse: A function can be called many times without rewriting its instructions.
- Organization: Functions divide a large program into smaller tasks.
- Readability: Meaningful function names help explain what a program does.
- Maintenance: Updating a function can improve every part of a program that uses it.
- Testing: Smaller functions can be checked separately.
4.2 Defining and Calling a Function
In Python, the keyword def is used to define a function.
def greet():
print("Welcome to programming!")
greet()
Output:
Welcome to programming!
The first part defines the function named greet. The statement greet() calls the function and executes its instructions.
4.3 Functions With Parameters
A parameter allows a function to receive information that it can use to perform a task.
def greet_student(name):
print("Welcome,", name)
greet_student("Ada")
greet_student("Chika")
Output:
Welcome, Ada
Welcome, Chika
The parameter name receives a different value each time the function is called.
4.4 Functions That Return Values
A function can use return to send a result back to the part of the program that called it.
def add_numbers(a, b):
return a + b
answer = add_numbers(10, 5)
print(answer)
Output:
15
The function adds the two numbers and returns the result. The program stores that result in answer and displays it.
5. Applying Control Structures to Simple Programs
Decision-making, loops and functions can be combined to solve practical problems. The following example checks scores for several students using a loop and a decision structure.
def check_result(score):
if score >= 50:
return "Pass"
else:
return "Needs improvement"
scores = [75, 42, 60, 35]
for score in scores:
result = check_result(score)
print("Score:", score, "-", result)
Expected output:
Score: 75 - Pass
Score: 42 - Needs improvement
Score: 60 - Pass
Score: 35 - Needs improvement
Explanation of the Program
- The function
check_result()receives a student's score. - The
if-elsestatement checks whether the score is at least 50. - The function returns an appropriate message.
- The
forloop processes each score in the list. - The program displays each score and its result.
6. Common Errors When Using Control Structures
| Error | Example | Correction |
|---|---|---|
| Missing colon | if score >= 50 |
Write if score >= 50:. |
| Incorrect indentation | The instruction under if is not indented. |
Indent the instruction inside the block. |
| Loop condition never becomes false | A counter is not updated in a while loop. |
Update the counter or other relevant condition. |
| Function is defined but never called | def greet(): is written without greet(). |
Call the function when its task is needed. |
| Incorrect function arguments | A function expects two arguments but receives one. | Supply the required arguments or revise the function definition. |
7. Summary
Control structures determine how a program executes its instructions. The if-else structure allows a program to make decisions. Loops, including for and while, repeat instructions. Functions group instructions into reusable blocks and can accept parameters or return values. Combining these structures helps programmers develop organized and useful programs.
8. Evaluation Questions
- What are control structures in programming?
- Explain the purpose of an
if-elsestatement. - Write a Python program that checks whether a number is positive or negative.
- What is a loop? Name two types of loops used in Python.
- Write a
forloop that displays the numbers from 1 to 5. - State four advantages of using functions.
- What is the difference between defining and calling a function?
- Explain how a function, an if-else statement and a loop can work together in a program.
9. Assignment
Write a Python program that performs the following tasks:
- Defines a function named
check_number(number). - Uses an
if-elsestatement to check whether the number is even or odd. - Returns or displays the appropriate message.
- Uses a
forloop to test the numbers 1, 2, 3, 4 and 5.
10. Interactive Revision Quiz
Select one answer for each question, then click Mark Quiz to see your score.
Comments
Post a Comment