Loops
Loops
Loops allows the lines of code to run over and over again
for Loops
-
Iterable - list, dictionary, tuple, set, string An iterable is any Python object capable of returning its elements one at a time.
-
Iterate -> one by one check each item in the collection
for loops allow us to iterate over anything that has a collection of items
for item in 'Zero':
print (item) #creates a variable, givies iterable item Z e r o
Nested Loops
for item in (1,2,3,4,5):
for x in ('a', 'b', 'c'): #nesting in loop
print(item, x)
Loops using Dict
- .items() → key-value pairs
- .keys() → keys only
- .values() → values only
user = {
'name': 'marwa',
'age': 22,
'can_swim': True
}
for i in user.items(): #.items(), .keys(), .values()
print(i)
for key, value in user.items(): # Tuple unpacking
print(key, value)
Range in Loops
range(start, stop, step) generates numbers.
for i in range (10,): #Output: print numbers 1 to 9, it also has stepover option
print(i) #range(start, stop, stepover)2, 4, 6, 8
A negative step makes the loop count backwards.
for i in range(10, 0, -1):
print(i) # Output: 10, 9, 8, ..., 1
Using strings & list
for _ in range (10):
print('email list') #prints email list 10 times
for _ in range (2): #creates loop of 2 list until 10
print(list(range(10)))
Enumerate in Loops
- enumerate() adds an index while looping.
- It is used to loop over an iterable (like a list, tuple, or string) while keeping track of the index of each item.
for i, char in enumerate('hellloooo'):
print(i, char) #we are unpacking, and access the index number of each item
for i, char in enumerate([1,2,3,4,5,6]):
print(i, char)
while Loop
- Executes while condition is True.
While is a loop statement that repeatedly executes a block of code as long as a given condition is True.
count = 1
while count <= 5: # Loop runs while condition is True
print(count)
count += 1 # Increment to avoid infinite loop or you can use break
else:
print('done') #else will only execute if there isn't a break
myList1 = [1,2,3]
for i in myList1:
print(i) #with for loop
i=0
while i < len(myList1):
print(myList1[i])
i+= 1 #with while loop
break, continue, pass
- break → exits loop.
- continue → skips current iteration.
- pass → placeholder, does nothing.
break in loop
while True:
response = input('say something: ')
if (response == 'bye'):
break
continue in loop
- Skips rest of the code in the current iteration and moves to the next iteration of the loop.
- With a continue, what we're saying is, hey, whatever happens when you hit this line, continue onto the top of the enclosing loop.
for i in range(5):
if i == 2:
continue # Skip when i is 2
print(i)
pass in loop
- One of those placeholders that we can use so that there is a line of code that does absolutely nothing but we can still pass through.