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.
We'll cover the following...
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:
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
whileloop is by using theelsestatement (optional).
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 ...