Search⌘ K
AI Features

Loops

Explore Python loops to repeatedly execute code blocks using for and while loops. Understand the range() function and discover list comprehensions for creating lists concisely, helping you manage and analyze data efficiently.

Loops allow us to repeatedly execute sets of statements for as long as a given condition remains True. There are two kinds of loops in Python, for and while.

The while loop

Before executing the statement (or statements) that is nested in the body of the loop, Python keeps evaluating the test expression (loop test) until the test returns a False value. Let’s start with a simple while loop in the cell below:

Python 3.5
# A simple while loop
i = 1 # initializing a variable i = 1
while i < 5: # loop test
# Run the block of code (given below), till "i < 5"
print('The value of i is: {}'.format(i)) # from your previous lecture, recall the placeholder in the print statement with the format() method!
i = i+1 # increase i by one for each iteration

If the i = i + 1 statement is removed, the loop becomes infinite because the condition never changes. This behavior is typically unintended.

Note: A nicer and cleaner way of exiting the while loop is by using the else statement (optional).

Python 3.5
i=1
while i < 5:
print('The value of i is: {}'.format(i))
i = i+1
else:
print('Exit loop')

The for loop

The for loop is a loop that we use very frequently. The for statement works on strings, lists, tuples, and other built-in iterables, as well as on new user-defined objects.

Let’s create a list my_list of numbers and run a for loop using that list. In a very simple situation, we can execute a block of code using a for loop for every single item ...