for i in "python":
print(i)
#> p
#> y
#> t
#> h
#> o
#> n
7 Loop
7.1 For Loop
Common iterables that can be used in loop:
range
str
: iterate through each characterslist
for i in [1, 2]:
print(i)
#> 1
#> 2
range()
is very helpful
range(start, stop, step)
start
is inclusionstop
is exclusive
type(range(1))
#> <class 'range'>
list(range(2))
#> [0, 1]
list(range(1, 3))
#> [1, 2]
list(range(1, 10, 2))
#> [1, 3, 5, 7, 9]
for number in range(3):
print(number)
#> 0
#> 1
#> 2
for number in range(1, 4):
print("Attempt: ", number, number * ".")
#> Attempt: 1 .
#> Attempt: 2 ..
#> Attempt: 3 ...
7.1.1 For else
The break
statement, breaks out of the innermost enclosing for
or while
loop
else
is executed when the loop terminates through exhaustion of the iterable, but not when the loop is terminated by a break statement.
From: Ref
= False
successful
for number in range(1, 4):
print("Attempt: ", number)
if successful:
print("Success")
break
else:
print("Attempt 3 times and failed")
#> Attempt: 1
#> Attempt: 2
#> Attempt: 3
#> Attempt 3 times and failed
7.1.2 Nested Loop
for x in range(3):
for y in range(2):
print(f"({x},{y})")
#> (0,0)
#> (0,1)
#> (1,0)
#> (1,1)
#> (2,0)
#> (2,1)
= 0
count
for n in range(1, 10):
if (n % 2) == 0:
print(n)
+= 1
count #> 2
#> 4
#> 6
#> 8
print(f"We have {count} even numbers")
#> We have 4 even numbers
10 % 2
#> 0
10 % 3
#> 1
7.1.3 Enumerate
= ["vanilla", "chocolate", "pecan", "strawberry"] flavor_list
Using range(len())
for i in range(len(flavor_list)):
= flavor_list[i]
flavor print(f"{i + 1}: {flavor}")
#> 1: vanilla
#> 2: chocolate
#> 3: pecan
#> 4: strawberry
Using enumerate()
(better)
for i, flavor in enumerate(flavor_list):
print(f"{i + 1}: {flavor}")
#> 1: vanilla
#> 2: chocolate
#> 3: pecan
#> 4: strawberry
- Prefer enumerate instead of looping over a range and indexing into a sequence.
- You can supply a second, optional parameter to enumerate that specifies the beginning number for counting (zero is the default).
7.2 While Loop
= 100
number while number > 0:
//= 2
number print(number)
#> 50
#> 25
#> 12
#> 6
#> 3
#> 1
#> 0