while loop in Python. How it works, examples of use

Loops are one of the main tools of any language. There are two basic loops in Python, one of which is while. Consider it, and also for a better understanding of the picture, one more. Indeed, in comparison with something similar, it is much easier to understand any material, isn’t it?

The concept of a cycle

A loop is needed when a certain action needs to be performed multiple times. This is very simplistic, because in reality the range of applications for cycles is much wider. There are two main types of loops in Python: for and while. The most popular is for.

In addition to specific actions, you can loop different pieces of code up to a certain point. This can be a certain number of times, or as long as a particular condition is true.

Before we begin to understand the types of loops and while, in particular, we still need to understand what iteration is. This is one repetition of an action or sequence of actions during the current cycle within the current application run.

Cycle For

Our For loop is not a counter, as in many other languages. Its task is to enumerate a certain sequence of values. What does this mean? Let’s say we have a list of elements. First, the loop takes the first, second, third, and so on.

The advantage of this loop in Python is that you don’t need to determine the index of the element to know when to exit the loop. Everything will be done automatically.

>>> spisok = [10, 40, 20, 30]

>>> for element in spisok:

…     print(element + 2)

12

42

22

32

In our example, we used the variable element after the for command. In general, the name can be anything. For example, a popular designation is i. And with each iteration, this variable will be assigned a specific object from the list, which we called the appropriate word.

In our case, the list is a sequence of numbers 10,40,20,30. At each iteration, the corresponding value appears in the variable. For example, as soon as the loop starts, the variable element the value 10 is assigned. On the next iteration, the ten turns into the number 40, the third time it turns into the number 20, and finally, on the last iteration of the loop, it turns into 30.

The signal for the end of the cycle is the end of the elements in the list.

If you need the loop to perform a classic enumeration of values, as in other programming languages, you should create a list with a sequence of natural numbers up to the value we need.

>>> spisok = [1,2,3,4,5]

Or use the function len(), to determine the length of the list. But in this case it is better to use a loop while, because there is no need to use a variable.

If you need to change the sequence of values ​​in the list, loop for and here comes to the rescue. To do this, at each iteration, each element of the list must be assigned an appropriate value.

While Loop

Unlike the cycle for, which simply iterates over the values ​​of the sequence, the loop while has more uses. The name of this type of cycles is translated as “yet”. That is, “until”.

This is a universal loop that is found in all programming languages. And in some ways it resembles a conditional operator yew, which performs a check to see if a certain condition is met. Only in contrast to the conditional operator, while performs the check at each iteration, not just once. And only if the condition is false, the loop ends and the command that follows it is executed. In simple words, if the situation in which he works is no longer valid.

If we draw a cycle while simplistically, this is done using such a scheme.while loop in Python. How it works, examples of use

The main branch of the program (which runs outside the loop) is depicted in this figure with blue rectangles. Turquoise represents the body of the cycle. In turn, a rhombus is a condition that is checked at each iteration.

Cycle while can result in two exceptions:

  1. If at the beginning of the loop the logical expression does not return true, then it simply does not begin, having completed before execution. In general, this situation is normal, because under certain circumstances, the application may not provide for the presence of expressions in the loop body.
  2. If the expression is always true, this can lead to a loop. That is, to the endless scrolling of the cycle. Therefore, in such programs, there should always be an exit statement from the loop or program. However, this situation will arise if the program was able to determine the truth or falsity of a particular condition. If she failed to do this, then an error is returned with the termination of the program. Or you can handle the error, and then, if it occurs, certain code will be executed.

There can be a huge number of options for how to handle an error. For example, the program may ask the user to enter data correctly. So, if a person indicated a negative number where it can only be positive, or entered letters where only numbers should be, the program can tell about it.

While Loop Examples

Here is an example of code that handles an error in this case.

n = input(“Enter an integer: “) 

while type(n) != int:

    Try:

        n = int(n)

    except ValueError:

        print(“Wrong entry!”)

        n = input(“Enter an integer: “) 

if n % 2 == 0:

    print(“Even”)

else:

    print(“Odd”)

Keep in mind that Python uses colons to declare complex code constructs.

In the code above, we defined as a condition that we should check if the number is an integer. If yes, then false is returned. If not, then true.

In the second part of the code, where the operator is used if, we used the % operator to find the remainder after the division operation. The next step is to check if the number is even. If not, then the remainder is one in this case. Accordingly, the number is odd. 

In simple terms, the above code first checks if the string entered by the user is a number. If yes, then a second check is made to see if there is a remainder of the division by two. But the second block will not be executed until the value entered by the user is numeric.

That is, the loop will be regularly executed until the condition occurs. In this situation, it works like this. 

That is, you can go from the opposite: loop a certain action until the event becomes false.

Code parsing

Now let’s see in more detail how this code works. To do this, we will analyze it step by step.

  1. First, the user enters a string, which is accepted by the variable n. 
  2. Using a loop while the type of this variable is checked. On the first entry, it is not equal int. Therefore, as a result of the test, it is found that this condition is true. Therefore, the loop body is entered.
  3. With the help of an operator try we’re trying to convert a string to a number. If this is done, then no error occurs. Accordingly, there is no need to process it. Therefore, the interpreter returns to the beginning of the loop, and according to the results of the check, it turns out that it has become an integer. So let’s go to step 7
  4. If the conversion was unsuccessful, then a ValueError is thrown. In this case, the program flow is sent to the except handler.
  5. The user enters a new value, which is assigned to the variable n.
  6. The interpreter returns to step 2 and checks again. If it is an integer value, go to step 7. If not, the conversion is attempted again according to step 3.
  7. With the help of an operator if Determines if there is a remainder after dividing a number by 2. 
  8. If not, the text “even” is returned.
  9. If not, the text “odd” is returned.

Consider now such an example. Try to determine how many times this cycle will go through?

total = 100 

i = 0

while i < 5:

    n = int(input())

    total = total — n

    i = i + 1 

print(“Remaining”, total)

The correct answer is 5. Initially, the value of the variable i – zero. The interpreter checks if the variable is equal i 4 or less. If yes, then the value is returned. true, and the loop is executed accordingly. The value is increased by one.

After the first iteration, the value of the variable becomes 1. A check is performed, and the program understands that this number is again less than 5. Accordingly, the loop body is executed for the second time. Since the steps are similar, the value is also increased by one, and the variable is now equal to 2.

This value is also less than five. Then the loop is executed a third time, added to the variable i 1 and it is assigned the value 3. This is again less than five. And so it comes to the sixth iteration of the loop, at which the value of the variable i equals 5 (after all, it was originally zero, as far as we remember). Accordingly, this condition does not pass the test, and the loop is automatically terminated and the transition to the next step, which is outside it (or program termination, if the following steps are not provided), is carried out.

The cycle can also occur in the opposite direction. Here is an example of code where, with each subsequent iteration, one is subtracted from the current value of the variable. 

total = 100 

while total > 0:

    n = int(input())

    total = total — n 

print(“Resource exhausted”)

Try to guess what this program does! Imagine that in a variable total information about the program resource is stored. Each time the interpreter checks if the resource exists. If not, then the text “Resource exhausted” is displayed and the program closes. And with each iteration of the loop, the resource decreases by the number that the user specifies.

And now homework. Try changing the above code so that the variable cannot physically become negative. 

4 Comments

  1. si code ahaan usoo gudbi

Leave a Reply