Control Statements
Control statements in Python determine the flow of execution based on conditions or repetitions. This chapter introduces the concept of loops and how we can manipulate the flow of loops using control statements.
Sometimes we want to repeat a set of statements in our program. For instance: Print 1 to 1000. A loop allows us to repeat a block of code multiple times. Instead of writing the same code again and again, loops help automate tasks by iterating over sequences (like lists, tuples, dictionaries, etc.) or running until a specific condition is met.
Types of Loops
Section titled “Types of Loops”| Loop Type | Description |
|---|---|
| While Loop | Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body. |
| For Loop | Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. |
While Loop
Section titled “While Loop”The while loop in Python is used when we want to execute a block of code as long as a condition is true.
Syntax:
while condition: # Code block to be executedExample:
i = 1while i < 5: print(i) i += 11234Explanation:
- The condition
i < 5is checked before each iteration. - As long as the condition is true, the code block inside the loop is executed.
iis incremented by 1 in each iteration.
Note: If the condition never becomes false, the loop keeps getting executed, making it an INFINITE LOOP.
INFINITE LOOP
Section titled “INFINITE LOOP”An infinite loop occurs when the loop's condition is always true and never becomes false. This leads to the loop running endlessly. Such loops should be used cautiously, as they can cause programs to freeze or crash.
Example of Infinite Loop:
while True: print("This is an infinite loop!")To break out of an infinite loop, we typically use a break statement, which we will cover later.
FOR LOOP
Section titled “FOR LOOP”The for loop in Python provides the ability to loop over the items of any sequence, such as a list, tuple, or a string.
Syntax:
for item in sequence: # Code block to be executedExample:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits: print(fruit)applebananacherryTHE range() FUNCTION
Section titled “THE range() FUNCTION”The range() function generates a sequence of numbers, which is often used with loops. It is particularly useful for generating a series of numbers in a for loop.
Syntax:
range(start, stop, step)start: The starting number (default is 0).stop: The end number (exclusive).step: The difference between each number in the sequence (default is 1).
Example:
for i in range(1, 6): print(i)12345Iterating by Sequence Index
Section titled “Iterating by Sequence Index”Sometimes we need to iterate over both the index and the value of a sequence. We can achieve this using the range() function combined with len().
Example:
fruits = ["apple", "banana", "cherry"]for i in range(len(fruits)): print(f"Index: {i}, Value: {fruits[i]}")Index: 0, Value: appleIndex: 1, Value: bananaIndex: 2, Value: cherryFor Loop with Else
Section titled “For Loop with Else”If an else block is used with a for loop, it is executed only when the for loop terminates normally (i.e., not by a break statement).
Example:
l = [1, 7, 8]
for item in l: print(item)else: print("done") # This is printed when the loop exhausts!178doneNested Loops
Section titled “Nested Loops”A nested loop is a loop inside another loop. The inner loop runs completely for each iteration of the outer loop.
Syntax:
for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)Example:
for i in range(1, 10): for j in range(1, 10): k = i * j print(k, end=' ') print()1 2 3 4 5 6 7 8 92 4 6 8 10 12 14 16 183 6 9 12 15 18 21 24 274 8 12 16 20 24 28 32 365 10 15 20 25 30 35 40 456 12 18 24 30 36 42 48 547 14 21 28 35 42 49 56 638 16 24 32 40 48 56 64 729 18 27 36 45 54 63 72 81Output:
LOOP CONTROL STATEMENTS
Section titled “LOOP CONTROL STATEMENTS”Loop control statements change the flow of a loop from its normal behavior. Python provides three main loop control statements:
| Control Statement | Description |
|---|---|
| Break Statement | The break statement terminates the loop immediately and the control flows to the statement after the body of the loop. |
| Continue Statement | The continue statement terminates the current iteration of the statement, skips the rest of the code in the current iteration and the control flows to the next iteration of the loop. |
| Pass Statement | The pass keyword in Python is generally used to fill up empty blocks and is similar to an empty statement represented by a semi-colon in languages such as Java, C++, JavaScript. |
Break Statement
Section titled “Break Statement”The break statement is used to exit the loop before it has iterated through all items or before the condition becomes false. When break is executed, the loop terminates immediately.
Example:
for i in range(1, 6):if i == 3: breakprint(i)12Explanation: The loop stops as soon as i becomes 3, due to the break statement.
Continue Statement
Section titled “Continue Statement”The continue statement is used to skip the rest of the code inside the loop for the current iteration and move to the next iteration.
Example:
for i in range(1, 6):if i == 3: continueprint(i)1245Explanation: When i is 3, the continue statement is executed, which skips printing 3 and moves to the next iteration.
Pass Statement
Section titled “Pass Statement”- The
passstatement does nothing and is used as a placeholder. - It is useful when you need a loop but do not want to execute any code inside the loop at the moment.
- The
passkeyword in Python is generally used to fill up empty blocks and is similar to an empty statement represented by a semi-colon in languages such as Java, C++, and Javascript.
Example:
for i in range(1, 6): pass # Without pass, the program will throw an errorIn this case, nothing will be executed, but the loop is syntactically correct.