Code Pumpkin

while loop | Python Flow Control

October 31, 2018
Posted by Dipen Adroja

Flow control is one of the important aspects of any programming language. Loops are used in programming to repeat a specific block of code. In this article, we will learn to create while loop in python.

Python While loop Flowchart

while-loop-flowcart

 python while loop syntax

while test_expression: 

       Body of while

In the while loop, first test_expression is evaluated. If it is evaluated to true then only loop body is executed. This process continues until the test_expression evaluates to False.

Example:


n = 10
sum = 0
i = 1

while i < n: # counter will break when i becomes 10
    sum = sum + i
    i = i+1    # update counter

# print the sum
print("The sum is " + str(sum))

Output:

The sum is 45

In the given program test condition will return true as long as the value of i is less than n(wiz 10).

while loop with else

As we have seen that we can use else with for loop, The part we can also use else block with while loop. 

The else is executed if the condition in the while loop evaluates to False. The else part is executed if and only the while loop is not terminated using break statement.

example:


n = 10
sum = 0
i = 1

while i < n: # counter will break when i becomes 10
    sum = sum + i
    i = i+1    # update counter
else:
	print("Loop is completed")
# print the sum
print("The sum is " + str(sum))

Output:

Loop is completed

The sum is 45

That's it for nowsmiley .

That's all for this topic. If you guys have any suggestions or queries, feel free to drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here.

Happy Learning 🙂



About the Author


Dipen Adroja
Coder, Blogger, Wanderer, Philosopher, Curious pumpkin



Tags: ,


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
</code></pre>
For more information on supported HTML tags in disqus comment, click here.
Total Posts : 122
follow us in feedly
Contribute Your Articles

Subscribe Us

Like Us On Facebook