web-profile

Python for loop

nums = [1, 2, 3, 4, 5]

print('Traditional loop with N steps:')
for num in range(5):
    print(num)

print('Loop thru all items in the list:')
for num in nums:
    print(num)

print('Loop thru dictionary:')
dict = {'name': 'Alex', 'age': 35, 'phone': '555-7777'}
for dict_key in list(dict.keys()):
    print(dict_key, dict[dict_key])

print('Break the for loop:')
# 1 2 Skipped
for num in nums:
    if num == 3:
        print('Skipped 3 and break the loop')
        break
    print(num)

print('Skip the step and continue the for loop:')
# 1 2 Skipped 4 5
for num in nums:
    if num == 3:
        print('Skipped 3 and continue the loop')
        continue
    print(num)

Leave a Reply

Your email address will not be published.