Can someone explain me difference between for loop and while loop in easy language and with some example ? I have trying to go through some websites or videos but the language may be little complicated for me
Asked
Active
Viewed 71 times
-2
-
6Does this answer your question? [When to use "while" or "for" in Python](https://stackoverflow.com/questions/920645/when-to-use-while-or-for-in-python) – Talendar Jan 26 '21 at 18:35
2 Answers
1
They mostly do the same thing, or they can be configured to do the same thing. But generally, for loop is used if we know how long the loop should run, and while is used if we need to loop "while" a condition is satisfied.
for i in range(0,10):
print("hello")
This will print "hello" 10 times, but if we want to print "hello" until a condition changes, we use while:
while(i != 20):
print("hello")
This will loop forever until i is changed to 20.
A. Emre Boyaci
- 11
- 1
-2
Both for loop and while loop are used to excute one or more lines of code certain number of times. The main differences are as follows.
Syntax:
While loop:
while(condtion) {
//statements to excute.
}
For loop:
for(intialization; condition; Increment or decrement){
// statements to be excuted.
}
There are few variations we can do with for loop.
Such as all three parts of for loop are optional. That means you can also have a loop like this.
for(;;) which is nothing but an infinite loop.
For initialization there can be multiple statements.
for(i =0, j =0;i<20;i++)
Similarly for the third component there can be any expression and not necessarily increment or decrement.
for(i =0;i<10;i = i * 2)
Working:
In while loop first of all the condition expression is evaluated and if it is true then the body of the loop is excuted. Then control again evaluate the condition expression. This goes on untill condition becomes false.
zubair malik
- 219
- 1
- 9