Python Day 11: Practicing While Loops with Real-Life Examples

Python Day 11: Practicing While Loops with Real-Life Examples

1. Display the Same Number Five Times Problem: A teacher asks five students to stand in a line. Each student wears a badge with the number 1. Display the badge numbers from left to right. Without a loop print(1, end=' ') print(1, end=' ') print(1, end=' ') print(1, end=' ') print(1, end=' ') Enter fullscreen mode Exit fullscreen mode With a while loop count = 1 while count = 0: print(count_down, end=' ') count_down = count_down - 2 Enter fullscreen mode Exit fullscreen mode Output: 10 8 6 4 2 0 Enter fullscreen mode Exit fullscreen mode Here, we use decrement instead of increment because the countdown moves backwards. Key Takeaways A loop is used to repeat an action. while executes as long as its condition is True. Initialization sets the starting value. The condition decides when the loop stops. Increment increases a value. Decrement decreases a value. Always update the loop variable to avoid an infinite loop. Remember: Don't try to think about the entire output at once. Understand the next step, dry-run the program, and gradually build the complete logic.

Original Source

Read the full article at Dev →

KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.