Lecture-29 while-true 24-25
COMP101 Introduction to Programming 2024-25
Lecture 29: While-True
Page 1: Introduction to While-True
Focus on While-True loops in programming.
Page 2: Understanding While-True Loops
While Loops: Execute code blocks as long as a specified Boolean expression is
True.Boolean Expression: Initially set to
True. The goal is for the programmer to change it toFalseto terminate the loop.Infinite Loop: If there is no provision to make the expression
False, the loop will run indefinitely.Break Statement: Often used in conjunction with an
ifstatement to exit the loop when a certain condition is met.
Page 3: Coding an Infinite Loop
Example Code: A code snippet to find the sum of the first 10 numbers:
numberInSet = 10 sum = 0 while True: sum = sum + numberInSet numberInSet = numberInSet - 1 print("Sum of First 10 Numbers is", sum)Intuition: The structure of
while Truemight be confusing; it requires clarity on the condition under which it runs. Python starts with the loop atTrue, meaning it runs indefinitely unless explicitly altered.Termination Condition: This example lacks a termination condition (like checking
numberInSet == 0), leading to an infinite loop.Alternative Code:
while (numberInSet > 0): sum = sum + numberInSet numberInSet = numberInSet - 1
Page 4: Infinite Loop with Break
Refined Example:
numberInSet = 10 sum = 0 while True: sum = sum + numberInSet numberInSet = numberInSet - 1 if numberInSet == 0: break print("Sum of First 10 Numbers is", sum)Using Break: Common practice to include an
ifstatement to avoid endless looping.Termination Condition: The loop runs until the
ifcheck fails (in this case, whennumberInSetreaches0), allowing the program to break out of the loop.Sentinel Value: Refers to a pre-defined condition that allows for loop termination.
Page 5: While-True Equivalent in Other Languages
Do-While Loop: Available in other programming languages but not in Python.
Structure in Other Languages:
do { //code block } while (condition);Python Equivalent:
while(True): //code block if(condition): break