Python- While Loop
Harshit Trehan
SDE-2 @Atlassian | Ex-Juspay | 85k+ | B.Tech Gold Medalist | Speaker | Content Writer | YouTuber
Dear Readers,
Today's topic is "While Loop" in Python.
In Python, a while loop allows you to repeatedly execute a block of code as long as a certain condition is true. The general syntax of a while loop in Python is as follows:
while condition:
# Code to be executed repeatedly
# as long as the condition is true
Here's a breakdown of how a while loop works:
领英推荐
Here's an example that demonstrates a simple while loop:
count = 0
while count < 5:
print("Count:", count)
count += 1
print("Loop finished.")
In this example, the loop starts with count equal to 0. The condition count < 5 is checked. If it's true, the code block inside the loop is executed, which prints the current value of count and increments it by 1. This process continues until count reaches 5. Once count becomes 5, the condition becomes false, and the loop is terminated. Finally, the program proceeds to print "Loop finished."
Note: Be cautious when using while loops to avoid infinite loops, where the condition never becomes false. Make sure to include a way to modify the loop condition within the loop's code block to prevent infinite looping.
The concept of?"While loop" is simple and I have made this more simplified in my new video on this. This is very useful and helpful for the students and working professional who are passionate about coding and its concepts.
Please check this video on YT (#HarshitTrehan)out and reach me in case of any query/doubts. I would love to help you in getting your concepts clear on this..
If you know someone who needs this, then please forward this to him/her.
Senior Software Engineer @Walmart | React, Redux, ES6 Expert | ex-Adobe | Mentoring Frontend Engineers for Interviews | Connect: topmate.io/shasank_pandey | Connect Preplaced : preplaced.in/profile/shasank-pandey
1 年Great share!