""" Урок 12. Цикл while — весь код примеров одним файлом. Источник: subjects/python-fundamentals/course/lessons/12-while-loop/examples.html Файл собран автоматически (tools/build_lesson_examples.py): правьте страницу урока. Запуск: python lesson-12.py """ # ==================================================================== # Пример 1. Счётчик от 1 до 5 # ==================================================================== i = 1 while i <= 5: print(i) i += 1 # 1 # 2 # 3 # 4 # 5 # ==================================================================== # Пример 2. Накопление результата: сумма и список за один проход # ==================================================================== values = [4, -2, 9, 0, 5, -7, 3] i = 0 total = 0 positives = [] while i < len(values): if values[i] > 0: total += values[i] positives.append(values[i]) i += 1 print("Total of positives:", total) print("Positives list:", positives) # Total of positives: 21 # Positives list: [4, 9, 5, 3] # ==================================================================== # Пример 3. Ловушка бесконечного цикла — забыли изменить переменную # ==================================================================== i = 0 attempts = 0 MAX_ITERATIONS = 5 # защитный лимит — в реальной ловушке i += 1 отсутствует, # поэтому i < 3 никогда не станет ложным while i < 3: print("iteration", attempts) attempts += 1 if attempts >= MAX_ITERATIONS: print("Forgot to update i! Breaking out after", attempts, "iterations to avoid a real infinite loop.") break # i += 1 # <- без этой строки i никогда не достигнет 3 само по себе # iteration 0 # iteration 1 # iteration 2 # iteration 3 # iteration 4 # Forgot to update i! Breaking out after 5 iterations to avoid a real infinite loop. # ==================================================================== # Пример 4. break: досрочный выход по сигналу # ==================================================================== inputs = iter(["10", "25", "stop", "999"]) total = 0 while True: value = next(inputs) if value == "stop": print("Stopped by user command.") break total += int(value) print("Sum before stop:", total) # Stopped by user command. # Sum before stop: 35 # ==================================================================== # Пример 5. continue: пропуск одной итерации # ==================================================================== numbers = [5, -3, 8, -1, 2] i = 0 total = 0 while i < len(numbers): n = numbers[i] i += 1 if n < 0: continue total += n print("Sum of non-negative numbers:", total) # Sum of non-negative numbers: 15 # ==================================================================== # Пример 6. while ... else: когда выполняется, а когда нет # ==================================================================== values = [1, 2, 3, 4, 5] target = 4 i = 0 while i < len(values): if values[i] == target: print(f"Found {target} at index {i}") break i += 1 else: print(f"{target} was not found") # Found 4 at index 3 target2 = 9 i = 0 while i < len(values): if values[i] == target2: print(f"Found {target2} at index {i}") break i += 1 else: print(f"{target2} was not found") # 9 was not found # ==================================================================== # Пример 7. while и for: когда что уместнее # ==================================================================== # for: число шагов известно заранее — три дня, и точка for day in range(1, 4): print(f"Day {day}: watering the plant") # Day 1: watering the plant # Day 2: watering the plant # Day 3: watering the plant # while: продолжаем, пока не выполнится условие — число шагов заранее не известно water_level = 10 day = 0 while water_level > 0: day += 1 water_level -= 3 print(f"Day {day}: water level = {water_level}") # Day 1: water level = 7 # Day 2: water level = 4 # Day 3: water level = 1 # Day 4: water level = -2 # ==================================================================== # Пример 8. Валидация ввода: цикл до получения корректного значения # ==================================================================== fake_inputs = iter(["abc", "-5", "42"]) # смоделированная последовательность вводов while True: raw = next(fake_inputs) if not raw.lstrip("-").isdigit(): print(f"'{raw}' is not a number, try again") continue number = int(raw) if number < 0: print(f"{number} is negative, try again") continue break print("Accepted number:", number) # 'abc' is not a number, try again # -5 is negative, try again # Accepted number: 42 # ==================================================================== # Пример 9. Реальная защита от бесконечного цикла: лимит попыток в игре «Угадай число» # ==================================================================== import random random.seed(7) secret = random.randint(1, 10) guesses = iter([3, 8, 6]) # смоделированные попытки игрока max_attempts = 3 attempts_used = 0 while attempts_used < max_attempts: guess = next(guesses) attempts_used += 1 if guess == secret: print(f"Guessed correctly in {attempts_used} attempts!") break hint = "greater" if guess < secret else "less" print(f"Attempt {attempts_used}: the secret number is {hint}") else: print(f"Out of attempts. The secret number was {secret}.") # Attempt 1: the secret number is greater # Attempt 2: the secret number is less # Guessed correctly in 3 attempts! # ==================================================================== # Пример 10. Модуль random: случайные числа для игр и симуляций # ==================================================================== import random random.seed(42) print("Random float:", random.random()) print("Dice roll:", random.randint(1, 6)) print("Random step:", random.randrange(0, 101, 10)) # Random float: 0.6394267984578837 # Dice roll: 1 # Random step: 40