Control Structures - SSS 2 Note

Control Structures - SSS 2 | CMPNOTE

CONTROL STRUCTURES

Subject: Digital Technologies
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:

  1. Use if-else statements to make decisions in simple programs.
  2. Apply loops to repetitive tasks.
  3. Create and use simple functions.
  4. 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.

Control structures are programming constructs that determine the order in which instructions are executed. They allow a program to make decisions, repeat instructions and organize tasks into reusable functions.

2. Decision-Making Using If-Else Statements

An if-else statement allows a program to choose between alternative actions depending on whether a condition is true or false.

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 else block executes when the preceding if condition is false and no earlier elif condition has been satisfied.
Remember: Indentation is important in Python. Instructions that belong to an if, else or elif block must be indented.

3. Introduction to Loops

A loop is a programming structure that repeats a block of instructions, either for a specified sequence or while a condition remains true.

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.

Warning: Always check the stopping condition of a loop. Update the necessary variables so that the loop can finish when intended.

4. Functions and Their Importance

A function is a named block of reusable code designed to perform a particular task.

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

  1. The function check_result() receives a student's score.
  2. The if-else statement checks whether the score is at least 50.
  3. The function returns an appropriate message.
  4. The for loop processes each score in the list.
  5. The program displays each score and its result.
Practical exercise: Change one of the scores in the list. Run the program and observe how the output changes. Then add another score to the list.

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

  1. What are control structures in programming?
  2. Explain the purpose of an if-else statement.
  3. Write a Python program that checks whether a number is positive or negative.
  4. What is a loop? Name two types of loops used in Python.
  5. Write a for loop that displays the numbers from 1 to 5.
  6. State four advantages of using functions.
  7. What is the difference between defining and calling a function?
  8. 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:

  1. Defines a function named check_number(number).
  2. Uses an if-else statement to check whether the number is even or odd.
  3. Returns or displays the appropriate message.
  4. Uses a for loop 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.

1. What is the main purpose of a control structure?

2. Which Python structure allows a program to choose between two alternatives?

3. Which keyword is used when defining a function in Python?

4. What is the output of this code?

for n in range(1, 4):
    print(n)

5. When does a while loop continue executing?

6. Which keyword can send a value back from a function?

7. What is one advantage of functions?

8. What is a likely result of forgetting to update a loop counter in some while loops?

9. What does the else block do in an if-else statement?

10. Which structure is most suitable for processing every item in a list?

Comments

Popular posts from this blog

Complete Computer Studies/ICT Curriculum for JSS 1 to SSS 3

90 Objective Examination Questions in Major Subjects

Number Base System