Пример 1: Вывод символов строки по индексу
Перебираем строку с помощью индекса, пока индекс меньше длины строки.
📄 examples/print_characters.py
text = input("Enter a word: ")
index = 0
while index < len(text):
print(f"Index {index}: {text[index]}")
index += 1
Пример работы:
Enter a word: Hello
Index 0: H
Index 1: e
Index 2: l
Index 3: l
Index 4: o
Пример 2: Подсчёт гласных
Цикл проходит по каждому символу и считает гласные буквы. Внутри используется continue для пропуска негласных.
📄 examples/vowel_counter.py
text = input("Enter a line: ").lower()
vowels = "aeiou"
count = 0
index = 0
while index < len(text):
char = text[index]
index += 1
if char not in vowels:
continue
count += 1
print(f"Vowels found: {count}")
Логика:
- Приводим строку к нижнему регистру, чтобы не зависеть от регистра ввода.
- Если символ не входит в строку
vowels, пропускаем итерацию черезcontinue. - Инкремент индекса стоит до
continue, чтобы избежать бесконечного цикла.
Пример 3: Переворот строки в цикле
Строки неизменяемы, поэтому собираем новую строку посимвольно.
📄 examples/reverse_string.py
text = input("Enter a word: ")
reversed_text = ""
index = len(text) - 1
while index >= 0:
reversed_text += text[index]
index -= 1
print(f"Reversed: {reversed_text}")
Альтернатива через срез:
text = input("Enter a word: ")
print(f"Reversed: {text[::-1]}")
Пример 4: Генератор короткого пароля
Комбинируем while и random, чтобы собрать строку из случайных букв.
📄 examples/simple_password.py
import random
letters = "abcdefghijklmnopqrstuvwxyz"
password = ""
length = 8
index = 0
while index < length:
password += random.choice(letters)
index += 1
print(f"Generated password: {password}")
Пример 5: Поиск подстроки через цикл
Программа запрашивает строку и проверяет, содержится ли в ней слово "Python". Для разнообразия показано два способа: через in и через цикл.
📄 examples/find_python.py
text = input("Enter a line: ")
target = "Python"
# Simple way
print(f"Contains '{target}': {target in text}")
# Loop way: case-insensitive search
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}")
Пример 6: Коды символов в диапазоне
Цикл печатает символы и их коды для заданного диапазона Unicode.
📄 examples/unicode_range.py
start = int(input("Enter start code: "))
stop = int(input("Enter stop code: "))
while start <= stop:
print(f"{start}: {chr(start)}")
start += 1
Как запустить в VS Code
- Создайте файл
example.pyв папке урока. - Скопируйте код из примера выше.
- Откройте терминал в VS Code (Ctrl + `).
- Активируйте виртуальное окружение:
venv\Scripts\activate(Windows) илиsource venv/bin/activate(Mac/Linux). - Запустите:
python example.py