""" Урок 15. Summary session 4 — весь код примеров одним файлом. Источник: subjects/python-fundamentals/course/lessons/15-summary-session-4/examples.html Файл собран автоматически (tools/build_lesson_examples.py): правьте страницу урока. Запуск: python lesson-15.py """ # ==================================================================== # Пример 1. Вывод символов строки по индексу # ==================================================================== text = input("Enter a word: ") index = 0 while index < len(text): print(f"Index {index}: {text[index]}") index += 1 # ==================================================================== # Пример 2. break и continue рядом # ==================================================================== word = "sky3blue7" digits = "0123456789" # break: stop searching as soon as we find the first digit position = 0 first_digit_index = -1 while position < len(word): if word[position] in digits: first_digit_index = position break position += 1 print(f"First digit index: {first_digit_index}") # continue: skip digits, keep only letters position = 0 letters_only = "" while position < len(word): char = word[position] position += 1 if char in digits: continue letters_only += char print(f"Letters only: {letters_only}") # ==================================================================== # Пример 3. Конструкция while / else: два сценария # ==================================================================== # Scenario 1: loop finishes naturally -> else runs counter = 1 while counter <= 3: print(counter) counter += 1 else: print("Loop completed without break.") print("---") # Scenario 2: loop exits via break -> else is skipped counter = 1 while counter <= 3: print(counter) if counter == 2: break counter += 1 else: print("This will not print.") # ==================================================================== # Пример 4. Переворот строки в цикле # ==================================================================== word = input("Enter a word: ") reversed_word = "" position = len(word) - 1 while position >= 0: reversed_word += word[position] position -= 1 print(f"Reversed: {reversed_word}") print(f"Reversed via slice: {word[::-1]}") # ==================================================================== # Пример 5. Срезы строк s[start:end:step] # ==================================================================== phrase = "Python programming" print(phrase[2:5]) # from index 2 up to (not including) index 5 print(phrase[:3]) # from the start up to index 3 print(phrase[::2]) # every second character print(phrase[::-1]) # full reverse: negative step print(phrase[-11:-4]) # negative indices count from the end # ==================================================================== # Пример 6. Сравнение строк лексикографически # ==================================================================== print("apple" < "banana") # 'a' < 'b' -> True print("Apple" < "apple") # 'A' (65) < 'a' (97) -> True print(ord("A"), ord("a")) word1 = "apple" word2 = "Apple" print(word1 == word2) # case-sensitive comparison print(word1.lower() == word2.lower()) # ignore case # ==================================================================== # Пример 7. Генератор короткого пароля # ==================================================================== import random letters = "abcdefghijklmnopqrstuvwxyz" password = "" length = 8 index = 0 while index < length: password += random.choice(letters) index += 1 print(f"Generated password: {password}") # ==================================================================== # random.randint(): случайное целое число # ==================================================================== import random words = ["python", "loop", "string", "random"] random_index = random.randint(0, len(words) - 1) print(f"Random index: {random_index}") print(f"Chosen word: {words[random_index]}") attempts_allowed = random.randint(3, 5) print(f"Attempts allowed: {attempts_allowed}") # ==================================================================== # Пример 9. Поиск подстроки через цикл # ==================================================================== text = input("Enter a line: ") target = "Python" # Simple way print(f"Contains '{target}': {target in text}") # Loop way: case-insensitive search with early exit lower_text = text.lower() lower_target = target.lower() found = False index = 0 while index <= len(lower_text) - len(lower_target): if lower_text[index:index + len(lower_target)] == lower_target: found = True break index += 1 print(f"Found via loop (case-insensitive): {found}") # ==================================================================== # Пример 10. Коды символов в диапазоне # ==================================================================== start = int(input("Enter start code: ")) stop = int(input("Enter stop code: ")) while start <= stop: print(f"{start}: {chr(start)}") start += 1