Contents:

Course with employment: "The Python Developer Profession"
Learn morePython code is typically executed sequentially: from the first line to the last. However, there are certain constructs that allow you to deviate from this linear order of execution, making it possible to perform more complex operations and control the flow of the program. These constructs include conditional statements, loops, and functions, giving developers the flexibility to write efficient and dynamic algorithms.
Loops are an important part of programming, allowing you to execute the same block of code multiple times. There are two main types of loops in Python: while and for. Let's consider their features and applications. The while loop executes code as long as the specified condition is true, making it useful for situations where the number of iterations is not known in advance. The for loop, on the other hand, is used to iterate over elements in sequences such as lists or strings, making it convenient to process collections of data. Both types of loops are indispensable tools in a developer's arsenal, providing flexibility and efficiency in writing code.
- How Loops Work
- The while loop in Python
- The for loop in Python
- The range() function
- Single-line loop: List comprehension
- Breaking a loop: the break keyword
- Skipping part of a loop: the continue keyword
- The last action in a loop: the else keyword
- Infinite loop
- How to make an analogue of do while in Python
- Nested loops in Python
How Loops Work
Every loop includes two main elements: conditions and actions. Conditions determine when a loop should begin and end, and actions determine what happens during its execution. Proper use of these components allows you to create efficient and optimized loops in programming, significantly improving code performance and making it easier to maintain.
- condition - initial parameter; The loop will start only when it is executed and will end as soon as the condition is no longer met;
- The body is the program itself, which is executed inside the loop.
This can be schematically depicted as follows:

Python syntax uses a colon at the end of a line containing a condition, after which the entire body of the condition is indented, which can be done using a tab or four spaces. This rule structures the code and makes it more readable, and also helps avoid errors associated with improper indentation. Proper use of indentation is critical in Python, as it defines blocks of code and the logical structure of the program.
The While Loop in Python
The While loop is one of the simplest and most intuitive types of loops in programming. It is also called a while loop, because execution of the code block continues as long as the specified condition is true. This approach allows for efficient management of repeating operations, making the While loop an indispensable tool for developers.
This program can be translated from Python into Russian as follows: "While variable x is less than five, display the value of x and increment it by one."
The simplicity of the while construct conceals a danger: it can lead to the creation of an infinite loop. For example, if you remove the line x += 1 in the code above, the program will continue to execute indefinitely, since the condition for exiting the loop will never change. This can cause the application or system to freeze. Therefore, it is important to always monitor the loop logic and ensure that the exit condition is met.
In this case, the variable x remains unchanged and is always equal to one. This results in the loop condition remaining true, and the loop never completes its execution. As a result, the program may freeze or run indefinitely, which is unacceptable for the correct execution of algorithms. To avoid this situation, you need to change the value of the x variable inside the loop so that the condition can become false and the loop will terminate.
When using the while loop, it's important to ensure that the condition becomes false at some point. This will help avoid infinite loops. It's also recommended to use the break statement, which allows you to interrupt the loop at the right time. We'll cover its use in more detail later.
The for Loop in Python
The for loop is used significantly more often by programmers than the while loop. Unlike the while loop, which sets a condition, in the for loop we work with iterable objects such as arrays, lists, tuples, strings, dictionaries, or ranges. This allows you to conveniently and efficiently process collection elements and perform repeated actions with each element, which makes the for loop a more versatile tool in programming.
At each iteration of the loop, the program checks if there are any elements left in the object that have not yet been processed.
Suppose we have an array of numbers: [14, 101, -7, 0]. We can use the for loop to display each element of the array on the screen individually. Using the for loop allows you to efficiently process the elements of the list, which makes this approach convenient for working with data in programming.
The number variable is updated with each new iteration of the loop. Initially, it contains the first element, then the second, and this continues until the entire list is processed. This allows you to efficiently loop through all the elements and perform the necessary operations with each of them.
Variables in programming can have any names, and the number variable is no exception. The letters i, j, and k are often used to denote counters in loops. If we don't access the variable during the loop, it's common practice in the Python programming community to use the underscore _. This indicates that the variable won't be used and makes the code more readable and understandable. Using variable names correctly is an important aspect of writing quality code.
To apply a for loop to a numeric range, you can use the range() function. This function allows you to specify a range of values by accepting one to three arguments. With range(), you can easily control the start, end, and step of a sequence of numbers, making it a convenient tool for iteration in Python.
With one argument, it creates a range that starts at zero and ends with the number preceding the value of that argument.
With two arguments, it creates a range that spans the values from the first argument to the number preceding the second argument.
If you have three arguments, the first two function similarly to the previous example. The third argument determines the step at which the numbers are arranged sequentially.
When only one action is performed within a for loop, Python syntax provides an opportunity to simplify the notation.
Syntactic sugar is a programming language element that does not add new functionality but significantly improves the readability and structure of the code. Using syntactic sugar allows you to quickly and easily create lists, which makes the code more understandable and easier to perceive. This is especially useful when working with large amounts of data, where a clear structure is critical to maintaining order and efficiency.
An additional condition can be added to this construction. Let's create a generator that will output only even numbers. In this case, we will not create a separate variable for the resulting list, but will directly display the result.
The if i % 2 == 0 construction is used to check whether the number i is even. This condition means that when i is divided by 2, the remainder is 0, which indicates that the number is even. In programming, this construct is often used to filter and process even values in various algorithms and logical operations.
The variable i allows for various operations. In this case, we will use the previous generator to output not even numbers themselves, but their squares. This approach allows for a deeper exploration of working with numbers and their transformations in programming. Squares of even numbers have their own unique properties and can be useful in various mathematical and programming tasks.
When using this approach, it is important not to overcomplicate the code. If the code becomes difficult to read and understand, for example, when multiple functions and methods are applied to the variable i simultaneously, or when complex conditions are specified, it is recommended to split it into multiple lines. Code clarity is more important than brevity. A clear structure and clarity significantly improve the ease of use of code and facilitate its future maintenance.
Breaking a Loop: The Break Keyword
In programming, there is sometimes a need to forcefully terminate a loop, even if its condition remains true. For this, the break keyword is used. This construct allows you to exit the loop at any time, which can be useful in situations where execution must be interrupted due to certain conditions or errors. Using break makes code more flexible and manageable, allowing you to effectively control the flow of program execution.
Let's look at the string «Hi, loop!» and print each character individually. If we encounter a comma, the loop will terminate prematurely. This approach allows us to control the process of iterating over characters, which can be useful in various programming scenarios.
If the string is missing a comma, the loop will iterate through each character in the string before terminating.
Skipping Part of a Loop: The Continue Keyword
Sometimes you need to force a transition to the next iteration of a loop, skipping the execution of certain lines in its body. In such cases, the continue keyword is used. It allows you to effectively control the process of loop execution, reducing program execution time and improving code readability. Using continue helps avoid redundant operations and focus on those parts of the loop that are truly important to the program logic.
Consider the numbers from 1 to 10 and select only those that are not divisible by either 2 or 3. To do this, we analyze each number in the given range. Numbers that meet the conditions will be useful in various problems related to numerical sequences and mathematical research. Thus, we get a list of numbers that meet the specified criteria, which can be useful for further calculations or analysis.
If the if condition is true (that is, the number is divisible by 2 or 3 without a remainder), then the rest of the code is not executed, and the variable i is not displayed. This behavior demonstrates how to use conditional statements to control the flow of program execution. Make sure you handle conditions correctly to avoid unwanted results.
The Last Action in a Loop: The Else Keyword
The else keyword is most often used in combination with the if statement, but its uses are not limited to this case. else can also be used in combination with while and for loops. In such situations, the code located after else will be executed after all loop iterations are completed. This allows you to effectively manage the program flow and handle the results of loops.
If the loop is terminated early with the break statement, the code block in else will not be executed. This is important to consider when designing program logic, as skipping the execution of certain instructions can lead to undesired application behavior.
Let's look at our code containing the line «Hi, loop!», and add the else statement. This will allow us to extend the functionality of the program by providing an alternative action if the specified condition is not met. Using else in your code makes it more flexible and allows you to handle different scenarios, which in turn improves the logic and structure of your application.
There was a comma in the line, which caused the break statement to be triggered, and the else condition was not met. Now let's remove the comma and analyze what happens as a result.
The loop completed all its iterations and automatically terminated, which led to the execution of the code in the else block. This code will also be executed if the loop has not completed a single iteration.
Infinite Loop
Using an infinite loop in programming can be a justified solution in certain situations. For example, when developing a game program, an infinite loop can ensure the continuous functioning of the game until the player decides to leave it. In such cases, it is important to properly implement the exit condition, using the break statement to end the loop and ensure the game ends gracefully. This creates a more dynamic and interactive experience for the user, who can control the time spent in the game.
To create an infinite loop, its condition must remain true for the entire execution time. There are several ways to achieve this result. For example, you can use a condition that always returns true, or set a variable that never changes. Properly implementing an infinite loop requires careful consideration to avoid potential problems such as program freezing or excessive resource usage.
Setting the while loop condition to False causes the loop to not start at all. This is important to consider when writing code to avoid infinite loops or skipping necessary operations. Properly setting the loop condition is a key aspect of programming, as it determines whether the code inside the loop will be executed.
Setting the while loop condition to 0 causes the loop to not start. As a result, the program will not execute any iterations, and the code inside the loop will remain unprocessed. This is important to keep in mind when writing code, as incorrectly initializing the condition can lead to unexpected results and make debugging difficult. Proper use of conditions in loops is a key aspect of effective programming.
If you use an empty element, such as a string str() or an empty list list(), in the while statement, the loop will not start. This is because the while loop condition checks the truth of the expression, and if it is empty or equal to zero, the loop will not be executed. Therefore, it is important to formulate the condition for starting the loop correctly to ensure its correct operation.
An alternative approach is to place a variable containing the corresponding condition after the while statement. This allows for more flexible control of the loop and improves code readability. This method can be useful in situations where it is necessary to dynamically change the loop execution conditions, leading to more efficient and understandable programming.
In situations where it is necessary to terminate a loop, you can do without the break statement. Instead, simply change the value of the condition variable to False, 0, None, or any empty element. This way, the loop will terminate its last pass, since the condition will no longer be met. This approach allows you to keep the code more readable and understandable by avoiding unnecessary flow control statements.
This approach is used to terminate a loop from various parts of a program, including functions or nested loops. It is important to note that since the loop terminates naturally, without using the break statement, the code located in the else block, if provided, will be executed. This allows for more flexible control of the program execution logic and avoids unexpected breaks in the loop, which can improve the readability and maintainability of the code.
How to make an analogue of do while in Python
In a number of programming languages, there is a loop with a postcondition, which is guaranteed to be executed at least once before checking the condition. This means that the loop body will be executed at least once, even if the condition is not met. This behavior differs from other types of loops, such as conditional loops, which may never execute if the condition is initially false. A loop with a postcondition is often used in situations where an action must be performed at least once before deciding whether to continue execution.

In programming languages In Java and C++, the do while construct allows a block of code to be executed at least once before checking its condition. Python does not have such a construct, but it is possible to implement similar behavior. To do this, use an infinite loop, within which you must specify a condition to exit the loop. This approach achieves the desired result by ensuring that the code is executed before checking the termination condition.
The loop, regardless of the value of the x variable, will execute at least one pass. This is the main property of a postcondition in programming. A postcondition ensures that a certain condition is met after the loop terminates, which is important for the correctness of the algorithm.
Nested Loops in Python
Python allows you to create nested loops, which means that one loop can be inside another. This complicates the program logic, but allows you to perform more complex tasks. Nested loops can be used to process multidimensional data structures, such as lists or arrays, and provide flexibility in algorithms that require repeated iteration of data. Proper use of nested loops can significantly improve the efficiency of problem solving, but it is important to monitor performance, as increasing the depth of nesting can lead to a significant increase in program execution time.

Nesting loops in programming allows you to create complex structures and algorithms. With each new level of nesting, you should increase the indentation to ensure code readability. This not only helps you understand the program's logic but also simplifies debugging. Each loop can contain its own operations, and proper indentation plays a key role in code organization. As a result, well-structured code with clear indentation makes it easier to read and maintain.
Let's create a program that displays the iteration numbers of both the outer and inner loops. This program will allow you to clearly see how nested loops work and interact with each other. As a result of executing the program, the user will be able to easily track the current iterations of each loop, which will help to better understand the structure and logic of nested repetitions.

