Control Flow in Python

Control flow refers to the order in which individual statements, instructions, or function calls are executed or evaluated in a script. In Python, control flow is regulated by conditional statements, loops, and control statements. Understanding control flow is crucial as it allows developers to dictate the logic that their programs follow.

Conditional Statements (if, elif, else)

Python uses if, elif, and else statements to execute code based on one or more conditions being evaluated as True or False.

  • The if statement is used to test a condition and execute a block of code if the condition is True.
  • The elif (short for else if) statement is used to test additional conditions if the previous conditions were False.
  • The else statement is used to execute a block of code if all the preceding conditions are False.

Conditional Statements

# Conditional statements
age = 18
if age >= 18:
    print("You are an adult.")
elif age < 18 and age > 12:
    print("You are a teenager.")
else:
    print("You are a child.")
                


Logical Operators

Logical operators (and, or, not) are used to combine conditional statements:

  • and: Returns True if both conditions are true.
  • or: Returns True if at least one condition is true.
  • not: Returns True if the condition is false.

Loops (while, for)

Loops are used to repeatedly execute a block of code as long as a condition is met.

  • The while loop tells the computer to do something as long as the condition is True.
  • The for loop is used for iterating over a sequence (that is, a list, a tuple, a dictionary, a set, or a string).

while loop

# while loop
count = 0
while count < 5:
    print("The count is:", count)
    count += 1
                



for loop

# for loop
for i in range(5):
    print("The count is:", i)
                


Loop Control Statements (break, continue, pass)

Control statements change the execution from its normal sequence.

  • break: Used to terminate the loop entirely.
  • continue: Skips the rest of the current loop iteration and moves to the next iteration.
  • pass: Does nothing; it's used as a placeholder in areas where a statement is required syntactically, but no action needs to be performed.

break

# break
for num in range(10):
    if num == 5:
        break  # break here
    print("Number is " + str(num))
                



continue

# continue
for num in range(10):
    if num == 5:
        continue  # continue here
    print("Number is " + str(num))
                



pass

# pass
for num in range(10):
    if num == 5:
        pass  # pass here
    print("Number is " + str(num))