0
0
Pythonprogramming~15 mins

While–else behavior in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
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 0
Use 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 break
Use an else clause on the while loop to print No number divisible by 7 found if loop completes without break
Increment 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
1
Create the list of numbers
Create a list called numbers with these exact values: [10, 13, 22, 35, 40]
Python
Need a hint?

Use square brackets [] to create a list and separate values with commas.

2
Set up the index variable
Create a variable called index and set it to 0
Python
Need a hint?

Use = to assign the value 0 to the variable index.

3
Write the while loop with else
Write a while loop with the condition index < len(numbers). Inside the loop, check if numbers[index] % 7 == 0. If true, print Found a number divisible by 7: {numbers[index]} and use break. Increment index by 1 inside the loop. Add an else clause on the while loop that prints No number divisible by 7 found.
Python
Need a hint?

Remember the else after a while runs only if the loop did not break.

4
Run the program to see the output
Run the program and print the output. The program should print Found a number divisible by 7: 35.
Python
Need a hint?

If you see this output, your program works correctly!