Python For Loops, While Loops, Enumerate, and Range
2020-07-25 09:18:01 | | Part 5 of 7
Tested On
- Linux Ubuntu 20.04
- Windows 10
- macOS Catalina
-
Part 4 of 7
‹ Python Dictionaries and JSON -
Part 6 of 7
Python Yield, Generators, and Generator Expressions ›
Loops give us the power to repeat a process as many times as needed. Loops are very fast and we can design them to be very efficient.
Let's say you wanted to go through 50,0000 books and collect only the ones that were published in the 1950s. Imagine having to manually go through each book cover to check the publishing information. This would take weeks. A loop can complete this operation in seconds.
How to Set Up a Project Skeleton
How to Create a Python Project with Windows 10 PowerShell 2.0+
cd ~
New-Item -ItemType "directory" -Path ".\python-fundamentals"
cd python-fundamentals
New-Item -ItemType "file" -Path . -Name "main.py"
virtualenv venv
.\venv\Scripts\activate
To verify that the virtual environment is active, make sure (venv) is in the PowerShell command prompt. For example, (venv) PS C:\Users\username\python-fundamentals>
How to Create a Python Project with Linux Ubuntu 14.04+ or macOS
cd ~
mkdir python-fundamentals
cd python-fundamentals
virtualenv -p python3 venv
source venv/bin/activate
touch main.py
To verify that the virtual environment is active, make sure (venv) is in the terminal command prompt.
This will create the following files and folders, and activate the virtual environment.
▾ python-fundamentals/
▸ venv/
main.py
Python For Loop
The following example demonstrates a basic for...in loop, when we loop through each element and perform an operation. In this case, we are simply printing the element to the console.
Try It Yourself
Controlling a Python For Loop with Continue and Break
The following examples demonstrate how to control the iteration steps of a loop. In example 1, we use a conditional to only print colors with the letter 'a' in them. In example 2, we use the continue statement to skip colors with the letter 'a' in them. In other words, if a color has 'a' in it, continue to the next element. In example 4, we break out of the loop if the color equals 'blue'. This is useful for when you find the element your looking for and no longer need to use computing resources to check the rest of the elements. In example 4, we use an else statement to indicate when we're finished looping through all of the elements.
Try It Yourself
Nested For Loops with Python
The following example shows us how to use nested loops to iterate through multiple lists to form combinations of values. Now we're beginning to see the power of loops in automating tasks that would normally take a lot of time and effort.
Try It Yourself
Up until now, we've only been exposed to one-dimensional lists; one dimension, meaning from left to right where each element is one position/column of the list. But we can also use nested for loops to iterate through multidimensional lists (lists that have rows, as well as columns):
Try It Yourself
Python Enumerate
Sometimes, we want to keep a count of iterations to know how far along the loop is. We can use enumerate to return the count, as well as the element. In the example 1, we tell the loop to break out after we reach the fifth element. In example 2, we use the count to print every other element of the list.
Try It Yourself
Python Range
Another way of controlling which elements we iterate through is with the range() function. range() accepts a number or range of numbers that we can use to indicate the range of elements.
Try It Yourself
Python While Loop
A Python while loop allows keep executing some code as long as a condition is true. For example:
Try It Yourself
Here's another example of a Python while loop, where we keep printing random numbers until 7 is generated.
Try It Yourself
Python Programming Exercises
Try to solve the following problems, using everything you've learned up to this point. Feel free to share solutions in the comments. Optimize each solution, as much as possible.
-
Write a Python loop that returns all the numbers between 1 and 100 that are divisible by 5
Input: None
Expected Output: [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
-
Write a Python function that accepts an integer, and returns a list of that integer's multiplication table
Input: 2
Expected Output: [2, 4, 6, 8 , 10 , 12, 14, 16, 18, 20]
Input: 4
Expected Output: [4, 8, 12, 16, 20, 24, 28, 32, 36, 40]
-
Write a Python loop that iterates over a list and produces a new list with the duplicates removed
Input: [1, 1, 2, 3, 4, 4, 5, 6, 7, 8, 8, 9]
Expected Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
-
Write a Python loop that iterates over a list and produces a new list that contains any value that has appeared more than once
Input: [1, 1, 2, 3, 4, 4, 5, 6, 7, 8, 8, 9]
Expected Output: [1, 4, 8]
-
Write a Python loop that puts the elements of this multidimensional list into a linear list
Input: [[0, 1], [1, 1], [2, 1]]
Expected Output: [0, 1, 1, 1, 2, 1]
Conclusion
That's the end of this tutorial. We hope you found it helpful. Make sure to check out our other tutorials, as well.
-
Part 4 of 7
‹ Python Dictionaries and JSON -
Part 6 of 7
Python Yield, Generators, and Generator Expressions ›
Comments
You must log in to comment. Don't have an account? Sign up for free.
Subscribe to comments for this post
Info