To loop for infinity (or until a certain condition is met):
while True:
# Insert code here
if conditition_to_break:
break
This will call your code in an endless loop until condition_to_break is True and then breaks out of the loop.
You can read more on while loops here.
If you want to repeat something n times try using a for loop (read more here).
for x in range(3):
# This code will execute 3 times
print("Executed {0} times".format(x+1))
Answer from Ewan on Stack OverflowTo loop for infinity (or until a certain condition is met):
while True:
# Insert code here
if conditition_to_break:
break
This will call your code in an endless loop until condition_to_break is True and then breaks out of the loop.
You can read more on while loops here.
If you want to repeat something n times try using a for loop (read more here).
for x in range(3):
# This code will execute 3 times
print("Executed {0} times".format(x+1))
Did you mean like while or for?
If you meant do while then it's a bit tricky in python, since python does not
have a built-in function for it, but your can do this:
while(True):
your_code_here()
if(your_exit_term): break
I know it's ugly, but I'm not familiar with any other way.
Hi, I am very new to python and my current problem is that I want to be able to repeat a certain line of code and not the entire program until something else becomes true, I've done some digging online and cant find a solution that I understand properly, the code pasted has a comment on line 22, that is where I want a repeat function to go, the comment goes more in-depth. Here is a link to the code
https://pastebin.com/M46X2awm
Videos
I would:
for _ in range(3):
do()
The _ is convention for a variable whose value you don't care about.
You might also see some people write:
[do() for _ in range(3)]
however that is slightly more expensive because it creates a list containing the return values of each invocation of do() (even if it's None), and then throws away the resulting list. I wouldn't suggest using this unless you are using the list of return values.
You could define a function that repeats the passed function N times.
def repeat_fun(times, f):
for i in range(times): f()
If you want to make it even more flexible, you can even pass arguments to the function being repeated:
def repeat_fun(times, f, *args):
for i in range(times): f(*args)
Usage:
>>> def do():
... print 'Doing'
...
>>> def say(s):
... print s
...
>>> repeat_fun(3, do)
Doing
Doing
Doing
>>> repeat_fun(4, say, 'Hello!')
Hello!
Hello!
Hello!
Hello!