Refresh your memory of Python loop statements and functions with this cheat sheet.
For a more guided walkthrough, check out the resources section at the bottom of this page. Each listed tutorial provides step-by-step directions, examples, and exercises to practice your skills.
Loop type | Explanation |
---|---|
For loop | An iterating function used to execute statements repeatedly. |
While loop | Used to iterate over code when the condition is true. This loop type is typically used when the number of times you’ll need to repeat is unknown. |
Nested loop | A loop inside of a loop. The innermost loop will execute once for each outer loop iteration. |
Do while loop | A variant of the while loop that checks the condition at the end of the loop rather than the beginning. The statements inside the loop body will be executed at least once. Python does not have a built-in do while loop but you can modify a while loop to achieve the same functionality. |
A Python while loop only runs when the condition is met. Since it checks that condition at the beginning, it may never run at all. To modify a while loop into a do while loop:
True
after the keyword while
so that the condition is always true to begin with.if
statements to check the inside condition and break
statements to control the flow of the loop based on your terms.Here’s an example:
Code | Explanation |
---|---|
if | if is a common conditional statement. If statements in Python dictate whether a statement should be executed or not by checking for a given condition. If the condition is true, the if block of code will be executed. |
else | The else statement contains the block of code that will execute if the condition from the if statement is false or resolves to zero. |
break | A break statement terminates the loop that contains it and redirects the program flow to the following statement. |
continue | You can use the keyword continue to end a for loop’s current iteration and continue on to the next. |
pass | In Python, pass does nothing. It can be used as a placeholder or to disregard code. |
range() | Python’s range function returns a sequence of numbers. By default, the range starts at 0 and increments in steps of 1. |
items() | A method of retrieving the key and its corresponding value simultaneously when looping through a dictionary. |
list() | A list is a mutable sequence type. When used as a function, it takes an iterable and creates a list object. |
reversed() | reversed() is a built-in Python function that returns a reverse iterator. |
enumerate() | Enumerate is a built-in function. It adds a counter to an iterable (like a list) and returns it as an enumerate object. |
This content has been made available for informational purposes only. Learners are advised to conduct additional research to ensure that courses and other credentials pursued meet their personal, professional, and financial goals.