Python Control Structures

Control structures allow you to manage the flow of your Python program. They help you make decisions, repeat tasks, and control loop execution. This lesson will cover:

  • Operators: Perform operations on values.

  • If, Else, and Elif Statements: Conditional statements for decision-making.

  • For-loop and While-loop Statements: Repeating code execution.

  • Control Flow Statements: Adjusting loop behavior using break, continue, and pass.

Operators

Python supports various operators that allow you to manipulate data and evaluate conditions.

Arithmetic Operators:

These perform basic mathematical operations.

  • + : Addition

  • – : Subtraction

  • * : Multiplication

  • / : Division

  • ** : Exponentiation

  • % : Modulus (remainder after division)

  • // : Floor division (integer division, without remainder)

Example:

x = 10
y = 3

print(x + y)   # 13
print(x - y)   # 7
print(x * y)   # 30
print(x / y)   # 3.333...
print(x % y)   # 1
print(x // y)  # 3

Comparison Operators:

These are used to compare two values and return True or False.

  • == : Equal to

  • != : Not equal to

  • > : Greater than

  • < : Less than

  • >= : Greater than or equal to

  • <= : Less than or equal to

Example:

x = 5
y = 10

print(x == y)   # False
print(x != y)   # True
print(x < y)    # True
print(x > y)    # False

Logical Operators:

These are used to combine conditional statements.

  • and : Returns True if both statements are true.

  • or : Returns True if one of the statements is true.

  • not : Reverses the result.

Example:

x = 5
y = 10

print(x > 3 and y < 15)  # True
print(x < 3 or y > 15)   # False
print(not(x == y))       # True

If, Else, and Elif Statements

These conditional statements are used to control the flow of execution based on conditions. Python evaluates conditions and executes the corresponding block of code.

Syntax:

if condition1:
    # Code to execute if condition1 is True
elif condition2:
    # Code to execute if condition1 was False and condition2 is True
else:
    # Code to execute if all conditions are False

Example:

age = 20

if age < 18:
    print("You are a minor.")
elif age == 18:
    print("You are exactly 18 years old.")
else:
    print("You are an adult.")

Explanation:

The if block executes if the first condition (age < 18) is true.

The elif block executes if the if condition is false but the second condition (age == 18) is true.

The else block executes if none of the conditions are true.

For-loop and While-loop Statements

Loops allow you to repeat blocks of code multiple times.

For-loop

A for loop is used to iterate over a sequence such as a list, tuple, dictionary, string, or range of numbers. The loop runs once for each item in the sequence.

Looping through a List:

islands = ["Luzon", "Visayas", "Mindanao"]

for island in islands:
    print(island)

Explanation:

The loop iterates over each item in the islands list and prints it.


Looping through a String:

word = "Philippines"

for letter in word:
    print(letter)

Explanation:

The loop iterates over each character in the string word and prints it.


Looping through a Dictionary:

person = {"name": "Maria", "age": 25, "city": "Cebu"}

for key, value in person.items():
    print(f"{key}: {value}")

Explanation:

The loop iterates through each key-value pair in the person dictionary and prints them.


Using range() in For-loops

The range() function generates a sequence of numbers, often used in for-loops. It can take up to three arguments: start, stop, and step.

Basic Range Example:

for i in range(5):  # Iterates from 0 to 4
    print(i)

Explanation:

The loop runs for each number in the range from 0 to 4.


Specifying Start, Stop, and Step:

for i in range(2, 10, 2):  # Iterates from 2 to 8, stepping by 2
    print(i)

Explanation:

The loop starts at 2, increments by 2 each time, and stops before reaching 10.


While-loop

A while loop executes as long as a given condition is true. If the condition never becomes false, the loop will continue indefinitely (becoming an “infinite loop”).

Syntax:

while condition:
    # Code to execute while the condition is True

Example:

count = 1

while count <= 5:
    print("Count:", count)
    count += 1

Explanation:

The loop will keep executing as long as count <= 5 is true. The count variable increments on each iteration.

Control Flow Statements: break, continue, and pass

break Statement

The break statement immediately terminates the loop, regardless of the loop condition.

Syntax:

for variable in sequence:
    if condition:
        break
    # Other code to execute

Example:

for number in range(10):
    if number == 5:
        break
    print(number)

Explanation:

The loop stops when number equals 5, even though the loop was designed to run until 9.


continue Statement

The continue statement skips the current iteration and moves to the next iteration of the loop.

Syntax:

for variable in sequence:
    if condition:
        continue
    # Code to execute if condition is not met

Example:

for number in range(5):
    if number == 2:
        continue
    print(number)

Explanation:

The number 2 is skipped, and the loop continues with the next iteration.


pass Statement

The pass statement is a null operation. It does nothing and is used as a placeholder when a statement is syntactically required but you don’t want to execute any code.

Syntax:

if condition:
    pass
else:
    # Code to execute if condition is False

Example:

for number in range(3):
    if number == 1:
        pass  # Placeholder
    else:
        print(number)

Explanation:

When number equals 1, the pass statement is executed, which does nothing, and the loop continues.

Scroll to Top