For Loop
A for loop is used for iterating over a sequence which can be a list, tuple, dictionary, set, or a string. Iterating is also known as traversing. Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.
Syntax
for val in sequence: # do something with val
Example
# list numbers = range(1,10, 2) for number in numbers: print(number) # string message = "Hello World" for character in message: print(f'char: {character}') # tuple """ id, person info """ person = tuple(('12345',{"name":"Folau","grade":"3.5"})) for p in person: print(p) # set names = set(('Folau','Lisa','Mele')) for name in names: print(name) #dictionary profile = dict(name="Folau",age=30,job="SWE") for attr in profile: print(attr)
The for loop does not require an indexing variable to set beforehand.
With the break statement we can stop the loop before it has looped through all the items. The example below stops its execution when count is 3.
numbers = range(1,10, 2) count = 0; for number in numbers: print(number) if count == 3: break count++
With the continue statement we can stop the current iteration of the loop, and continue with the next. The example below shows that when number is 0 the program will throw an error but instead of terminating the program it should keep going til the end of the list.
numbers = range(1,10, 2) for number in numbers: print(number) try: result = 12 / number except: continue
for
loops cannot be empty, but if you for some reason have a for
loop with no content, put in the pass
statement to avoid getting an error.
numbers = range(1,10, 2) for number in numbers: pass
else statement with for loop
We can use else statement with for loop to execute some code when the for loop is finished. It’s useful in logging or sending a notification when the processing of a sequence is successfully completed.
teams = ['Lakers','Jazz','Suns'] for team in teams: print(team) else: print("done looping through teams")
Reverse iteration using reversed function
The for loop iterates through the sequence elements in the order of its occurrence. Sometimes we have to iterate through the elements in the reverse order. We can use reversed() function with the for loop to achieve this.
numbers = (1, 2, 3, 4, 5) for num in reversed(numbers): print(num)
While Loop
while loop is used to repeat a block of code until the specified condition is False. It is used when we don’t know the number of times the code block has to execute. We should take proper care in writing while loop condition if the condition never returns False, the while loop will go into the infinite loop. Every object in Python has a boolean value. If the value is 0 or None, then the boolean value is False. Otherwise, the boolean value is True. We can define an object boolean value by implementing __bool__()
function. We use the reserved keyword – while – to implement the while loop in Python. We can terminate the while loop using the break statement. We can use continue statement inside while loop to skip the code block execution. Python supports nested while loops.
Syntax
while condition: # while body else: # else body
Example
count = 0 while count < 10: print(count) count+=1 else: print("done counting!")
Python for loop and while loops are enough to create any type of loops. We can use the break and continue statements to control the loop execution flow. You can also use the “else” block for logging successful execution of the loops.