while loop | Python Flow Control
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
python while loop syntax
while test_expression:
Body of while
In the while loop,
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
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))
Loop is completed
The sum is 45
That's it for
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 🙂
If you like the content on CodePumpkin and if you wish to do something for the community and the planet Earth, you can donate to our campaign for planting more trees at CodePumpkin Cauvery Calling Campaign.
We may not get time to plant a tree, but we can definitely donate ₹42 per Tree.
About the Author
Tags: python, Python Tutorials
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.