This question already has answers here:
When to use "while" or "for" in Python
(10 answers)
Closed 2 years ago.
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
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.
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.
Related
This question already has answers here:
When to use "while" or "for" in Python
(10 answers)
Closed 1 year ago.
There is a really differ between while and for in python? Or can I use anyone I want?
And my second question :-
persons['alic', 'sam', 'rain']
first_name = 'mike'
for first_name in persons :
#when the program runs for the first time
#what is the value of first_name?
#is it 'mike',or its value is Null??
print(first_name)
And thanks.
In general, a for in loop is useful for iteration over a known set and the number of iterations is predetermined. A while loop is generally used when the exit condition is a change of state, not a predetermined length.
Common use cases for while loops include:
Running the main loop of a program until a keyboard interrupt:
try:
while True:
break
except KeyboardInterrupt:
print("Press Ctrl-C to terminate while statement")
pass
Finding the last node in a list of references:
while(node is not None):
node = node.next()
This question is answered well in this stackoverflow
Pulling out the information:
while loop - used for looping until a condition is satisfied and when it is unsure how many times the code should be in loop
for loop - used for looping until a condition is satisfied but it is used when you know how many times the code needs to be in loop
do while loop - executes the content of the loop once before checking the condition of the while.
def function():
while True:
...omission...(this function is repeated permanently)
i =0
while i < 4:
driver.execute_script("""window.open("URL")""")
driver.switch_to.window(driver.window_handles[-1])
time.sleep(1)
function()
time.sleep(1)
i += 1 #open new tab and run function.
it doesn't work because while true loop is repeated permanently. Is there any ways to run multiple functions together?
https://imgur.com/a/4SIVekS This picture shows what I want
According to your picture, what you want is to launch the function a set number of times (4?), and run those in parrallel.
On a single core, as is the normal behavior, straight up parallel processing is impossible. You need to access other cores and manage a decentralized processing. while is useless there. I'm worried the level of difficulty is over your current skills, but here we go.
The overall flow that you (probably, depends on the actual memory safety of your functions) need is:
- to create a thread pool with the set number of threads for the number of runs you want.
- indicate the function you need to run
- start them, making sure the start itself is non-blocking.
- ensure one functions's processing doesn't impact another's results. race conditions are a common problem.
- gather results, again, in a non-blocking way.
You can use several methods. I highly recommend you read up a lot on the following documentations.
Threading:
https://docs.python.org/3/library/threading.html
Multiprocessing:
https://docs.python.org/3/library/multiprocessing.html
I don't understand your question because I don't understand what your function is supposed to do.
while True:
will always create an infinite loop. "while" is a command that tells python to loop through the following block so long as the expression following it evaluates to True. True always evaluates to True.
It seems like you want to use a conditional, like you do in "while x < 4".
x < 4
...is an expression that evaluates to true when x is less than 4, and false if x is not less than 4. Everything below the line:
while x < 4:
will then run if x is less than 4, and when it's done running that code, it will go back and evaluate if x is less than 4 again, and if it is, run the code again. To include another while loop inside of that loop, that new loop also needs an expression to evaluate. If you want to evaluate the same expression, write it out:
while x < 4:
# do something
while x < 4:
#do more things
# do even more things
# change x at some point, or else you're in an infinite loop.
However, there's no reason to do that specifically, because you're already doing it. All of the code is only running when x < 4, so checking that condition again right there is redundant, and doing it in another loop doesn't make sense. If the inside loop is also incrementing x, then the outside loop won't loop and doesn't need to increment x.
Also, if you want a function to check a condition based on a variable outside the function, you'll want to pass things to that function.
I'm new to Python so forgive me for such a newbie question but I have to ask.
I started from C++ and PHP, they have the operators { and } which could be used to set the loop execution range, even in VB there is such thing called "end for(while)" to define the range of the loop; But in Python, I searched for a while and I didn't see any article which can tell me that there is such thing?
I need to use the Loop to execute multiple lines of code, and I need a way to limit its execution area so the Loop won't affect the code after the Area I wish. Please tell me how can I achieve that.
In Python, consecutive lines with same amount of indentation form a 'BLOCK'
In the following example, statement 1 to 3 are in the same block.
for i in range(n):
statement 1
statement 2
statement 3
statement 4
This question already has answers here:
What does "while True" mean in Python?
(18 answers)
Closed 9 years ago.
in the following program:
count = 0
while True:
count += 1
if count>10:
break
if count==5:
continue
print(count)
what exactly is while True testing? And can there ever be a while false condition, if so what would that be testing?
while True: is an infinite loop. It will only ever be broken by break, return, or an exception being raised (in your case the first).
It is an infinite loop. It tests if True is.. true, which it always is.
It is the conditions in the loop that end it; the break statement breaks out of the infinite loop here, not the while condition.
Note that the continue statement merely skips the remainder of the loop iteration and skips to the next.
Other events that'd end the loop are a return (provided the loop is part of a function), or an if an exception was raised.
This will create an infinite loop, most likely causing your program to crash. If you would like to stop the loop, use return. You're code is pretty much counting up to 10, then stopping, as seen in
if count>10:
break
a better way of doing this would be to use a for loop
for count in range(0, 10):
This question already has answers here:
More Pythonic Way to Run a Process X Times [closed]
(5 answers)
Closed 7 months ago.
In Python you have two fine ways to repeat some action more than once. One of them is while loop and the other - for loop. So let's have a look on two simple pieces of code:
for i in range(n):
do_sth()
And the other:
i = 0
while i < n:
do_sth()
i += 1
My question is which of them is better. Of course, the first one, which is very common in documentation examples and various pieces of code you could find around the Internet, is much more elegant and shorter, but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?
So what do you think, which way is better?
but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?
That is what xrange(n) is for. It avoids creating a list of numbers, and instead just provides an iterator object.
In Python 3, xrange() was renamed to range() - if you want a list, you have to specifically request it via list(range(n)).
This is lighter weight than xrange (and the while loop) since it doesn't even need to create the int objects. It also works equally well in Python2 and Python3
from itertools import repeat
for i in repeat(None, 10):
do_sth()
python3 & python2
just use range():
for _ in range(n):
# do something n times exactly
The fundamental difference in most programming languages is that unless the unexpected happens a for loop will always repeat n times or until a break statement, (which may be conditional), is met then finish with a while loop it may repeat 0 times, 1, more or even forever, depending on a given condition which must be true at the start of each loop for it to execute and always false on exiting the loop, (for completeness a do ... while loop, (or repeat until), for languages that have it, always executes at least once and does not guarantee the condition on the first execution).
It is worth noting that in Python a for or while statement can have break, continue and else statements where:
break - terminates the loop
continue - moves on to the next time around the loop without executing following code this time around
else - is executed if the loop completed without any break statements being executed.
N.B. In the now unsupported Python 2 range produced a list of integers but you could use xrange to use an iterator. In Python 3 range returns an iterator.
So the answer to your question is 'it all depends on what you are trying to do'!