Control Flow: The for Loops

for else Structure

A for loop will repeat the statements inside the block of that loop as many times as the loop specifies. However, execution flow of the loop statements can be altered by using special keywords break and continue.

The break statement can be used to stop repeating the loop immediately. Code execution will continue with the first statement following the loop body.

The continue statement will cause the loop to repeat the loop body with the next iteration, immediately abandoning the remaining code statements in the current iteration of the loop. 

iteration_count = 0
max_value = int(input("Please enter the max value:"))

#Also try for 50 and 51 and assess why the else part is executed.

for number in range(max_value):

    if number % 2 == 0:
        # Skip the remaining code in the loop for even numbers
        continue

    if number >= 50:
        # Exit the loop immediately
        break

    iteration_count += 1

    if number % 5 == 0:
        print(number * 100)
    else:
        print(number)

    print ("Iteration: ", iteration_count)

else:
    print("The loop executed completely without encountering the break statement")

An optional else block may be appended to the end of a for block to be executed if the for block was not interrupted by any break statement.