Python loop that always executes at least once? [duplicate] - python

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
do-while loop in Python?
How do I write a loop in Python that will always be executed at least once, with the test being performed after the first iteration? (different to the 20 or so python examples of for and while loops I found through google and python docs)

while True:
#loop body
if (!condition): break

You could try:
def loop_body():
# implicitly return None, which is false-ish, at the end
while loop_body() or condition: pass
But realistically I think I would do it the other way. In practice, you don't really need it that often anyway. (Even less often than you think; try to refactor in other ways.)

Related

Is there a way to make an infinite loop in python? [duplicate]

This question already has answers here:
Infinite for loop in Python like C++
(6 answers)
Closed 1 year ago.
I know you can just do this (technically):
import time
variable = 0
while variable < 99999999999999999999999999999999999999
variable = variable + 1
time.sleep(1)
But is there just a way to make an infinite loop without typing all those 9's?
(idk if this makes sense but I'm sure you get what I mean)
You can use
import time
while True:
time.sleep(1)
Because you want an infinite loop with a one-second delay between iterations.

What the difference between while and for loop [duplicate]

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.

When is a variable released from memory? [duplicate]

This question already has answers here:
when does python delete variables?
(4 answers)
Closed 7 years ago.
Say I define a function, which builds a list, and then prints the items of the list one by one (no practical use, just an example:
import os
def build_and_print():
thingy = os.walk('some directory')
for i in thingy:
print i
if __name__ == '__main__:
build_and_print()
If the thingy that is built is very large it could take up a lot of memory, at what point will it be released from memory?
Does python store the variable thingy until the script is finished running or until the function that builds/uses it is finished running?
Once a Variable goes out of scope, it is collected by the garbage collector.
You can see the collector code here. Go to collect function, there comments explain the process well.

for or while loop to do something n times [duplicate]

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'!

Raw Input with a time limit [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
raw_input and timeout
I was wondering how I can make my raw_input have a time limit.
I want something like raw_input=("What do you want?")
and then if an input isn't given in less than 5 seconds, it'd print "too late"
I've been trying to read up, but it doesn't seem like anything like this is available for raw_input
Use a timer object, setting it to the required number of seconds; and just use tje timer function to display the message you want once the event object is invoked.

Categories

Resources