2 Upvotes

Python For Else Loop

Python
General Python

An example of using a For Else loop.

In this code snippet a For loop iterates through a list of city names and checks if any match the string in the new_city variable. If the loop is exhausted then this triggers the else clause.

cities = ['London','New York','Paris']
new_city = 'Madrid'

for city in cities:
    if new_city == city:
        print('City in list')
        break
else:
    print('City not in list')

By detro - Last Updated Aug. 29, 2021, 2:12 p.m.

Did you find this snippet useful?

Sign up to bookmark this in your snippet library

COMMENTS
RELATED SNIPPETS
Top Contributors
103
100