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 to False to 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 if statement 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 True might be confusing; it requires clarity on the condition under which it runs. Python starts with the loop at True, 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 if statement to avoid endless looping.

  • Termination Condition: The loop runs until the if check fails (in this case, when numberInSet reaches 0), 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