4. More Control Flow Tools¶
Besides the while statement just introduced, Python uses the usual flow control statements known from other languages, with some twists.
4.1. if Statements¶
Perhaps the most well-known statement type is the if statement. For example:
There can be zero or more elif parts, and the else part is optional. The keyword ‘ elif ’ is short for ‘else if’, and is useful to avoid excessive indentation. An if … elif … elif … sequence is a substitute for the switch or case statements found in other languages.
If you’re comparing the same value to several constants, or checking for specific types or attributes, you may also find the match statement useful. For more details see match Statements .
4.2. for Statements¶
The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended):
Code that modifies a collection while iterating over that same collection can be tricky to get right. Instead, it is usually more straight-forward to loop over a copy of the collection or to create a new collection:
4.3. The range() Function¶
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions:
The given end point is never part of the generated sequence; range(10) generates 10 values, the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the ‘step’):
To iterate over the indices of a sequence, you can combine range() and len() as follows:
In most such cases, however, it is convenient to use the enumerate() function, see Looping Techniques .
A strange thing happens if you just print a range:
In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t. It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesn’t really make the list, thus saving space.
We say such an object is iterable , that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the for statement is such a construct, while an example of a function that takes an iterable is sum() :
Later we will see more functions that return iterables and take iterables as arguments. In chapter Data Structures , we will discuss in more detail about list() .
4.4. break and continue Statements, and else Clauses on Loops¶
The break statement, like in C, breaks out of the innermost enclosing for or while loop.
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the iterable (with for ) or when the condition becomes false (with while ), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:
(Yes, this is the correct code. Look closely: the else clause belongs to the for loop, not the if statement.)
When used with a loop, the else clause has more in common with the else clause of a try statement than it does with that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs. For more on the try statement and exceptions, see Handling Exceptions .
The continue statement, also borrowed from C, continues with the next iteration of the loop:
4.5. pass Statements¶
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:
This is commonly used for creating minimal classes:
Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The pass is silently ignored:
4.6. match Statements¶
A match statement takes an expression and compares its value to successive patterns given as one or more case blocks. This is superficially similar to a switch statement in C, Java or JavaScript (and many other languages), but it’s more similar to pattern matching in languages like Rust or Haskell. Only the first pattern that matches gets executed and it can also extract components (sequence elements or object attributes) from the value into variables.
The simplest form compares a subject value against one or more literals:
Note the last block: the “variable name” _ acts as a wildcard and never fails to match. If no case matches, none of the branches is executed.
You can combine several literals in a single pattern using | (“or”):
Patterns can look like unpacking assignments, and can be used to bind variables:
Study that one carefully! The first pattern has two literals, and can be thought of as an extension of the literal pattern shown above. But the next two patterns combine a literal and a variable, and the variable binds a value from the subject ( point ). The fourth pattern captures two values, which makes it conceptually similar to the unpacking assignment (x, y) = point .
If you are using classes to structure your data you can use the class name followed by an argument list resembling a constructor, but with the ability to capture attributes into variables:
You can use positional parameters with some builtin classes that provide an ordering for their attributes (e.g. dataclasses). You can also define a specific position for attributes in patterns by setting the __match_args__ special attribute in your classes. If it’s set to (“x”, “y”), the following patterns are all equivalent (and all bind the y attribute to the var variable):
A recommended way to read patterns is to look at them as an extended form of what you would put on the left of an assignment, to understand which variables would be set to what. Only the standalone names (like var above) are assigned to by a match statement. Dotted names (like foo.bar ), attribute names (the x= and y= above) or class names (recognized by the “(…)” next to them like Point above) are never assigned to.
Patterns can be arbitrarily nested. For example, if we have a short list of points, we could match it like this:
We can add an if clause to a pattern, known as a “guard”. If the guard is false, match goes on to try the next case block. Note that value capture happens before the guard is evaluated:
Several other key features of this statement:
Like unpacking assignments, tuple and list patterns have exactly the same meaning and actually match arbitrary sequences. An important exception is that they don’t match iterators or strings.
Sequence patterns support extended unpacking: [x, y, *rest] and (x, y, *rest) work similar to unpacking assignments. The name after * may also be _ , so (x, y, *_) matches a sequence of at least two items without binding the remaining items.
Mapping patterns: <"bandwidth": b, "latency": l>captures the "bandwidth" and "latency" values from a dictionary. Unlike sequence patterns, extra keys are ignored. An unpacking like **rest is also supported. (But **_ would be redundant, so it is not allowed.)
Subpatterns may be captured using the as keyword:
will capture the second element of the input as p2 (as long as the input is a sequence of two points)
Most literals are compared by equality, however the singletons True , False and None are compared by identity.
Patterns may use named constants. These must be dotted names to prevent them from being interpreted as capture variable:
For a more detailed explanation and additional examples, you can look into PEP 636 which is written in a tutorial format.
4.7. Defining Functions¶
We can create a function that writes the Fibonacci series to an arbitrary boundary:
The keyword def introduces a function definition. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must be indented.
The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or docstring. (More about docstrings can be found in the section Documentation Strings .) There are tools which use docstrings to automatically produce online or printed documentation, or to let the user interactively browse through code; it’s good practice to include docstrings in code that you write, so make a habit of it.
The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables and variables of enclosing functions cannot be directly assigned a value within a function (unless, for global variables, named in a global statement, or, for variables of enclosing functions, named in a nonlocal statement), although they may be referenced.
The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object). 1 When a function calls another function, or calls itself recursively, a new local symbol table is created for that call.
A function definition associates the function name with the function object in the current symbol table. The interpreter recognizes the object pointed to by that name as a user-defined function. Other names can also point to that same function object and can also be used to access the function:
Coming from other languages, you might object that fib is not a function but a procedure since it doesn’t return a value. In fact, even functions without a return statement do return a value, albeit a rather boring one. This value is called None (it’s a built-in name). Writing the value None is normally suppressed by the interpreter if it would be the only value written. You can see it if you really want to using print() :
It is simple to write a function that returns a list of the numbers of the Fibonacci series, instead of printing it:
This example, as usual, demonstrates some new Python features:
The return statement returns with a value from a function. return without an expression argument returns None . Falling off the end of a function also returns None .
The statement result.append(a) calls a method of the list object result . A method is a function that ‘belongs’ to an object and is named obj.methodname , where obj is some object (this may be an expression), and methodname is the name of a method that is defined by the object’s type. Different types define different methods. Methods of different types may have the same name without causing ambiguity. (It is possible to define your own object types and methods, using classes, see Classes ) The method append() shown in the example is defined for list objects; it adds a new element at the end of the list. In this example it is equivalent to result = result + [a] , but more efficient.
4.8. More on Defining Functions¶
It is also possible to define functions with a variable number of arguments. There are three forms, which can be combined.
4.8.1. Default Argument Values¶
The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:
This function can be called in several ways:
giving only the mandatory argument: ask_ok(‘Do you really want to quit?’)
giving one of the optional arguments: ask_ok(‘OK to overwrite the file?’, 2)
or even giving all arguments: ask_ok(‘OK to overwrite the file?’, 2, ‘Come on, only yes or no!’)
This example also introduces the in keyword. This tests whether or not a sequence contains a certain value.
The default values are evaluated at the point of function definition in the defining scope, so that
Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:
This will print
If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:
4.8.2. Keyword Arguments¶
Functions can also be called using keyword arguments of the form kwarg=value . For instance, the following function:
accepts one required argument ( voltage ) and three optional arguments ( state , action , and type ). This function can be called in any of the following ways:
but all the following calls would be invalid:
In a function call, keyword arguments must follow positional arguments. All the keyword arguments passed must match one of the arguments accepted by the function (e.g. actor is not a valid argument for the parrot function), and their order is not important. This also includes non-optional arguments (e.g. parrot(voltage=1000) is valid too). No argument may receive a value more than once. Here’s an example that fails due to this restriction:
When a final formal parameter of the form **name is present, it receives a dictionary (see Mapping Types — dict ) containing all keyword arguments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the form *name (described in the next subsection) which receives a tuple containing the positional arguments beyond the formal parameter list. ( *name must occur before **name .) For example, if we define a function like this:
It could be called like this:
and of course it would print:
Note that the order in which the keyword arguments are printed is guaranteed to match the order in which they were provided in the function call.
4.8.3. Special parameters¶
By default, arguments may be passed to a Python function either by position or explicitly by keyword. For readability and performance, it makes sense to restrict the way arguments can be passed so that a developer need only look at the function definition to determine if items are passed by position, by position or keyword, or by keyword.
A function definition may look like:
where / and * are optional. If used, these symbols indicate the kind of parameter by how the arguments may be passed to the function: positional-only, positional-or-keyword, and keyword-only. Keyword parameters are also referred to as named parameters.
4.8.3.1. Positional-or-Keyword Arguments¶
If / and * are not present in the function definition, arguments may be passed to a function by position or by keyword.
4.8.3.2. Positional-Only Parameters¶
Looking at this in a bit more detail, it is possible to mark certain parameters as positional-only. If positional-only, the parameters’ order matters, and the parameters cannot be passed by keyword. Positional-only parameters are placed before a / (forward-slash). The / is used to logically separate the positional-only parameters from the rest of the parameters. If there is no / in the function definition, there are no positional-only parameters.
Parameters following the / may be positional-or-keyword or keyword-only.
4.8.3.3. Keyword-Only Arguments¶
To mark parameters as keyword-only, indicating the parameters must be passed by keyword argument, place an * in the arguments list just before the first keyword-only parameter.
4.8.3.4. Function Examples¶
Consider the following example function definitions paying close attention to the markers / and * :
The first function definition, standard_arg , the most familiar form, places no restrictions on the calling convention and arguments may be passed by position or keyword:
The second function pos_only_arg is restricted to only use positional parameters as there is a / in the function definition:
The third function kwd_only_args only allows keyword arguments as indicated by a * in the function definition:
And the last uses all three calling conventions in the same function definition:
Finally, consider this function definition which has a potential collision between the positional argument name and **kwds which has name as a key:
There is no possible call that will make it return True as the keyword ‘name’ will always bind to the first parameter. For example:
But using / (positional only arguments), it is possible since it allows name as a positional argument and ‘name’ as a key in the keyword arguments:
In other words, the names of positional-only parameters can be used in **kwds without ambiguity.
4.8.3.5. Recap¶
The use case will determine which parameters to use in the function definition:
Use positional-only if you want the name of the parameters to not be available to the user. This is useful when parameter names have no real meaning, if you want to enforce the order of the arguments when the function is called or if you need to take some positional parameters and arbitrary keywords.
Use keyword-only when names have meaning and the function definition is more understandable by being explicit with names or you want to prevent users relying on the position of the argument being passed.
For an API, use positional-only to prevent breaking API changes if the parameter’s name is modified in the future.
4.8.4. Arbitrary Argument Lists¶
Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (see Tuples and Sequences ). Before the variable number of arguments, zero or more normal arguments may occur.
Normally, these variadic arguments will be last in the list of formal parameters, because they scoop up all remaining input arguments that are passed to the function. Any formal parameters which occur after the *args parameter are ‘keyword-only’ arguments, meaning that they can only be used as keywords rather than positional arguments.
4.8.5. Unpacking Argument Lists¶
The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the * -operator to unpack the arguments out of a list or tuple:
In the same fashion, dictionaries can deliver keyword arguments with the ** -operator:
4.8.6. Lambda Expressions¶
Small anonymous functions can be created with the lambda keyword. This function returns the sum of its two arguments: lambda a, b: a+b . Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope:
The above example uses a lambda expression to return a function. Another use is to pass a small function as an argument:
4.8.7. Documentation Strings¶
Here are some conventions about the content and formatting of documentation strings.
The first line should always be a short, concise summary of the object’s purpose. For brevity, it should not explicitly state the object’s name or type, since these are available by other means (except if the name happens to be a verb describing a function’s operation). This line should begin with a capital letter and end with a period.
If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description. The following lines should be one or more paragraphs describing the object’s calling conventions, its side effects, etc.
The Python parser does not strip indentation from multi-line string literals in Python, so tools that process documentation have to strip indentation if desired. This is done using the following convention. The first non-blank line after the first line of the string determines the amount of indentation for the entire documentation string. (We can’t use the first line since it is generally adjacent to the string’s opening quotes so its indentation is not apparent in the string literal.) Whitespace “equivalent” to this indentation is then stripped from the start of all lines of the string. Lines that are indented less should not occur, but if they occur all their leading whitespace should be stripped. Equivalence of whitespace should be tested after expansion of tabs (to 8 spaces, normally).
Here is an example of a multi-line docstring:
4.8.8. Function Annotations¶
Function annotations are completely optional metadata information about the types used by user-defined functions (see PEP 3107 and PEP 484 for more information).
Annotations are stored in the __annotations__ attribute of the function as a dictionary and have no effect on any other part of the function. Parameter annotations are defined by a colon after the parameter name, followed by an expression evaluating to the value of the annotation. Return annotations are defined by a literal -> , followed by an expression, between the parameter list and the colon denoting the end of the def statement. The following example has a required argument, an optional argument, and the return value annotated:
4.9. Intermezzo: Coding Style¶
Now that you are about to write longer, more complex pieces of Python, it is a good time to talk about coding style. Most languages can be written (or more concise, formatted) in different styles; some are more readable than others. Making it easy for others to read your code is always a good idea, and adopting a nice coding style helps tremendously for that.
For Python, PEP 8 has emerged as the style guide that most projects adhere to; it promotes a very readable and eye-pleasing coding style. Every Python developer should read it at some point; here are the most important points extracted for you:
Use 4-space indentation, and no tabs.
4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). Tabs introduce confusion, and are best left out.
Wrap lines so that they don’t exceed 79 characters.
This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.
Use blank lines to separate functions and classes, and larger blocks of code inside functions.
When possible, put comments on a line of their own.
Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4) .
Name your classes and functions consistently; the convention is to use UpperCamelCase for classes and lowercase_with_underscores for functions and methods. Always use self as the name for the first method argument (see A First Look at Classes for more on classes and methods).
Don’t use fancy encodings if your code is meant to be used in international environments. Python’s default, UTF-8, or even plain ASCII work best in any case.
Likewise, don’t use non-ASCII characters in identifiers if there is only the slightest chance people speaking a different language will read or maintain the code.
Actually, call by object reference would be a better description, since if a mutable object is passed, the caller will see any changes the callee makes to it (items inserted into a list).
Циклы
Выполнение программ, написанных на любом языке программирования, по умолчанию является последовательным. Иногда нам может понадобиться изменить выполнение программы. Выполнение определенного кода может потребоваться повторить несколько раз.
Для этого в языках программирования предусмотрены различные типы циклов, которые способны повторять определенный код несколько раз. Чтобы понять принцип работы оператора цикла, рассмотрим следующую схему.

Для чего нужны циклы в python?
Циклы упрощают сложные задачи до простых. Он позволяет нам изменить поток программы таким образом, что вместо того, чтобы писать один и тот же код снова и снова, мы можем повторять его конечное число раз. Например, если нам нужно вывести первые 10 натуральных чисел, то вместо того, чтобы использовать оператор print 10 раз, мы можем вывести их внутри цикла, который выполняется до 10 итераций.
Преимущества циклов
В Python преимущества циклов, как и в других язвках программирования, заключаются в следующем:
- Это обеспечивает возможность повторного использования кода.
- Используя циклы, нам не нужно писать один и тот же код снова и снова.
- С помощью циклов мы можем перебирать элементы структур данных (массивов или связанных списков).
В Python существуют следующие операторы циклов.
Оператор цикла | Описание |
---|---|
for | Цикл for используется в том случае, когда необходимо выполнить некоторую часть кода до тех пор, пока не будет выполнено заданное условие. Цикл for также называют циклом c предусловием. Лучше использовать цикл for, если количество итераций известно заранее. |
while | Цикл while используется в сценарии, когда мы не знаем заранее количество итераций. Блок операторов в цикле while выполняется до тех пор, пока не будет выполнено условие, указанное в цикле while. Его также называют циклом с предварительной проверкой условия. |
do-while | Цикл do-while продолжается до тех пор, пока не будет выполнено заданное условие. Его также называют циклом с пстусловием. Он используется, когда необходимо выполнить цикл хотя бы один раз. |
Цикл for в Python
Цикл for в Python используется для многократного повторения операторов или части программы. Он часто используется для обхода структур данных, таких как список, кортеж или словарь.
Синтаксис цикла for в python приведен ниже.
Цикл For с использованием последовательности
Пример 1: Итерация строки с помощью цикла for
Пример 2: Программа для печати таблицы заданного числа.
Пример 3: Программа для печати суммы заданного списка.
Цикл For с использованием функции range()
Функция range()
Функция range() используется для генерации последовательности чисел. Если мы передадим range(10) , она сгенерирует числа от 0 до 9 . Синтаксис функции range() приведен ниже.
- Start означает начало итерации.
- Stop означает, что цикл будет повторяться до stop-1. range(1,5) будет генерировать числа от 1 до 4 итераций. Это необязательный параметр.
- Размер шага используется для пропуска определенных чисел в итерации. Его использование необязательно. По умолчанию размер шага равен 1. Это необязательно.
Рассмотрим следующие примеры:
Пример 1: Программа для печати чисел по порядку.
Пример 2: Программа для печати таблицы заданного числа.
Пример 3: Программа для печати четного числа с использованием размера шага в range().
Мы также можем использовать функцию range() с последовательностью чисел. Функция len() сочетается с функцией range() , которая выполняет итерацию по последовательности с использованием индексации. Рассмотрим следующий пример.
Вложенный цикл for в python
Python позволяет нам вложить любое количество циклов for внутрь цикла for. Внутренний цикл выполняется n раз за каждую итерацию внешнего цикла. Синтаксис приведен ниже.
Пример 1: Вложенный цикл for
Пример 2: Программа для печати пирамиды чисел.
Использование оператора else в цикле for
В отличие от других языков, таких как C, C++ или Java, Python позволяет нам использовать оператор else с циклом for , который может быть выполнен только тогда, когда все итерации исчерпаны. Здесь мы должны заметить, что если цикл содержит какой-либо оператор break, то оператор else не будет выполнен.
Цикл for полностью исчерпал себя, так как нет прерывания.
В приведенном выше примере цикл прерван из-за оператора break, поэтому оператор else не будет выполнен. Будет выполнен оператор, находящийся непосредственно рядом с блоком else .
Цикл был прерван, благодаря оператору break.
Цикл while в Python
Цикл while позволяет выполнять часть кода до тех пор, пока заданное условие не станет ложным. Он также известен как цикл с предварительной проверкой условия.
Его можно рассматривать как повторяющийся оператор if . Когда мы не знаем количество итераций, цикл while является наиболее эффективным.
Синтаксис приведен ниже.
Здесь утверждения могут быть одним утверждением или группой утверждений. Выражение должно быть любым допустимым выражением Python, приводящим к true или false . Истиной является любое ненулевое значение, а ложью — 0 .
Операторы управления циклом
Мы можем изменить обычную последовательность выполнения цикла while с помощью оператора управления циклом. Когда выполнение цикла while завершается, все автоматические объекты, определенные в этой области видимости, уничтожаются. Python предлагает следующие управляющие операторы для использования в цикле while.
1. Оператор continue — Когда встречается оператор continue , управление переходит в начало цикла. Давайте разберем следующий пример.
2. Оператор break — Когда встречается оператор break , он выводит управление из цикла.
3. Оператор pass — Оператор pass используется для объявления пустого цикла. Он также используется для определения пустого класса, функции и оператора управления. Давайте разберем следующий пример.
Пример 1: Программа для печати от 1 до 10 с использованием цикла while
Пример 2: Программа для печати таблицы заданных чисел.
Бесконечный цикл while
Если условие, заданное в цикле while, никогда не станет ложным, то цикл while никогда не завершится, и он превратится в бесконечный цикл while.
Любое ненулевое значение в цикле while указывает на всегда истинное состояние, в то время как ноль указывает на всегда ложное состояние. Такой подход полезен, если мы хотим, чтобы наша программа непрерывно выполнялась в цикле без каких-либо помех.
Использование else в цикле while
Python позволяет нам также использовать оператор else с циклом while . Блок else выполняется, когда условие, заданное в операторе while , становится ложным. Как и в случае с циклом for , если цикл while прервать с помощью оператора break , то блок else не будет выполнен, а будет выполнен оператор, присутствующий после блока else . Оператор else необязателен для использования с циклом while . Рассмотрим следующий пример.
В приведенном выше коде, когда встречается оператор break , цикл while останавливает свое выполнение и пропускает оператор else .
Программа для печати чисел Фибоначчи до заданного предела
Оператор прерывания в Python
Break — это ключевое слово в python, которое используется для вывода управления программой из цикла. Оператор break разрывает циклы по одному, то есть в случае вложенных циклов он сначала разрывает внутренний цикл, а затем переходит к внешним циклам. Другими словами, можно сказать, что break используется для прерывания текущего выполнения программы, и управление переходит на следующую строку после цикла.
Прерывание обычно используется в тех случаях, когда нам нужно прервать цикл при заданном условии.
Синтаксис прерывания приведен ниже.
Пример: оператор break с циклом while
Оператор continue в Python
Оператор continue в Python используется для возврата управления программой в начало цикла. Оператор continue пропускает оставшиеся строки кода внутри цикла и начинает следующую итерацию. В основном он используется для определенного условия внутри цикла, чтобы мы могли пропустить определенный код для конкретного условия.
Рассмотрим следующие примеры.
Обратите внимание на вывод приведенного выше кода, значение 5 пропущено, потому что мы предоставили условие if с помощью оператора continue в цикле while . Когда оно совпадает с заданным условием, управление передается в начало цикла while , и он пропускает значение 5 из кода.
Давайте посмотрим на другой пример:
Оператор pass в python
Оператор pass является нулевым оператором (null operation), поскольку при его выполнении ничего не происходит. Он используется в тех случаях, когда оператор синтаксически необходим, но мы не хотим использовать вместо него какой-либо исполняемый оператор.
Например, он может быть использован при переопределении метода родительского класса в подклассе, но мы не хотим давать его конкретную реализацию в подклассе.
Pass также используется в тех случаях, когда код будет записан где-то, но еще не записан в программном файле. Рассмотрим следующий пример.
Python цикл Do While
В Python нет цикла do while. Но мы можем создать подобную программу.
Цикл do while используется для проверки условия после выполнения оператора. Он похож на цикл while, но выполняется хотя бы один раз.
Работа с циклами 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 — универсальная управляющая конструкция
Циклы являются мощнейшим инструментом, предоставляемым высокоуровневыми языками программирования. Эти управляющие конструкции позволяют многократно выполнять требуемую последовательность инструкций. Циклы в языке Python представлены двумя основными конструкциями: while и for .
Применение циклов
Концепция циклов — это не просто очередная абстрактная выдумка программистов. Повторяющиеся раз за разом операции окружают нас и в реальной жизни:
— всё это циклы, и представить нормальную жизнь без них попросту невозможно.
Впрочем, то же касается и программирования. Представьте, что вам нужно последовательно напечатать числа от 1 до 9999999999. В отсутствии циклов, эту задачу пришлось бы выполнять ручками, что потребовало бы колоссального количества кода и огромных временных затрат:
print(1) print(2) print(3) # . # 9999999995 строк # . print(9999999998) print(9999999999)
Циклы же позволяют уместить такую многокилометровую запись в изящную и простую для понимания конструкцию, состоящую всего из двух строчек:
for i in range(1, 10000000000): print(i)
Смысл её крайне прост. В основе цикла for лежат последовательности, и в примере выше это последовательность чисел от 1 до 9999999999. for поэлементно её перебирает и выполняет код, который записан в теле цикла. В частности, для решения данной задачи туда была помещена инструкция, позволяющая выводить значение элемента последовательности на экран.
Итерации
- Итерация (Iteration) — это одно из повторений цикла (один шаг или один "виток" циклического процесса). К примеру цикл из 3-х повторений можно представить как 3 итерации.
- Итерируемый объект (Iterable) — объект, который можно повторять. Проще говоря это объект, который умеет отдавать по одному результату за каждую итерацию.
- Итератор (iterator) — итерируемый объект, в рамках которого реализован метод __next__, позволяющий получать следующий элемент.
Чтобы выполнить итерацию, Python делает следующее:
- Вызывает у итерируемого объекта метод iter() , тем самым получая итератор.
- Вызывает метод next() , чтобы получить каждый элемент от итератора.
- Когда метод next возвращает исключение StopIteration , цикл останавливается.
Пример создания итерируемого объекта Для того чтобы создать собственный класс итерируемого объекта, нужно всего лишь внутри него реализовать два метода: __iter__() и __next__() :
- внутри метода __next__ () описывается процедура возврата следующего доступного элемента;
- метод __iter__() возвращает сам объект, что даёт возможность использовать его, например, в циклах с поэлементным перебором.
Создадим простой строковый итератор, который на каждой итерации, при получении следующего элемента (т.е. символа), приводит его к верхнему регистру:
class ToUpperCase: def __init__(self, string_obj, position=0): """сохраняем строку, полученную из конструктора, в поле string_obj и задаём начальный индекс""" self.string_obj = string_obj self.position = position def __iter__(self): """ возвращаем сам объект """ return self def __next__(self): """ метод возвращает следующий элемент, но уже приведенный к верхнему регистру """ if self.position >= len(self.string_obj): # исключение StopIteration() сообщает циклу for о завершении raise StopIteration() position = self.position # инкрементируем индекс self.position += 1 # возвращаем символ в uppercase-e return self.string_obj[position].upper() low_python = "python" high_python = ToUpperCase(low_python) for ch in high_python: print(ch, end="") > PYTHON
Синтаксис for
Как было замечено, цикл for python — есть средство для перебора последовательностей. С его помощью можно совершать обход строк, списков, кортежей и описанных выше итерируемых объектов.
В простейшем случае он выглядит так:
for item in collection: # do something
Если последовательность collection состоит, скажем, из 10 элементов, for будет поочерёдно обходить их, храня значение текущего элемента в переменной item .
Принцип работы for максимально схож с таковым у циклов foreach , применяемых во многих других высокоуровневых языках.
aliceQuote = "The best way to explain it is to do it." # с помощью цикла for посчитаем количество символов (с пробелами) в строке # зададим счетчик count = 0 # будем посимвольно обходить весь текст for letter in aliceQuote: # на каждой новой итерации: # в переменной letter будет храниться следующий символ предложения; # увеличиваем счетчик на 1; count += 1 print(count) > 39
range() и enumerate()
Вы уже наверняка запомнили, что for работает с последовательностями. В программировании очень часто приходится повторять какую-то операцию фиксированное количество раз. А где упоминается "количество чего-то", существует и последовательность, числовая.
Для того чтобы выполнить какую-либо инструкцию строго определенное число раз, воспользуемся функцией range() :
# скажем Миру привет целых пять раз! for i in range(5): print("Hello World!") > Hello World! Hello World! Hello World! Hello World! Hello World!
range() можно представлять, как функцию, что возвращает последовательность чисел, регулируемую количеством переданных в неё аргументов. Их может быть 1, 2 или 3:
- range(stop) ;
- range(start, stop) ;
- range(start, stop, step) .
Здесь start — это первый элемент последовательности (включительно), stop — последний (не включительно), а step — разность между следующим и предыдущим членами последовательности.
# 0 — начальный элемент по умолчанию for a in range(3): print(a) > 0 1 2 # два аргумента for b in range(7, 10): print(b) > 7 8 9 # три аргумента for c in range(0, 13, 3): print(c) > 0 3 6 9 12
Чрезвычайно полезная функция enumerate() определена на множестве итерируемых объектов и служит для создания кортежей на основании каждого из элементов объекта. Кортежи строятся по принципу (индекс элемента, элемент) , что бывает крайне удобно, когда помимо самих элементов требуется ещё и их индекс.
# заменим каждый пятый символ предложения, начиная с 0-го, на * text = "Это не те дроиды, которых вы ищете" new_text = "" for char in enumerate(text): if char[0] % 5 == 0: new_text += '*' else: new_text += char[1] print(new_text) > *то н* те *роид*, ко*орых*вы и*ете
break и continue
Два похожих оператора, которые можно встретить и в других языках программирования.
- break — прерывает цикл и выходит из него;
- continue — прерывает текущую итерацию и переходит к следующей.
Здесь видно, как цикл, дойдя до числа 45 и вернув истину в условном выражении, прерывается и заканчивает свою работу.
# continue for num in range(40, 51): if num == 45: continue print(num) > 40 41 42 43 44 46 47 48 49 50
В случае continue происходит похожая ситуация, только прерывается лишь одна итерация, а сам же цикл продолжается.
Если два предыдущих оператора можно часто встречать за пределами Python, то else , как составная часть цикла, куда более редкий зверь. Эта часть напрямую связана с оператором break и выполняется лишь тогда, когда выход из цикла был произведен НЕ через break .
group_of_students = [21, 18, 19, 21, 18] for age in group_of_students: if age < 18: break else: print('Всё в порядке, они совершеннолетние') > Всё в порядке, они совершеннолетние
Best practice
Цикл по списку
Перебрать list в цикле не составляет никакого труда, поскольку список — объект итерируемый:
# есть список entities_of_warp = ["Tzeench", "Slaanesh", "Khorne", "Nurgle"] # просто берём список, «загружаем» его в цикл и без всякой задней мысли делаем обход for entity in entities_of_warp: print(entity) > Tzeench Slaanesh Khorne Nurgle
Так как элементами списков могут быть другие итерируемые объекты, то стоит упомянуть и о вложенных циклах. Цикл внутри цикла вполне обыденное явление, и хоть количество уровней вложенности не имеет пределов, злоупотреблять этим не следует. Циклы свыше второго уровня вложенности крайне тяжело воспринимаются и читаются.
strange_phonebook = [ ["Alex", "Andrew", "Aya", "Azazel"], ["Barry", "Bill", "Brave", "Byanka"], ["Casey", "Chad", "Claire", "Cuddy"], ["Dana", "Ditrich", "Dmitry", "Donovan"] ] # это список списков, где каждый подсписок состоит из строк # следовательно можно (зачем-то) применить тройной for # для посимвольного чтения всех имён # и вывода их в одну строку for letter in strange_phonebook: for name in letter: for character in name: print(character, end='') > A l e x A n d r e w A y a A z a z e l B a r .
Цикл по словарю
Чуть более сложный пример связан с итерированием словарей. Обычно, при переборе словаря, нужно получать и ключ и значение. Для этого существует метод .items() , который создает представление в виде кортежа для каждого словарного элемента.
Цикл, в таком случае, будет выглядеть следующим образом:
# создадим словарь top_10_largest_lakes = < "Caspian Sea": "Saline", "Superior": "Freshwater", "Victoria": "Freshwater", "Huron": "Freshwater", ># обойдём его в цикле for и посчитаем количество озер с солёной водой и количество озёр с пресной salt = 0 fresh = 0 # пара "lake, water", в данном случае, есть распакованный кортеж, где lake — ключ словаря, а water — значение. # цикл, соответственно, обходит не сам словарь, а его представление в виде пар кортежей for lake, water in top_10_largest_lakes.items(): if water == 'Freshwater': fresh += 1 else: salt += 1 print("Amount of saline lakes in top10: ", salt) print("Amount of freshwater lakes in top10: ", fresh) > Amount of saline lakes in top10: 1 > Amount of freshwater lakes in top10: 3
Цикл по строке
Строки, по сути своей — весьма простые последовательности, состоящие из символов. Поэтому обходить их в цикле тоже совсем несложно.
word = 'Alabama' for w in word: print(w, end=" ") > A l a b a m a
Как сделать цикл for с шагом
Цикл for с шагом создается при помощи уже известной нам функции range , куда, в качестве третьего по счету аргумента, нужно передать размер шага:
# выведем числа от 100 до 1000 с шагом 150 for nums in range(100, 1000, 150): print(nums) > 100 250 400 550 700 850
Обратный цикл for
Если вы еще не убедились в том, что range() полезна, то вот ещё пример: благодаря этой функции можно взять и обойти последовательность в обратном направлении.
# выведем числа от 40 до 50 по убыванию # для этого установим step -1 for nums in range(50, 39, -1): print(nums) > 50 49 48 47 46 45 44 43 42 41 40
for в одну строку
Крутая питоновская фишка, основанная на так называемых list comprehensions или, по-русски, генераторов. Их запись, быть может, несколько сложнее для понимания, зато очевидно короче и, по некоторым данным, она работает заметно быстрее на больших массивах данных.
В общем виде генератор выглядит так:
[результирующее выражение | цикл | опциональное условие]
Приведем пример, в котором продублируем каждый символ строки inputString :
# здесь letter * 2 — результирующее выражение; for letter in inputString — цикл, а необязательное условие опущено double_letter = [letter * 2 for letter in "Banana"] print(double_letter) > ['BB', 'aa', 'nn', 'aa', 'nn', 'aa']
Другой пример, но теперь уже с условием:
# создадим список, что будет состоять из четных чисел от нуля до тридцати # здесь if x % 2 == 0 — необязательное условие even_nums = [x for x in range(30) if x % 2 == 0] print(even_nums) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]