SHREYA SARVAN MASANAM’s Post

𝗗𝗮𝘆 𝟭𝟴: 𝗳𝗼𝗿–𝗲𝗹𝘀𝗲 𝗶𝗻 𝗣𝘆𝘁𝗵𝗼𝗻 In Python, a loop can have an else block. The else runs only if the loop finishes normally, meaning it was not stopped using break. Basic structure: for i in range(5): print(i) else: print("Loop completed") output: 0 1 2 3 4 Loop completed Since there is no break, the else block executes. Now look at this: for i in range(5): if i == 3: break else: print("Loop completed") output: 0 1 2 Here, else will not execute because the loop stopped early using break. Real-world Example: Searching for an element numbers = [2, 4, 6, 8] for num in numbers: if num == 5: print("Found") break else: print("Not Found") output:Not Found If 5 is not in the list, the loop completes fully, and else runs. Why is this useful? • Searching operations • Validation checks • Avoiding extra flag variables • Without for-else, many beginners use a flag variable to track results. • With for-else, Python handles it cleanly. Important: • else runs only if no break occurs • Works with both for and while loops It’s a small concept, but it makes your code more elegant and readable. #Python #LearnPython #CodingJourney #Programming

  • diagram

To view or add a comment, sign in

Explore content categories