Loops Cheatsheet
Loops Cheatsheet
Loops
Python For Loop
A Python for loop can be used to iterate over a list of
items and perform a set of actions on each item. The for <temporary variable> in <list variable>:
syntax of a for loop consists of assigning a temporary <action statement>
value to a variable on each successive iteration. <action statement>
When writing a for loop, remember to properly indent
each action, otherwise an IndentationError will
#each num in nums will be printed below
result. nums = [1,2,3,4,5]
for num in nums:
print(num)
In nite Loop
An in nite loop is a loop that never terminates. In nite
loops result when the conditions of the loop prevent it
from terminating. This could be due to a typo in the
conditional statement within the loop or incorrect logic.
To interrupt a Python program that is running forever,
press the Ctrl and C keys together on your
keyboard.
/
break Keyword
In a loop, the break keyword escapes the loop,
regardless of the iteration number. Once break
numbers = [0, 254, 2, -1, 3]
executes, the program will continue to execute after the
loop. for num in numbers:
In this example, the output would be: if (num < 0):
print("Negative number detected!")
●
0 break
● print(num)
254
●
2 # 0
●
Negative number detected! # 254
# 2
# Negative number detected!
/
Python Nested Loops
In Python, loops can be nested inside other loops. Nested
loops can be used to access items of lists which are inside groups = [["Jobs", "Gates"], ["Newton",
other lists. The item selected from the outer loop can be "Euclid"], ["Einstein", "Feynman"]]
used as the list for the inner loop to iterate over.