11.3. While Break

  • Force exit the loop

Example:

>>> while True:
...     break

11.3.1. Example

>>> i = 0
>>>
>>> while True:
...     print(i)
...     i += 1
...     if i == 3:
...         break
0
1
2

11.3.2. Use Case - 1

  • Force user to respond

  • If answer is not 'yes' or 'no' ask again

>>>
... while True:
...     answer = input('Continue [yes/no]?')
...     if answer in ('yes', 'no'):
...         break

11.3.3. Use Case - 2

  • If user hit enter key, without typing a number

  • Variable number will be equal to '' (empty string)

  • Keyword break will exit the loop

>>>
... while True:
...     number = input('Type number: ')
...
...     if not number:
...         break

If user hit enter key without typing a number, variable number will be equal to '' (empty string). Logic value of empty string is False, therefore it will execute the if block content. Keyword break will exit the loop.

11.3.4. Use Case - 3

>>> i = 10
>>>
>>> while True:
...     print(i)
...     i -= 1
...
...     if i == 6:
...         print('Fuel leak detected. Abort, Abort, Abort!')
...         break
10
9
8
7
Fuel leak detected. Abort, Abort, Abort!

11.3.5. Assignments

# TODO: Write automated tests

# %% About
# - Name: While Break Guessing
# - Difficulty: medium
# - Lines: 9
# - Minutes: 5

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Write a game to guess the `HIDDEN_NUMBER` number generated by the computer
# 2. If the player guesses a smaller number, print `Too low! Try again.` and continue the game
# 3. If the player guesses a larger number, print `Too high! Try again.` and continue the game
# 4. If the player guesses the number, print `Congratulations! You have guessed the number.` and end the game
# 5. The game continues until the user guesses the number
# 6. Non-functional requirements:
#    - The user will always input only one digit
#    - The user will not input any invalid characters or longer numbers
#    - Use the `input()` function as normal
#    - `Mock` will simulate the user inputting numbers
# 7. Run doctests - all must succeed

# %% Polish
# 1. Napisz grę w zgadywanie liczby `HIDDEN_NUMBER` wygenerowanej przez komputer
# 2. Jeżeli gracz poda mniejszą liczbę, to wypisz `Too low! Try again.` i kontynuuj grę
# 3. Jeżeli gracz poda większą liczbę, to wypisz `Too high! Try again.` i kontynuuj grę
# 4. Jeżeli gracz zgadnie liczbę, to wypisz `Congratulations! You have guessed the number.` i zakończ grę
# 5. Gra toczy się aż do momentu gdy użytkownik zgadnie
# 6. Wymagania niefunkcjonalne:
#    - Użytkownik zawsze wpisze tylko jedną cyfrę
#    - Użytkownik nie wpisze żadnych nieprawidłowych znaków lub dłuższych liczb
#    - Skorzystaj z funkcji `input()` tak jak normalnie
#    - `Mock` zasymuluje wpisanie liczb przez użytkownika
# 7. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# Too low! Try again.
# Too high! Try again.
# ...
# Too high! Try again.
# Congratulations! You have guessed the number.

# %% Hints
# - `Stop` or `Ctrl+C` kills infinite loop
# - `<` - less than operator
# - `>` - greater than operator
# - `==` - equals operator
# - `while True`
# - `int()`
# - `input(prompt)`
# - `\n` - newline
# - `print()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% Imports
from unittest.mock import Mock

# %% Types

# %% Data
HIDDEN_NUMBER = 4

input = Mock(side_effect=['0', '9', '1', '8', '2', '7', '3', '6', '4'])

# %% Result