Putting it all together
Putting it all together
- You now know variables, input,
if, loops, lists, functions, and dictionaries. - A real program combines these small pieces into one useful tool.
- In this lesson you build a tiny class-scores analyzer, one function at a time.
Объединение всего вместе
- Теперь вы знаете переменные, ввод,
if, циклы, списки, функции и словари. - Настоящая программа объединяет эти маленькие части в один полезный инструмент.
- В этом уроке вы создаете крошечный анализатор оценок класса, функцию за функцией.
The plan
- We have a list of test scores, like
[70, 90, 50, 80]. - We want three answers: the average, how many passed, and a short summary.
- We will write one small function for each job, then they work together.
План
- У нас есть список оценок, например,
[70, 90, 50, 80]. - Нам нужны три ответа: средний балл, количество сданных экзаменов и краткое резюме.
- Мы напишем одну маленькую функцию для каждой задачи, затем они будут работать вместе.
The analyzer calls each helper
A big program calls small functions in turn, each returning one answer.
Handy built-ins for lists
- Python gives you ready-made helpers that work on a list of numbers.
len(x)counts the items,sum(x)adds them,max(x)/min(x)find the largest / smallest.- Use them instead of writing a loop every time.
Полезные встроенные функции для списков
- Python предоставляет готовые вспомогательные инструменты для работы со списком чисел.
len(x)считает элементы,sum(x)суммирует их,max(x)/min(x)находят наибольшее / наименьшее.- Используйте их вместо написания цикла каждый раз.
scores = [70, 90, 50, 80]
print(len(scores)) # 4
print(sum(scores)) # 290
print(max(scores)) # 90
print(min(scores)) # 50
A pattern you will reuse: count items that pass a test
- A very common job: loop a list, and count the items that pass some test.
- Start a counter at
0, and add1each time theifis true. - Here we count the long words; soon you will count the passing scores.
Шаблон, который вы будете использовать повторно: подсчет элементов, прошедших проверку
- Очень частая задача: пройти по списку и подсчитать элементы, прошедшие某种 тест.
- Начните счетчик с
0и добавляйте1каждый раз, когда условие вifистинно. - Здесь мы считаем длинные слова; скоро вы будете считать сданные оценки.
def how_many_long_words(words, min_length):
count = 0
for w in words:
if len(w) >= min_length:
count = count + 1
return count
print(how_many_long_words(["hi", "hello", "hey", "howdy"], 4)) # 2
Common mistakes
- Build in small pieces and test each one before adding the next.
- Read the whole task first, then plan before you code.
Распространенные ошибки
- Стройте код небольшими частями и тестируйте каждую перед добавлением следующей.
- Прочитайте всю задачу целиком, затем спланируйте решение перед написанием кода.
Now you try
- Build the analyzer in three steps:
average,count_passing, thenstats. - Each function is small. Together they turn a list of scores into real answers.
- Press Check answer after each one.
Теперь попробуйте сами
- Постройте анализатор в три шага:
average,count_passing, затемstats. - Каждая функция мала. Вместе они превращают список оценок в реальные ответы.
- Нажимайте Check answer после каждой функции.
Write average(scores) that returns the average (mean) of a list of numbers: the total divided by how many. If the list is empty, return 0 (so it does not crash). Example: average([2, 4]) is 3.0.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Write count_passing(scores, pass_mark) that returns how many scores are greater than or equal to pass_mark. Loop the list and count. Example: count_passing([40, 50, 60], 50) is 2.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Write stats(scores) (assume at least one score) that returns a dictionary with three keys: "highest", "lowest", and "average". Example: stats([70, 90, 50, 80]) returns {"highest": 90, "lowest": 50, "average": 72.5}.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Write grade_counts(scores) that returns a dictionary counting grades: A for 80 and above, B for 60 and above, C for the rest. Always include all three keys: grade_counts([85, 72, 90, 40]) is {"A": 2, "B": 1, "C": 1}.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.