+ 3
Difference between for and while loop
Where and when i will use for and while loop. Can someone give me the answer with real life scenario?
6 Answers
+ 2
In Python, a loop variable is like any regular variable, so it will be accessible from the outside, and it will keep the value from the last iteration.
It works differently with comprehensions, which make use of the for syntax, but have their own names, like for example a function.
for loops in Python means, that you iterate over an iterable, a collection of things, and do something with each item.
for word in words:
print(word)
I have written two tutorials treating 'for' in Python, so I'll send you there for details.
The while loop runs independently from an iterable - it needs a condition and runs until that condition is not true anymore.
while x != 42:
Here you calculate stuff.
If x ever becomes 42,
the loop ends.
https://code.sololearn.com/cSdiWZr4Cdp7/?ref=app
https://code.sololearn.com/ck6HicJ6Z8jG/?ref=app
+ 7
Perhaps the question has been asked before and you can search for previous answers?
+ 5
for - condition integer
while - condition Boolean
+ 3
`for` and `while` loop are interchangeable, the different one was the `do-while` loop which will do at least 1 iteration before checking on loop condition. But in Python there's no `do-while` loop.
In PHP and JavaScript, `for` loop allows to create variables which are only valid/recognized within its block scope. `while` loop doesn't support this. I'm not too sure how this works in Python.
Loops are just a way to repetitive task, I'm not sure what you mean by real life scenario here.
0
for: Use it when you know the starting and end point. You have the control how much it should be executed, how much it should be incremented to reach the final destination.
while: When you know already how many times the loop should be executed.
- 1
đ§đ©đ§đ©đ§đ©