loading...
Cover image for Beginner Python tips Day - 05 while...else, for...else

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

paurakhsharma profile image Paurakh Sharma Humagain ・1 min read
# 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

Discussion

markdown guide