loops python, python loop, while loop in python, python while loop, while python, python while

Greeting learners! Welcome to the new tutorial on Python, where we are going to discuss the loops. In the previous lecture, our focus was on the primary introduction of the loops in Python. If you are from a programming background, you must know that there is a little bit of difference between the loops in Python and those in other programming languages. At the end of the previous lecture, we saw the details of the basic differences and examined why we consider Python better than other languages when considering loops. In the current lecture, our focus is only on the while loop, and you will get to know its importance soon when we discuss the detail of this loop. But before this, have a look at the list of the major concepts:

  • What are the loops?

  • Why do we use the while loop in Python?

  • What are some major points that must be known about the while loop in Python?

  • Can we use the loops while designing the games?

  • What is the concept of statements in Python?

  • How do break statements work in Python?

  • What do you know about the continue statement in Python?

  • What does the else statement do in Python when we use it with the while loop?

All of these are important interview questions and we will find the answer to each and every concept in detail with the example. We have been working with the Jupyter Notebook and therefore, we are again using it for the practical implementation of the concepts of the current lecture. So let’s move towards the first concept.

loops python, python loop, while loop in python, python while loop, while python, python while

Why Do We use While Loop in Python?

While loop is one of the most common loops in programming languages and if we talk about Python, loops have fundamental importance and while loop is the favorite of many programmers. No one can get excellence in programming in Python without knowing the detail of the loops in it. The reason why we are learning it so deeply is, there is a bit of difference between Python loops and other programming languages. We discussed it in the previous lecture. There are different reasons behind this statement, and some of them are explained next:

loops python, python loop, while loop in python, python while loop, while python, python while

Repeating Action in While Loop

As all the loops do, the while loop repeats itself until a certain condition is satisfied. There is no restriction on the data type in the loop, which means, no matter if you have sequences, strings, integers, or other data types, you can use the while loop anywhere. This gives the programmer the independence to use it in a versatile way by using their creativity. Moreover, keep in mind the condition where the programmer wants to get input from the user after a certain condition is met in the code. In such cases, a while loop is perfect to use, and the restriction can be applied to the input as well. 

While Loop on Sequence of Unknown Length

The idea of the condition is so smooth in the while loop that it becomes interesting to use the sequences in the while loop. In some cases, when the length of the sequence is not known, programmers can use the sequence in the while loop to get the required result. In this way, the compiler keeps iterating the sequence until a certain condition is met. 

Gaming and While Loop

Have you ever noticed the condition of a game where the sequence of certain objects keeps on moving in a specific sequence? This happens when the loops are used with special planning, and the while loop is one of those loops that provide the perfect results according to the needs of the program. In the simulations where a certain condition is to be fulfilled, the need for the while loop is always felt. 

In addition, when the need to fulfil a certain condition is felt, a loop can be used, and the compiler uses the condition again and again until the requirements are met; once the mission is completed, the game is then over. This is the very basic idea that how programmers use while looping in gaming, there are many innovations every year where programmers use the loops in a different way to present interesting results. All the discussion can be proved with the help of the example in the jupyter notebook:

Code:

loops python, python loop, while loop in python, python while loop, while python, python while

#initializing the while loop with the true condition

while True:

#providing the first condition 

    try:

#using the integers as the condition

        number = int(input("Enter the age of your character: "))

#if the condition is satisfied, the program is terminated

        break

#if the condition is not true, throw the error

    except ValueError:

#printing the error message

        print("The input is not correct, enter only the integers")

 Output:

loops python, python loop, while loop in python, python while loop, while python, python while

Discussion:

Once you have seen the working of the code, you might be thinking, "What happens at the backend?" This example is chosen here to tell you that not all conditions of the loops use a comparison between two things only. We can use the boolean conditions as well to get the required output. If you have seen the simple examples of the while loops, then you must be wondering about the output of this program. You can see that the compiler first gives an error when the input does not meet the requirements of the program.

If the user does not give the expected data type for the program, the compiler goes out of the loop and ignores the break statement. In the second part of the program, the compiler goes to the except value and prints the error message that tells the details of the expected input. In this way, the user understands the requirements in detail, and the program does not end, but the iteration is continued until a certain result is obtained. 

Python Statements in While Loop 

In the while loop, there is the ability to use statements of various types, one of which you have just seen. Yet, for the convenience of the learners, we are discussing all the categories in detail. Each of the types has its own example in the Jupyter notebook. To open this, have a look at the steps given next:

  • In your Windows search bar, go and search for "Jupyter Notebook.”

  • Wait until it opens a new tab in your browser. 

  • Once the tab is opened, go to the dialogue box and open a new Python project. 

  • It will open a new tab with the cells where you can write your code.

Break Statement in While Loop

In the while loop, the break statement is used many times. As the name suggests, the break statement breaks the iteration, and the compiler stops executing the program as soon as it passes through the break statement. No matter if the body of the code still has to be executed, if the break statement appears in the code, the compiler stops working. Therefore, programmers use the break statement when they have more than one case and just want to execute the one that suits the condition. There are certain benefits to this statement, and one of these is, it gives the programmer all the long codes at once. Here is an example of a break statement in a while loop:”

Code:

loops python, python loop, while loop in python, python while loop, while python, python while

#Initializing the variable

a = 4

#Starting a while loop

while a <= 12:

#Printing the required output that we want on the screen

  print(a, ":I am a Programmer of Python")

#Using the if loop to provide the condition to the compiler for break statement

  if a == 9:

    break

#iteration

  a += 1

Output:

loops python, python loop, while loop in python, python while loop, while python, python while

Discussion on the Code:

It may seem that the code has some unusual things in it such as the starting point is from 4 instead of 1. This is the way to give you the concept that the starting point is not always zero. It totally depends on the choice of the programmer according to the requirements of the program. Once the variable is declared, the while loop is started, where the maximum number of iterations is shown. Right after declaring the condition, the results are printed.

For the convenience of the reader, I have shown the number of the iteration so that one may understand the whole scenario. Here, to use the break statement, I have shown you the “if” loop. In this way, the compiler understands that whenever the iteration number is 9, it has to stop and jump to the next line instead of completing the iteration. Therefore, after the 9th iteration, the compiler is not showing us any results. 

Another thing to notice is, the value of “a” is 4 at the start, but after every iteration, the compiler checks for the value when it is at the last line, and then it sees that the value of “a” is now one number greater, and therefore, the next iteration starts. 

Continue Statement in While Loop 

If you have understood the previous case, then this one is like a piece of cake because we can say that the working of the continuous statement is somehow opposite to the break statement. 

Code:

loops python, python loop, while loop in python, python while loop, while python, python while

#Initializing the variable

a = 0

#Starting a while loop

while a <= 12:

  a += 1


#Using the if loop to provide the condition to the compiler for the continue statement

  if a == 3:

    continue

#Printing the required output that we want on the screen

  print(a,"I am using the continue statement")

Output:

loops python, python loop, while loop in python, python while loop, while python, python while

Discussion:

The other pieces of code are the same, but you can see there is a bit of difference in the position of some lines. If you have observed this, then you are on point. The iteration is done in   the body of the while loop, and right after this, we are using the “if” condition. In the output, observe that the third number of iterations is missing, and this is because we told the compiler to jump whenever the iteration is at the third position. Once the iteration is ignored, the print operation gives us the output on the screen, where our value of the variable and the message on the screen are printed. 

else Statement in While Loop

The third and last statement of today is the else statement, and this is quite similar to the cases given above. The else statement has the power to show the result once the condition is no longer true. It means that it can be the ending message that we want to print until the condition is satisfied. As a result, we get two blocks of the code at once that can be printed using the same code. 

Code:

loops python, python loop, while loop in python, python while loop, while python, python while

#Initializing the variable

a = 0

#Starting a while loop

while a <= 12:

#Printing the required output that we want on the screen

   print(a,"I am using the continue statement")

#iteration

   a +=1

#Using the else statement to tell the user that the condition is satisfied

else:

    print("The condition is satisfied")

Output:

loops python, python loop, while loop in python, python while loop, while python, python while

Discussion:

Here, you can see we are getting a continuous stream of the output where every number of the variable is being used. It is because there were no distractions for the compiler in the code within the while loop. Once we have used it to show that all the iterations are done, the compiler then jumps to the else statement, which tells us the final words of the code.

In the end, we can say that today we have learned a lot about the statements used with the while loop in Python, and with the help of examples, the concept is not completely clear. The focus was on the while loop, but using the example of the statements, we understood how we could get the perfect result by merging the concepts of loops and statements in Python. From the introduction to the ending, the discussion was clear about the loops, and we took care of the minor details as well to know best about the while loop. It was an informative lecture, and in the next lecture, we have to know more about loops in Python, so stay tuned with us and be happy with the practice.