else in the end of for and while loops - python

who can say me:
What is the difference between writing code inside else or just after the loops?
for x in range(6):
print('hello')
print('bye')
or
for x in range(6):
print('hello')
else:
print('bye')

From for/else documentation:
The else clause executes after the loop completes normally. This means that the loop did not encounter a break statement.
This means that in your specific example there is no difference in using else or not.

In the second example you're using conditional statement, Whereas in the first scenario after the loop completes, It automatically executes the next line.
Basically your post is an example of getting same result with alternative solutions.
Though your first solution can be considered as valid practice comparing with second one.
Although I would suggest you to read this article before posting any questions on stack overflow.

Related

python How to while loop while true , run multiple functions together

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.

Control flow in a while loop

When solving a question of Project Euler I ran into the following logical error related to when n is updated.
while(n<1000):
#update n
#do something with n
#do stuff
vs
while(n<1000):
#do something with n
#do stuff
#update n
In the first instance, I ended up performing an operation with n even though the condition of n<1000 is violated.
Does this logical error have a name? How common is this bug?
I tried to look for it, I did find things about pre-incrementing and post-incrementing a variable. Although that is close to the error, it isn't exactly what is happening here. I found a reference to this in a SO answer about for loop vs while loop in the part describing how for loops are more concise and direct when compared to while loops. Essentially with while loops we end up running code after a variable update which could be buried somewhere in the code.
This is not always a bug: it depends on the algorithm. In some cases, you know that the original value of n is legal (so you can enter the loop), but you want to update and use the new value in your processing. You need to match your code to your algorithm. Your second code block is the canonical for-equivalent, and is more common.
This falls under the general heading of "off by 1 error".

Infinite for loop in Python like C++

In C++ we can write an infinite for loop like for(;;). Is here any syntax like this to write an infinite for loop in Python?
Note : I know that if I write for i in range(a_very_big_value) then it may run infinity. I am searching a simple syntax like C++ or any other tricks to write infinite for loop in Python.
Python's for statement is a "for-each" loop (sort of like range-for in C++11 and later), not a C-style "for-computation" loop.
But notice that in C, for (;;) does the same thing as while (1). And Python's while loop is basically the same as C's with a few extra bells and whistles. And, in fact, the idiomatic way to loop forever is:1
while True:
If you really do want to write a for loop that goes forever, you need an iterable of infinite length. You can grab one out of the standard library:2
for _ in itertools.count():
… or write one yourself:
def forever():
while True:
yield None
for _ in forever():
But again, this isn't really that similar to for (;;), because it's a for-each loop.
1. while 1: used to be a common alternative. It's faster in older versions of Python, although not in current ones, and occasionally that mattered.
2. Of course the point of count isn't just going on forever, it's counting up numbers forever. For example, if enumerate didn't exist, you could write it as zip(itertools.count(), it).
Yes, it is possible.
With a while loop:
while True:
...
With a for loop (just for kicks):
from itertools import cycle
for _ in cycle(range(1)):
...
The cycle returns 1 indefinitely.
In either case, it's up to you to implement your loop logic in such a way that you terminate eventually. And lastly, if you want to implement an execute-until-___ loop, you should stick to while True, because that's the idiomatic way of doing it.
I found the answer from here and here
Using itertools.count:
import itertools
for i in itertools.count():
if there_is_a_reason_to_break(i):
break
In Python2 xrange() is limited to sys.maxint, which may be enough for most practical purposes:
import sys
for i in xrange(sys.maxint):
if there_is_a_reason_to_break(i):
break
In Python3, range() can go much higher, though not to infinity:
import sys
for i in range(sys.maxsize**10): # you could go even higher if you really want
if there_is_a_reason_to_break(i):
break
So it's probably best to use count()
It is also possible to achieve this by mutating the list you're iterating on, for example:
l = [1]
for x in l:
l.append(x + 1)
print(x)
Yes, here you are:
for i in __import__("itertools").count():
pass
The infinite iterator part was taken from this answer. If you really think about it though, a while loop looks way better.
while True:
pass
You can use:
while True:
# Do stuff here
for _ in iter(str, "forever"):
... pass
This may help. Because the iter() function creates an iterator that will call str() with no arguments for each call to its next() method[ This returns an empty string ]; if the value returned by str() is equal to the string "forever"(WHICH WILL NEVER HAPPEN AS "" != "forever"), StopIteration will be raised thus breaking the loop, otherwise the loop will continue running and this is the case for our loop.
REF: https://docs.python.org/3/library/functions.html?highlight=iter#iter

Flow control after breaking out of while loop in Python

I am pretty new to both programming and Python. A few times now, I have created what feels like an awkward program flow, and I am wondering if I am following best practices. This is conceptually what I have wanted to do:
def pseudocode():
while some condition is true:
do some stuff
if a condition is met:
break out of the while loop
now do a thing once, but only if you never broke out of the loop above
What I've ended up doing works, but feels off somehow:
def pseudocode():
while some condition is true:
do some stuff
if some condition is met:
some_condition_met = True
break out of the while loop
if some_condition_met is False:
do a thing
Is there a better way?
You're looking for while-else loop:
def pseudocode():
while some condition is true:
do some stuff
if a condition is met:
break out of the while loop
else:
now do a thing once, but only if you never broke out of the loop above
From docs:
while_stmt ::= "while" expression ":" suite
["else" ":" suite]
A break statement executed in the first suite terminates the loop
without executing the else clause’s suite.
Use an else clause to the while loop:
while some_condition:
do_stuff()
if a_condition_is_met:
break
else:
executed_when_never_broken
See the while statement documentation:
A break statement executed in the first suite terminates the loop without executing the else clause’s suite.
If you think about it, you might already have a perfectly good condition to use without setting a flag: the condition at the top of the while loop (or, rather, the not of it). Assuming you don't change the truthiness of your condition during the same iteration as a break, this gives you:
while something:
do_stuff()
if something_else:
break
if not something:
more_stuff()
This makes sense if you think of while as a repeated if: instead of happening once, a while keeps going until the condition becomes falsey.
But, like the other answers have mentioned, the analogy goes further: just like you don't have to spell all your ifs as
if a:
a_stuff()
if not a:
b_stuff()
while accepts an else that is executed if the condition at the top is tested and found to be falsey. So,
while something:
do_stuff()
if something_else:
break
else:
more_stuff()
And, same as the if/else case, this doesn't imply any further tests of the condition than what would happen anyway. In the same way that an else attached to if a won't run if the true-branch makes a falsey, an else attached to a while will never run after a break since that explicitly skips ever checking the condition again. This makes the else: equivalent to a decicated flag in every case.
This also extends to for loops, even though the analogy breaks - but it executes under similar enough rules: the else is run if the loop ends by having run its course rather than hitting a break.

Is while True: a suitable way to repeat a block until an accepted case is reached?

Is while True an accepted method for looping over a block of code until an accepted case is reached as below? Is there a more elegant way to do this?
while True:
value = input()
if value == condition:
break
else:
pass
# Continue code here.
Thank you for any input.
That's the way to do this in Python. You don't need the else: pass bit though.
Note, that in python 2.x you're likely to want raw_input rather than input.
If it's deterministic, then yes. If it is not deterministic (thus meaning you could be stuck in a loop forever at some statistical likelihood) then no.
If you wanted to make it a little more clean and easier to debug as the code grows larger, use a boolean or integer to indicate the status of your loop condition.

Categories

Resources