CMPE 150

Introduction to Computing

Fall 2021

Created by Gökçe Uludoğan

While loops

  • Indefinite loop: the number of times to iterate is not known beforehand.
  • Syntax:
    
    while test_expression:
        Body of while
        
  • Body of while is executed as long as the condition is satisfied.
### Example ```python num = int(input()) sum = 0 counter = 1 while counter <= num: sum = sum + counter counter = counter + 1 print("The sum is", sum) ``` #### Output for num = 10 ``` The sum is 55 ```

Execution

Break and continue

  • break: immediately terminates a loop entirely.
  • continue: immediately terminates the current loop iteration.
### Example: Break ```python n = 5 while n > 0: n -= 1 if n == 2: break print(n) print('End of the loop.') ``` #### Output ``` 4 3 End of the loop. ```
### Example: Continue ```python n = 5 while n > 0: n -= 1 if n == 2: continue print(n) print('End of the loop.') ``` #### Output ``` 4 3 1 0 End of the loop. ```

References

  1. https://pythontutor.com/
  2. https://realpython.com/python-while-loop/
  3. https://www.programiz.com/python-programming/while-loop