0% found this document useful (0 votes)
214 views

Loops Cheatsheet

A for loop in Python is used to iterate over the elements of a list and perform an action on each element. The basic syntax of a for loop assigns each element in the list sequentially to a temporary variable. The body of the for loop is indented and the statements inside the body will be executed once for each element. The range() function can be used to iterate a specific number of times. Keywords like break and continue can be used to control the flow of the for loop. Nested for loops allow iterating over elements of nested lists. List comprehensions provide a concise way to create lists from expressions involving existing lists.

Uploaded by

Pranay Bagde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
214 views

Loops Cheatsheet

A for loop in Python is used to iterate over the elements of a list and perform an action on each element. The basic syntax of a for loop assigns each element in the list sequentially to a temporary variable. The body of the for loop is indented and the statements inside the body will be executed once for each element. The range() function can be used to iterate a specific number of times. Keywords like break and continue can be used to control the flow of the for loop. Nested for loops allow iterating over elements of nested lists. List comprehensions provide a concise way to create lists from expressions involving existing lists.

Uploaded by

Pranay Bagde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Cheatsheets / Learn Python 3

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)

Python for Loops


Python for loops can be used to iterate over and
perform an action one time for each element in a list. dog_breeds = ["boxer", "bulldog", "shiba inu"]
Proper for loop syntax assigns a temporary value, the
current item of the list, to a variable on each successive # Print each breed:
iteration: for <temporary value> in <a for breed in dog_breeds:
list>: print(breed)

for loop bodies must be indented to avoid an


IndentationError .

Python Loops with range().


In Python, a for loop can be used to perform an action
a speci c number of times in a row. # Print the numbers 0, 1, 2:
The range() function can be used to create a list that for i in range(3):
can be used to specify the number of iterations in a print(i)
for loop.
# Print "WARNING" 3 times:
for i in range(3):
print("WARNING")

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!

The Python continue Keyword


In Python, the continue keyword is used inside a loop
to skip the remaining code inside the loop code block big_number_list = [1, 2, -1, 4, -5, 5, 2, -9]
and begin the next loop iteration.
# Print only positive numbers:
for i in big_number_list:
if i < 0:
continue
print(i)

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 rst
before the block of code runs. If the condition is not met
while hungry:
initially, then the code block will never run. print("Time to eat!")
hungry = False

# This loop will run 5 times


i = 1
while i < 6:
print(i)
i = i + 1

/
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.

# This outer loop will iterate over each list


in the groups list
for group in groups:
# This inner loop will go through each name
in each list
for name in group:
print(name)

Python List Comprehension


Python list comprehensions provide a concise way for
creating lists. It consists of brackets containing an # List comprehension for the squares of all
expression followed by a for clause, then zero or more for even numbers between 0 and 9
or if clauses: [EXPRESSION for ITEM in LIST <if result = [x**2 for x in range(10) if x % 2 ==
CONDITIONAL>] . 0]
The expressions can be anything - any kind of object can
go into a list. print(result)
A list comprehension always returns a list. # [0, 4, 16, 36, 64]

You might also like