FOR LOOPS
Python by Computer G
THE FOR LOOP
A for loop is used for iterating over a sequence (that is either a
list, a tuple, a dictionary, a set, or a string).
Example Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Note: Remember to increment i, or else
the loop will continue forever
BREAK STATEMENT
With the break statement we can stop the loop before it has looped
through all the items:
Example Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
CONTINUE STATEMENT
With the continue statement we can stop the current iteration of
the loop, and continue with the next:
Example Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue print(x)
THE RANGE() FUNCTION
To loop through a set of code a specified number of times, we can
use the range() function
Example Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
Thanks For Watching