Работа с циклами for в Python 3
Циклы позволяют автоматизировать выполнение последовательностей задач в программах.
В данном руководстве мы рассмотрим цикл for в языке программирования Python 3.
Цикл for повторно выполняет код согласно счетчику или переменной цикла. Циклы for используются тогда, когда количество итераций известно заранее, до запуска цикла (в отличие от цикла while, который выполняется согласно логическим условиям).
Основы работы с циклом for
В Python циклы for создаются таким образом:
for [iterating variable] in [sequence]:
[do something]
Цикл будет выполнять заданное действие ([do something]) до конца последовательности.
Для примера рассмотрим цикл for, который перебирает диапазон значений:
for i in range(0,5):
print(i)
Такая программа вернёт следующий вывод:
Этот цикл for использует i в качестве итерационной переменной. Последовательность существует в диапазоне от 0 до 5.
Выражение print внутри цикла выводит одно целое число для каждой итерации.
Примечание: В программировании отсчёт, как правило, начинается с 0. В диапазоне от 0 до 5 цикл выводит 0, 1, 2, 3, 4.
Циклы for обычно используются в ситуациях, когда программе необходимо повторить блок кода определённое количество раз.
Функция range()
Функция range() – это один из встроенных неизменяемых типов последовательностей Python. В циклах range() указывает, сколько раз нужно повторить последовательность.
Функция range() имеет такие аргументы:
- start указывает целое число, с которого начинается последовательность (включительно) . Если этот аргумент не указан, по умолчанию используется значение 0.
- stop нужно использовать всегда. Это последнее целое число последовательности (исключительно).
- step определяет шаг: насколько нужно увеличить (в случае с отрицательными числами уменьшить) следующую итерацию. Если аргумент step пропущен, по умолчанию используется 1.
Попробуйте передать функции range() несколько аргументов.
Для начала используйте только stop.
for i in range(6):
print(i)
В примере выше аргумент stop имеет значение 6, потому код выполнит итерацию от 0 до 6 (исключая 6).
Теперь попробуйте добавить аргумент start. Функция будет иметь такой вид:
Укажите диапазон, в котором нужно выполнить итерацию:
for i in range(20,25):
print(i)
В данном случае перебор начинается с 20 (включительно) и заканчивается на 25 (исключительно).
Аргумент step в функции range() определяет шаг (как в срезах строк); его можно использовать для пропуска значений в последовательности.
Попробуйте использовать все доступные аргументы. Они указываются в такой последовательности:
range(start, stop, step)
for i in range(0,15,3):
print(i)
В данном случае цикл for переберёт значения от 0 до 15 с шагом 3, в результате он выведет каждое третье число:
Также в качестве шага можно использовать отрицательные числа, тогда цикл будет перебирать значения в обратном направлении. В таком случае не забудьте откорректировать аргументы start и stop (поставьте их по убыванию).
for i in range(100,0,-10):
print(i)
В данном примере 100 – значение start, 0 – stop, -10 – шаг.
В Python циклы for часто используют функцию range() как один из параметров итерации.
Цикл for и последовательные типы данных
Списки и другие последовательные типы данных также можно использовать в качестве параметров итерации для цикла. Например, вместо функции range() вы можете определить список и итерацию по этому списку.
Присвойте список переменной, а затем запустите итерацию по нему:
sharks = [‘hammerhead’, ‘great white’, ‘dogfish’, ‘frilled’, ‘bullhead’, ‘requiem’] for shark in sharks:
print(shark)
В данном случае цикл выведет каждый элемент списка.
hammerhead
great white
dogfish
frilled
bullhead
requiem
Списки и другие последовательные типы данных (строки и кортежи) часто используются в циклах, потому что они итерируемые. Можно комбинировать эти типы данных с функцией range(), чтобы добавить элементы в список, например:
sharks = [‘hammerhead’, ‘great white’, ‘dogfish’, ‘frilled’, ‘bullhead’, ‘requiem’] for item in range(len(sharks)):
sharks.append(‘shark’)
print(sharks)
[‘hammerhead’, ‘great white’, ‘dogfish’, ‘frilled’, ‘bullhead’, ‘requiem’, ‘shark’, ‘shark’, ‘shark’, ‘shark’, ‘shark’, ‘shark’]
Циклы for позволяют составлять новые списки:
integers = [] for i in range(10):
integers.append(i)
print(integers)
В данном случае инициированный список integers пуст, но цикл for добавляет в него данные:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Также можно выполнять итерацию строк:
8host = ‘8Host’
for letter in 8host:
print(letter)
8
H
o
s
t
Аналогичным образом можно выполнить итерацию кортежа.
При итерации словарей важно помнить о структуре «ключ: значение», чтобы вызывать правильные элементы из словаря. Например:
willy_orca = <'name': 'Willy', 'animal': 'orca', 'color': 'black', 'location': 'ocean'>
for key in willy_orca:
print(key + ‘: ‘ + willy_orca[key])
name: Willy
animal: orca
location: ocean
color: black
При использовании словарей в циклах for итерируемое значение соответствует ключу кловаря, а dictionary_variable[iterating_variable] соответствует значению. Таким образом, в примере выше key – ключ, а willy_orca[key] – значение.
Вложенные циклы for
Python позволяет вкладывать циклы друг в друга.
Вложенный цикл – это цикл, который встречается внутри другого цикла. Структурно это похоже на выражение if.
Вложенный цикл выглядит так:
for [first iterating variable] in [outer loop]: # Outer loop
[do something] # Optional
for [second iterating variable] in [nested loop]: # Nested loop
[do something]
Программа сначала выполняет внешний цикл. Внутри первой итерации внешнего цикла запускается внутренний, вложенный цикл. Затем программа возвращается обратно к началу внешнего цикла, завершает вторую итерацию и снова вызывает вложенный цикл. После завершения вложенного цикла программа возвращается в начало внешнего цикла. Это будет происходить до тех пор, пока последовательность не будет завершена или прервана (или пока какое-то выражение не приведёт к нарушению процесса).
Попробуйте создать вложенный цикл. В данном примере внешний цикл будет перебирать список чисел (num_list), а внутренний – алфавит (alpha_list).
num_list = [1, 2, 3] alpha_list = [‘a’, ‘b’, ‘c’] for number in num_list:
print(number)
for letter in alpha_list:
print(letter)
Такая программа выведет:
Программа завершает первую итерацию, выводя на экран 1, после чего запускается внутренний цикл, который выводит последовательно «a, b, c». После этого программа возвращается в начало внешнего цикла, выводит 2, а затем снова обрабатывает внутренний цикл.
Вложенные циклы for могут быть полезны для перебора элементов в списках, составленных из списков. Если в списке, который состоит из списков, использовать только один цикл, программа будет выводить каждый внутренний список в качестве элемента:
list_of_lists = [[‘hammerhead’, ‘great white’, ‘dogfish’],[0, 1, 2],[9.9, 8.8, 7.7]] for list in list_of_lists:
print(list)
[‘hammerhead’, ‘great white’, ‘dogfish’] [0, 1, 2] [9.9, 8.8, 7.7]
Чтобы вывести каждый отдельный элемент внутренних списков, нужно использовать вложенный цикл.
list_of_lists = [[‘hammerhead’, ‘great white’, ‘dogfish’],[0, 1, 2],[9.9, 8.8, 7.7]] for list in list_of_lists:
for item in list:
print(item)
hammerhead
great white
dogfish
0
1
2
9.9
8.8
7.7
Пример вложенного списка for можно найти в другой нашей статье.
Заключение
Теперь вы знаете, как работает цикл for в языке программирования Python. Циклы for выполняют блок кода заданное количество раз.
Цикл for в Python
Цикл for в Python используется для перебора последовательностей (списков, кортежей, строк) и других итерируемых объектов. Перебор последовательности называется обходом.
Синтаксис цикла
Цикл продолжается до тех пор, пока мы не достигнем последнего элемента последовательности. Тело цикла for является отдельным блоком кода и отделяется отступом.
Блок-схема цикла
Пример цикла
Вывод:
Функция range()
С помощью функции range() мы можем сгенерировать последовательность чисел. range(10) , к примеру, сгенерирует числа от 0 до 9 (всего 10 чисел).
Мы также можем определить начало, конец и размер шага — range(начало, конец, размер_шага) . Если не указать шаг (размер_шага), то по умолчанию он будет равен 1.
Объект range в некотором смысле «ленивый». Когда мы вызываем этот объект, он не генерирует все числа, которые он «содержит». Но это и не итератор — он поддерживает операции in , len и __getitem__ .
Эта функция не хранит все значения в памяти — это неэффективно. Для нее важны лишь начало, конец и размер шага — генерация следующего числа происходит на ходу.
Для вывода всех элементов следует воспользоваться функцией list() .
Наглядный пример
Вывод:
Функцию range() можно использовать для перебора последовательности чисел в цикле for . Индексация реализуется при комбинации с функцией len() . Пример:
Вывод:
Цикл for с блоком else
В цикле for может быть дополнительный блок else . Блок else выполняется, если элементы последовательности закончились.
Для остановки цикла for используется ключевое слово break . В этом случае выполнение цикла останавливается.
Следовательно, блок else выполняется только в том случае, если выполнение цикла не было прервано оператором break.
Наглядный пример
Вывод:
В этом примере цикл for печатает элементы списка до тех пор, пока он не закончится. После завершения цикла выполняется блок else , который печатает сообщение Элементов в списке не осталось .
Оператор for. else можно использовать так: блок else выполнится только в том случае, если не выполнится оператор break .
Loops In python — Why Should You Use One
Dealing with redundant code and repetitive commands can be a nightmare for any programmer. Python makes use of loops, control and conditional statements to overcome this hurdle. This article will help you understand loops in python and all the terminologies that surround loops.
- What are Loops in Python?
- What is for loop and while loop?
- Loop control statements
What Are Loops In Python?
Loops in Python allow us to execute a group of statements several times. Let's take an example to understand why loops are used in python.
Suppose, you are a software developer and you are required to provide a software module for all the employees in your office. So, you must print the details of the payroll of each employee separately. Printing the details of all the employees will be a tiresome task, instead you can use the logic for calculating the details and keep on iterating the same logic statement. This will save your time and make your code efficient.
The illustration below is the flowchart for a loop:
The execution starts and checks if the condition is True or False. A condition could be any logic that we want to test in our program. If its true it will execute the body of the loop and if its false, It will exit the loop.
Conditional Statements
Conditional statements in Python support the usual logical conditions from mathematics.
- Equals: a == b
- Not Equals: a != b
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to : a >= b
These statements can be used in several ways, most commonly in if statement.
Let us understand the concept of if statements.
‘if’ Statement
An if statement is written using the ‘if’ keyword, The syntax is the keyword ‘if’ followed with the condition.
Below is the flowchart of the if statement:
As you can see, the execution encounters the if condition and acts accordingly. If it is true, it executes the body and if it is false, it exits the if statement.
Above code snippet illustrates the basic example of how a condition is used in the if statement.
When it reaches the if statement it checks whether the value of b is greater or not. If b is greater, it prints “b is greater“. Now if the condition is false, it exits the if statement and executes the next statement. In order to print the next statement, we can add a keyword ‘else’ for the alternate result that we wish to execute. Lets move to the else statement for better understanding.
‘else’ Statement
The else keyword catches anything that is not caught by the preceding conditions. When the condition is false for the if statement, the execution will move to the else statement.
Let's take a look at the flowchart of else statement below:
As you can see, when the if statement was false the execution moved to the body of else. Let's understand this with an example.
The first condition is not true, so we will move to the next statement which is the else statement and print “b is greater”.
In case we have more conditions to test, we can also use elif statement.
‘elif’ Statement
elif statement in layman term means “try this condition instead”. Rest of the conditions can be used by using the elif keyword.
Let us look at the code below:
“When the if statement is not true, the execution will move to the elif statement and check if it holds true. And in the end, the else statement if and elif are false.
Since a != b, “b is greater” will get printed here.
Note: python relies on indentation, other programming languages use curly brackets for loops.
What Is ‘for’ Loop and ‘while’ Loop
A for loop is used to execute statements, once for each item in the sequence. The sequence could be a list, a Dictionary, a set or a string.
A for loop has two parts, the block where the iteration statement is specified and then there is the body which is executed once every iteration.
Unlike while loop, we already specify the number of times the iterations must execute. for loop syntax takes three fields, a Boolean condition, initial value of the counting variable and the increment of the counting variable.
Look at the example to understand this better:
Here we were iterating through the list. To iterate through a code for a specified number of times we could use the range() function.
Range Function
Range function requires a specific sequence of numbers. It starts at 0 and then the value increments by 1 until the specified number is reached.
It will print from 0–2, the output will look like
Note: the range (3) does not mean the values from 0–3 but the values from 0–2.
Below is another example using the condition statements:
‘while’ Loop
The ‘while’ loop executes the set of statements as long as the condition is true.
It consists of a condition block and the body with the set of statements, It will keep on executing the statement until the condition becomes false. There is no guarantee to see how long the loop will keep iterating.
Following is the flowchart for while loop:
To understand this let’s take a look at the example below.
Output: it will print 1 2 3 4 5
The execution will continue until value of i reaches 6.
The while loop requires the relevant variable to be ready, here we need an indexing variable, which could be any value.
Let's consider another example:
Note: remember to iterate i or the loop will continue forever. if there is no control statement here, loop will continue forever. try removing the break statement and run again.
We might need to control the flow of the execution to favor a few conditions in some cases, so let’s understand the loop control statements in Python.
Loop Control Statements
To control the flow of the loop or to alter the execution based on a few specified conditions we use the loop control statements discussed below. The control statements are used to alter the execution based on the conditions.
In Python we have three control statements:
Break
Break statement is used to terminate the execution of the loop containing it. As soon as the loop comes across a break statement, the loop terminates and the execution transfers to the next statement following the loop.
As you can see the execution moves to the statement below the loop, when the break returns true.
Let us understand this better with an example:
Output:
Here the execution will stop as soon as the string “i” is encountered in the string. And then the execution will jump to the next statement.
Continue
The continue statement is used to skip the rest of the code in the loop for the current iteration. It does not terminate the loop like the break statement and continues with the remaining iterations.
When continue is encountered it only skips the remaining loop for that iteration only.
It will skip the string “i” in the output and the rest of the iterations will still execute. All letters in the string except “i” will be printed.
The pass statement is a null operation. It basically means that the statement is required syntactically but you do not wish to execute any command or code.
Take a look at the code below:
Output:
The execution will not be affected and it will just print the pass block once it encounters the “a” string. And the execution will start at “a” and execute the rest of the remaining iterations.
‘while’ Loop Using The Break Statement
Let's understand how we use a while loop using a break statement with an example below:
Output: it will print 1 2
The execution will be terminated when the iteration comes to 3 and the next statement will be executed.
Using Continue Statement
Let’s take an example for continue statement in a while loop:
Here the execution will be skipped, and the rest of the iterations will be executed.
Nested Loops
Python allows us to use one loop inside another loop, Following are a few examples
Nested for loop
An example to use a for loop inside another for loop:
Output:
Nested ‘while’ loop
Below is the basic syntax to use a nested while loop:
An example to show a nested while and for loop:
In this program we have used a while loop and inside the body of the while loop, we have incorporated a for loop.
The concepts discussed in this blog will help you understand the loops in Python. This will be very handy when you are looking to master Python and will help you make your code efficient. Python is a widely used high-level language. If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.
Do look out for other articles in this series which will explain the various other aspects of Python and Data Science.
Цикл for в Python
Цикл for в Python – это итеративная функция. Если у вас есть объект последовательности, например список, вы можете использовать цикл for для перебора элементов, содержащихся в списке.
Функциональность цикла for не сильно отличается от того, что вы видите во многих других языках программирования.
Базовый синтаксис
Мы можем использовать цикл for для перебора списка, кортежа или строк. Синтаксис:
Как вывести отдельные буквы строки?
Строка Python – это последовательность символов. Мы можем использовать цикл for для перебора символов и их печати.
Использование цикла for для перебора списка или кортежа
Список и кортеж – повторяемые объекты. Мы можем использовать цикл для перебора их элементов.
Давайте посмотрим на пример, чтобы найти сумму чисел в кортеже:
Вложенный цикл
Когда у нас есть цикл for внутри другого цикла for, он называется вложенным циклом for. В следующем коде показаны вложенные циклы:
Использование с функцией range()
Python range() – одна из встроенных функций. Она используется с циклом for для выполнения блока кода определенное количество раз.
Мы также можем указать параметры запуска, остановки и шага для функции диапазона.
Оператор break
Оператор break используется для преждевременного выхода из цикла for. Он используется для прерывания цикла при выполнении определенного условия.
Допустим, у нас есть список чисел, и мы хотим проверить, присутствует ли число. Мы можем перебрать список чисел и, если число найдено, выйти из цикла, потому что нам не нужно продолжать перебирать оставшиеся элементы.
В этом случае мы будем использовать условие if else.
Оператор continue
Мы можем использовать операторы continue внутри цикла, чтобы пропустить выполнение тела цикла for для определенного условия.
Допустим, у нас есть список чисел, и мы хотим вывести сумму положительных чисел. Мы можем использовать операторы continue, чтобы пропустить цикл для отрицательных чисел.
С (необязательным) блоком else
Блок else выполняется только в том случае, если цикл не завершается оператором break.
Допустим, у нас есть функция для вывода суммы чисел, когда все числа четные. Мы можем использовать оператор break, чтобы завершить цикл for, если присутствует нечетное число. Мы можем вывести сумму в части else, чтобы она выводилась, когда цикл выполняется нормально.