Learn Python 3 - Loops Cheatsheet - Codecademy
Learn Python 3 - Loops Cheatsheet - Codecademy
Loops
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!
/
The Python continue Keyword
In Python, the continue keyword is used inside a
loop to skip the remaining code inside the loop code big_number_list = [1, 2, -1, 4, -5, 5, 2,
block and begin the next loop iteration. -9]
Infinite Loop
An infinite loop is a loop that never terminates. Infinite
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.
/
Python while Loops
In Python, a while loop will repeatedly execute a
code block as long as a condition evaluates to True .
# This loop will only run 1 time
hungry = True
The condition of a while loop is always checked first
while hungry:
before the block of code runs. If the condition is not met
initially, then the code block will never run. print("Time to eat!")
hungry = False