Python - Else conditional statement inside a for loop


Python tip:

If your for loop includes a conditional statement, you can use an else statement in your loop. The else clause is executed if the loop is not terminated with a break statement.

def contains_number_bigger_than_1000(numbers_list):
    for number in numbers_list:
        if number > 1000:
            print("list CONTAINS a number bigger than 1000")
            break
    else:
        print("list DOES NOT contain a number bigger than 1000")


contains_number_bigger_than_1000([1, 200, 50])
# -> list DOES NOT contain a number bigger than 1000

contains_number_bigger_than_1000([1, 200, 5000])
# -> list CONTAINS a number bigger than 1000