Цикли for
Останнє оновлення 2025-12-29 | Редагувати цю сторінку
Огляд
Питання
- Як змусити програму робити багато речей?
Цілі
- Поясніть, для чого зазвичай використовуються цикли for.
- Проаналізуйте виконання простого (невкладеного) циклу та правильно вкажіть значення змінних у кожній ітерації.
- Напишіть цикли for, які використовують шаблон накопичувача для агрегування значень.
Цикл for виконує команди один раз для кожного значення в колекції.
- Doing calculations on the values in a list one by one is as painful
as working with
pressure_001,pressure_002, etc. - A for loop tells Python to execute some statements once for each value in a list, a character string, or some other collection.
- “для кожного елемента в цій групі виконайте ці операції”
- Цей цикл
forє еквівалентним наступному:
- І результат циклу
forє таким:
ВИХІД
2
3
5
Цикл for складається з колекції, змінної циклу та тіла
циклу.
- Колекція
[2, 3, 5]є те, що опрацьовується в циклі. - Тіло циклу,
print(number), визначає, що робити для кожного значення в колекції. - Змінна циклу,
number, змінюється для кожної ітерації циклу.- “Поточне значення”.
Перший рядок циклу for має закінчуватися двокрапкою, а
тіло циклу має бути з відступом.
- Двокрапка в кінці першого рядка вказує на початок блоку операторів.
- Python використовує відступ, а не
{}абоbegin/end, щоб показати вкладеність.- Будь-який послідовний відступ є допустимим, але майже усі використовують чотири пробіли.
ПОМИЛКА
IndentationError: expected an indented block
- Відступи у Python завжди важливі.
ПОМИЛКА
File "<ipython-input-7-f65f2962bf9c>", line 2
lastName = "Smith"
^
IndentationError: unexpected indent
- Ця помилка може бути виправлена шляхом видалення зайвих пробілів на початку другого рядку.
Змінні циклу можна називати як завгодно.
- Як і всі інші змінні, змінні циклу:
- Створюються за потреби
- Не несуть смислового навантаження: їх імена можуть бути будь-якими.
Тіло циклу може містити багато операторів.
- Але жоден цикл не повинен мати довжину більше кількох рядків.
- Людям важко запам’ятати великі фрагменти коду.
ВИХІД
2 4 8
3 9 27
5 25 125
Використовуйте range для перебору послідовності
чисел.
- Вбудована функція
rangeстворює послідовність чисел.- Не список: номери виробляються на вимогу, щоб зробити цикл у великих діапазонах більш ефективним.
-
range(N)є набором чисел 0..N-1- Точні індекси списку або рядка символів довжиною N
ВИХІД
a range is not a list: range(0, 3)
0
1
2
The Accumulator pattern turns many values into one.
- A common pattern in programs is to:
- Initialize an accumulator variable to zero, the empty string, or the empty list.
- Update the variable with values from a collection.
PYTHON
# Sum the first 10 integers.
total = 0
for number in range(10):
total = total + (number + 1)
print(total)
ВИХІД
55
- Read
total = total + (number + 1)as:- Add 1 to the current value of the loop variable
number. - Add that to the current value of the accumulator variable
total. - Assign that to
total, replacing the current value.
- Add 1 to the current value of the loop variable
- We have to add
number + 1becauserangeproduces 0..9, not 1..10.
Classifying Errors
Is an indentation error a syntax error or a runtime error?
An IndentationError is a syntax error. Programs with syntax errors cannot be started. A program with a runtime error will start but an error will be thrown under certain conditions.
| Line no | Variables |
|---|---|
| 1 | total = 0 |
| 2 | total = 0 char = ‘t’ |
| 3 | total = 1 char = ‘t’ |
| 2 | total = 1 char = ‘i’ |
| 3 | total = 2 char = ‘i’ |
| 2 | total = 2 char = ‘n’ |
| 3 | total = 3 char = ‘n’ |
Practice Accumulating (continued)
Create an acronym: Starting from the list
["red", "green", "blue"], create the acronym
"RGB" using a for loop.
Hint: You may need to use a string method to properly format the acronym.
Identifying Variable Name Errors
- Read the code below and try to identify what the errors are without running it.
- Run the code and read the error message. What type of
NameErrordo you think this is? Is it a string with no quotes, a misspelled variable, or a variable that should have been defined but was not? - Fix the error.
- Repeat steps 2 and 3, until you have fixed all the errors.
- Python variable names are case sensitive:
numberandNumberrefer to different variables. - The variable
messageneeds to be initialized as an empty string. - We want to add the string
"a"tomessage, not the undefined variablea.
- A for loop executes commands once for each value in a collection.
- A
forloop is made up of a collection, a loop variable, and a body. - The first line of the
forloop must end with a colon, and the body must be indented. - Indentation is always meaningful in Python.
- Loop variables can be called anything (but it is strongly advised to have a meaningful name to the looping variable).
- The body of a loop can contain many statements.
- Use
rangeto iterate over a sequence of numbers. - The Accumulator pattern turns many values into one.