# All three uses of elsedeffind_and_process(data, target):
# try/else: handle import errorstry:
from math import sqrt
except ImportError:
print("No math module")
else:
print(f"sqrt available: {sqrt(16)}")
# for/else: search patternfor i, val inenumerate(data):
if val == target:
print(f"Found {target} at index {i}")
breakelse:
print(f"{target} not in data")
# if/else: process resultif target in data:
idx = data.index(target)
if idx % 2 == 0:
print("Found at even index")
else:
print("Found at odd index")
else:
print("Cannot process: not found")
find_and_process([10, 20, 30, 40], 30)
print()
find_and_process([10, 20, 30, 40], 99)
Output
Click "Run" to execute your code
Python uses 'else' in three contexts: if/else (condition), for-else/while-else (no break), and try/else (no exception). Each serves a different purpose.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?