Categories

Chapter 2.2: Loops – For and While

Understanding and using loops (for, while)

In Python, loops are used to repeatedly execute a block of program statements. The two types of loops in Python are the for loop and the while loop.

The for Loop

The for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) or other iterable objects. Iterating over a sequence is called traversal.

Here’s a simple example of a for loop:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

In this example, fruit is the loop variable that takes each value in the fruits list. The block of code within the loop (here, the print statement) is executed once for each item in the list.

You can also combine for loops with range() function:

for i in range(5):
    print(i)

The range() function generates a sequence of numbers from 0 up to (but not including) the number specified as the parameter (in this case, 5).

The while Loop

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.

Here’s a simple example of a while loop:

i = 0

while i < 5:
    print(i)
    i += 1

In this example, the print statement will be executed as long as i is less than 5. We then increment i by 1 after each loop iteration. If we didn’t do this, i would always be 0, the condition would always be true, and the loop would run forever, creating an infinite loop.

Remember, the loop variable (i in this case) needs to be defined before the loop is started, and you should make sure that something changes from iteration to iteration so that the loop condition will eventually become false. Otherwise, the loop will run forever, creating an infinite loop.

Loop Control Statements

Loop control statements change the normal sequence of flow in loop iterations. Python supports the following control statements:

  • break statement: Terminates the loop statement and transfers execution to the statement immediately following the loop.
  • continue statement: Causes the loop to skip the remainder of its body and immediately start the next iteration.
  • pass statement: The pass statement in Python is used when a statement is required syntactically, but you do not want any command or code to execute.

That’s the basic introduction to for and while loops in Python. These looping structures are among the most important constructs in programming. They give us the power to repeat certain operations, which can be particularly useful when working with large collections of data.

Leave a Reply

Your email address will not be published. Required fields are marked *