Loops
Explore the fundamentals of Python loops including for and while loops, along with list comprehensions. Understand their syntax and practical use cases to automate repetitive coding tasks and generate lists efficiently, which are essential skills for data analysis and programming.
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:
In the code above, what if we don’t have the i = i+1 statement? Well, as per the rules of the while loop, we’ll get into an infinite while loop. But that is not what we want…
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 ...