DEV Community

Cover image for Beginner Python tips Day - 05 while...else, for...else
Paurakh Sharma Humagain
Paurakh Sharma Humagain

Posted on

3 2

Beginner Python tips Day - 05 while...else, for...else

# Python Day 05 - while....else, for...else

# else block in while and for loop is only executed
# if break statement is not executed inside for loop

my_list = ['Python', 'JavaScript', 'Dart', 'Golang', 'Rust']

# while else
index = 0
while index < len(my_list):
    if my_list[index] == 'PHP':
        result = 'Found PHP'
        break
    index += 1
else:
    result = 'PHP not found'

print(result)
# Prints 'PHP not found'
# else block in while loop is only executed
# if the break statement is not executed
# if the break statement is executed
# else block is not executed

# for else
for x in my_list:
    if x == 'C#':
        result = 'Found C#'
        break
else:
    result = 'C# not found'

print(result)
# Prints 'C# not found'
# same as while...else
# else is only executed if break is not executed

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay