Python while loop

In our previous section we have seen examples of if-else. In this section, we will take a look at Python while loop.

The common question that comes to our mind is which one is faster? For or while loop? 

In the Java section, we have tried to find out the answer. You may have a look.

Let’s see how Python while loop works first.

After that we will discuss the for loop in Python.

Then finally we will be able to discuss the common difference between the for and while loop in Python.


If you are a programming beginner you may take an interest in the following posts.

Steps in program development

Learn Programming Techniques

The levels of programming languages

What is high level language?

What is language portability?

Programming languages translators

Learn structured programming

Machine language to Assembly language


As we know, in fact it’s a common scenario.

We use loops for repeating a block of code. But loops in Python have wide repercussions. 

With reference to the looping statement, we can say that we should not generalize or restrict our definition within a limited boundary. Right? 

Let’s see some code first.

# first we initialize the variable
i = 1
n = 10

# while it loops from i = 1 to 10
while i <= n:
  print(i, end=', ')
  i = i + 1

# output
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 

In the above code, we have seen how we have used comma separators to distinguish between the numbers.

However, we can stop that with a simple trick.

# first we initialize the variable
i = 1
n = 10

# while it loops from i = 1 to 10
while i <= n:
  if i == n:
    print(i, end='')
    break
  print(i, end=', ')
  i = i + 1

# output
1, 2, 3, 4, 5, 6, 7, 8, 9, 10

The common syntax of while loop starts with the condition. 

While the condition is true, the loop continues.

Because of this reason, if we write ‘True’ in place of condition, it becomes an infinite loop.

Otherwise  we provide a condition and the looping mechanism starts with evaluation. 

In each iteration, it checks whether the condition is True or not.

It keeps moving on, until the condition is true.

Certainly we can break the iteration at any point. 

Exactly that happens in the above code. 

At the same time, we can also use many other tricks to control a while loop statement. 

We will see that and many more in our coming sections.

For more Python code for beginners please visit the respective GitHub repository.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

TensorFlow, Machine Learning, AI and Data Science

Flutter, Dart and Algorithm

C, C++, Java and Game Development

Twitter


Posted

in

, ,

by

Comments

Leave a Reply