Understanding While-else Behavior in Python
📖 Scenario: Imagine you are checking a list of numbers to find if any number is divisible by 7. You want to know if you found such a number or if none exists.
🎯 Goal: You will write a Python program that uses a while loop with an else clause to check numbers and print a message depending on whether a divisible number is found.
📋 What You'll Learn
Create a list called
numbers with the exact values: [10, 13, 22, 35, 40]Create a variable called
index and set it to 0Use a
while loop with the condition index < len(numbers)Inside the loop, check if
numbers[index] is divisible by 7 using %If divisible, print
Found a number divisible by 7: <number> and breakUse an
else clause on the while loop to print No number divisible by 7 found if loop completes without breakIncrement
index by 1 inside the loop💡 Why This Matters
🌍 Real World
Checking lists or data for specific conditions and knowing if none matched is common in data processing and validation.
💼 Career
Understanding loop control and the <code>else</code> clause helps in writing clear and efficient code for tasks like searching, filtering, and error checking.
Progress0 / 4 steps