Python · Синтаксис · Начальный уровень
Функции уровень 2
Расширенная практика функций в Python: обработка строк и чисел, логические проверки, списки, фильтрация, подсчёты, поиск значений и написание небольших переиспользуемых функций.
Краткое введение в тему и пояснения перед упражнениями (упражнения ниже):
Паттерны этого уровня
#Справочник: методы строки, срезы и паттерны функций
#Упражнения:
Even или Odd.
#def even_or_odd(n):
pass
Решение
def even_or_odd(n):
if n % 2 == 0:
return "Even"
else:
return "Odd"
# или так можно: сначала получить остаток
def even_or_odd(n):
rest = n % 2
if rest == 0:
return "Even"
return "Odd"
Переворот строки функцией.
#def reverse_text(text):
pass
Решение
def reverse_text(text):
return text[::-1]
# или так можно через цикл
def reverse_text(text):
result = ""
for char in text:
result = char + result
return result
Среднее арифметическое.
#def average(a, b):
pass
Решение
def average(a, b):
return (a + b) / 2
Подсчёт гласных.
#def count_vowels(text):
pass
Решение
def count_vowels(text):
vowels = "aeiouy"
count = 0
for ch in text.lower():
if ch in vowels:
count += 1
return count
Делимость на 3 и 5.
#def divisible_by_3_and_5(n):
pass
Решение
def divisible_by_3_and_5(n):
return n % 3 == 0 and n % 5 == 0
Строка без пробелов.
#def remove_spaces(text):
pass
Решение
def remove_spaces(text):
result = ""
for ch in text:
if ch != " ":
result += ch
return result
# или так:
def remove_spaces(text):
return text.replace(" ", "")
Сумма положительных элементов.
#def sum_positive(numbers):
pass
Решение
def sum_positive(numbers):
total = 0
for n in numbers:
if n > 0:
total += n
return total
Проверка палиндрома.
#def is_palindrome(text):
pass
Решение
def is_palindrome(text):
return text == text[::-1]
# или так можно: подготовить перевёрнутую строку отдельно
def is_palindrome(text):
reversed_text = text[::-1]
return text == reversed_text
Positive, Negative или Zero.
#def describe_number(n):
pass
Решение
def describe_number(n):
if n > 0:
return "Positive"
elif n < 0:
return "Negative"
else:
return "Zero"
Количество слов в строке.
#def count_words(text):
pass
Решение
def count_words(text):
if text == "":
return 0
return len(text.split())
Кратность десяти.
#def is_multiple_of_ten(n):
pass
Решение
def is_multiple_of_ten(n):
return n % 10 == 0
Первый и последний символ функцией.
#def first_and_last(text):
pass
Решение
def first_and_last(text):
if text == "":
return ""
return text[0] + text[-1]
Yes, если больше 100.
#def more_than_hundred(n):
pass
Решение
def more_than_hundred(n):
if n > 100:
return "Yes"
return "No"
# Или так через тернарный оператор:
def more_than_hundred(n):
return "Yes" if n > 100 else "No"
Подсчёт буквы a.
#def count_a(text):
pass
Решение
def count_a(text):
count = 0
for ch in text.lower():
if ch == "a":
count += 1
return count
# или
def count_a(text):
return text.lower().count("a")
Разность по модулю.
#def abs_diff(a, b):
pass
Решение
def abs_diff(a, b):
diff = a - b
if diff < 0:
diff = -diff
return diff
# или так можно через abs
def difference(a, b):
return abs(a - b)
Чётная длина строки.
#def is_even_length(text):
pass
Решение
def is_even_length(text):
return len(text) % 2 == 0
Последняя цифра числа.
#def last_digit(n):
pass
Решение
def last_digit(n):
if n < 0:
n = -n
return n % 10
# или так можно через строку
def last_digit(n):
return int(str(abs(n))[-1])
Без первой и последней буквы.
#def trim_edges(text):
pass
Решение
def trim_edges(text):
if len(text) <= 2:
return ""
return text[1:-1]
Small, Medium или Large.
#def size_label(n):
pass
Решение
def size_label(n):
if n < 10:
return "Small"
elif n <= 100:
return "Medium"
else:
return "Large"
Удаление восклицательных знаков.
#def remove_exclamations(text):
pass
Решение
def remove_exclamations(text):
result = ""
for ch in text:
if ch != "!":
result += ch
return result
# или так можно через replace
def remove_exclamation(text):
return text.replace("!", "")