Translate

Monday, October 13, 2025

PP_Control Structures

Control structures in programming are essential components that dictate the sequence in which a program operates. Conditional statements represent a category of control structure that enables a program to make choices depending on the truth value of a condition. There are three major types of control structures: Sequential, selection, and repetition structures

1. Sequential Structure

Sequential structures execute code in a linear (top-to-bottom) order. Every line is executed once and in sequence.

2. Selection Structure

On the contrary, selection structures allow a program to make decisions. A block of code is executed only if a certain condition is met. The most common examples are if, elif, and else statements.

Examples 1: The if Statement

Syntax:

if condition:

  # Code executed if the condition is True (indented)

  # This code block must be indented

Example 1: If statement

age = 20

if age >= 20:

  print("You are not a teenager.")

 

Example 2: The else Statement

Unlike the if statement, the if-else statement provides an alternative block of code that is executed when the if condition is False.

Syntax:

if condition:

  # Code to be executed if the condition is True

else:

  # Code to be executed if the condition is False

Example:

age = 20

 

if age >= 20:

  print("You are nolonger a teenager.")

else:

  print("You look younger.")

Example 3: The elif Statement

Else if (elif) allows checking multiple conditions sequentially and executes as soon as it finds a True condition and skips the rest.

Syntax:

if condition1:

  # Code for condition1

elif condition2:

  # Code for condition2

elif condition n:

  # Code for condition n

else:

  # Code for all other cases

  • elif blocks to be executed (These codes are, however, optional and is the final catch it all).

Example:

grade = 80

if grade >= 90:

  print("A")

elif grade >= 80:

  print("B")

elif grade >= 70:

  print("C")

elif grade >= 60:

  print("D")

else:

  print ("retake for post graduate level")

3. Repetition Structure (Loops)

While repetition structures allow a program to execute a block of code multiple times, a loop repeatedly executes a block of code until a specific condition is no longer met.  Examples include the while loop and, for loop.

Example:

is_raining = True

temperature = 15 degrees F

if is_raining:

  print("stay indoor.")

  if temperature > 20:

    print("turn off the air conditioner.")

  else:

    print("We can move out.")

else:

  print("Move out at will.")

 

 

 


Question 1 of X

No comments:

Post a Comment