Can I do something like this in Python?
for (i = 0; i < 10; i++):
if someCondition:
i+=1
print i
I need to be able to skip some values based on a condition
EDIT: All the solutions so far suggest pruning the initial range in one way or another, based on an already known condition. This is not useful for me, so let me explain what I want to do.
I want to manually (i.e. no getopt) parse some cmd line args, where each 'keyword' has a certain number of parameters, something like this:
for i in range(0,len(argv)):
arg = argv[i]
if arg == '--flag1':
opt1 = argv[i+1]
i+=1
continue
if arg == '--anotherFlag':
optX = argv[i+1]
optY = argv[i+2]
optZ = argv[i+3]
i+=3
continue
...
Yes, this is how I would do it
>>> for i in xrange(0, 10):
... if i == 4:
... continue
... print i,
...
0 1 2 3 5 6 7 8 9
EDIT
Based on the update to your original question... I would suggest you take a look at optparse
for (i = 0; i < 10; i++)
if someCondition:
i+=1
print i
In python would be written as
i = 0
while i < 10
if someCondition
i += 1
print i
i += 1
there you go, that is how to write a c for loop in python.
There are two things you could do to solve your problem:
require comma-separated arguments which are going to be grouped into the following option value, you could use getopt, or any other module then.
or do more fragile own processing:
sys.argv.pop()
cmd = {}
while sys.argv:
arg = sys.argv.pop(0)
if arg == '--arg1':
cmd[arg] = sys.argv.pop(0), sys.argv.pop(0)
elif:
pass
print(cmd)
Strange way:
for x in (x for x in xrange(10) if someCondition):
print str(x)
You should use continue to skip a value, in both C and Python.
for i in range(10):
if someCondition:
continue
print(i)
You probably don't actually need the indices, you probably need the actual items. A better solution would probably be like this:
sequence = 'whatever'
for item in sequence:
if some_condition:
continue
do_stuff_with(item)
You could first turn the argv list into a generator:
def g(my_list):
for item in my_list:
yield item
You could then step through the items, invoking the generator as required:
my_gen = g(sys.argv[1:]):
while True:
try:
arg = my_gen.next()
if arg == "--flag1":
optX = my_gen.next()
opyY = my_gen.next()
--do something
elif arg == "--flag2":
optX = my_gen.next()
optY = my_gen.next()
optZ = my_gen.next()
--do something else
...
except StopIteration:
break
You can ensure that an index is incremented within a try...finally block. This solve the common problem of wanting to continue to the next index without having to copy/past i += 1 everywhere. Which is one of the main advantages the C-like for loop offers.
The main disadvantage to using a try...finally is having to indent your code once more. but if you have a while loop with many continue conditions its probably worth it.
Example
This example demonstrates that i still gets incremented in the finally block, even with continue being called. If i is not incremented its value will remain even forever, and the while loop will become infinite.
i = 0
while i < 10:
try:
print(i)
if i % 2 == 0:
continue
finally:
i += 1
without it you would have to increment i just before calling continue.
i = 0
while i < 10:
print(i)
if i % 2 == 0:
i += 1 # duplicate code
continue
i += 1
for i in xrange(0, 10):
if i % 3 == 0
continue
print i
Will only values which aren't divisible by 3.
If you need to iterate over something, and need an index, use enumerate()
for i, arg in enumerate(argv):
...
which does the same as the questioner's
for i in range(0,len(argv)):
arg = argv[i]
Your problem seems to be that you should loop not raw parameters but parsed parameters. I would suggest you to consider to change your decision not to use standard module (like the others).
increament = 4 #say
for i in range(n):
#write your code here
n=n+increment
this might be the simple solution to the problem if you just want to iterate through the array by skipping 4 members
Related
What is the problem?
i even tried this at the starting soas to get a output
print("enter list elements")
arr = input()
def AlternateRearr(arr, n):
arr.sort()
v1 = list()
v2 = list()
for i in range(n):
if (arr[i] % 2 == 0):
v1.append(arr[i])
else:
v2.append(arr[i])
index = 0
i = 0
j = 0
Flag = False
#set value to true is first element is even
if (arr[0] % 2 == 0):
Flag = True
#rearranging
while(index < n):
#if 1st elemnt is eevn
if (Flag == True):
arr[index] = v1[i]
index += 1
i+=1
Flag = ~Flag
else:
arr[index] = v2[j]
index +=1
j += 1
Flag = ~Flag
for i in range(n):
print(arr[i], end = "" )
arr = [9, 8, 13, 2, 19, 14]
n = len(arr)
AlternateRearr(arr, n)
print(AlternateRearr(arr))
There's no error.
Just the driver code dosen't work i guess, there's no output.
no outputs
The only place where it could output anything is print(AlternateRearr(arr)). But let's take a look at AlternateRearr itself - what does it return?
There's no return statement anywhere in AlternateRearr, so the print would show None. Well, it's something, not completely nothing...
But the code doesn't reach this part anyway - if it did, it would throw an error because print(AlternateRearr(arr)) passes only one argument to the function AlternateRearr that takes 2 arguments. You don't have default value set for n, so it wouldn't work.
Okay, so we came to conclusion that we don't reach the print anyway. But why? Because you never call it. You only define it and it's a different thing from calling it.
You might encounter a problem if you just try calling it near your normal code - Python is an interpreted language, so your main-level code (not enclosed in functions) should be at the bottom of the file because it doesn't know anything that is below it.
Is that your complete code?
Because you do have a function called AlternateRearr but you never call it
Call the function and also pass the integer for iteration.
Add after the function:
AlternateRearr(arr, 5)
Does Python have anything in the fashion of a "redo" statement that exists in some languages?
(The "redo" statement is a statement that (just like "break" or "continue") affects looping behaviour - it jumps at the beginning of innermost loop and starts executing it again.)
No, Python doesn't have direct support for redo. One option would something faintly terrible involving nested loops like:
for x in mylist:
while True:
...
if shouldredo:
continue # continue becomes equivalent to redo
...
if shouldcontinue:
break # break now equivalent to continue on outer "real" loop
...
break # Terminate inner loop any time we don't redo
but this mean that breaking the outer loop is impossible within the "redo-able" block without resorting to exceptions, flag variables, or packaging the whole thing up as a function.
Alternatively, you use a straight while loop that replicates what for loops do for you, explicitly creating and advancing the iterator. It has its own issues (continue is effectively redo by default, you have to explicitly advance the iterator for a "real" continue), but they're not terrible (as long as you comment uses of continue to make it clear you intend redo vs. continue, to avoid confusing maintainers). To allow redo and the other loop operations, you'd do something like:
# Create guaranteed unique sentinel (can't use None since iterator might produce None)
sentinel = object()
iterobj = iter(mylist) # Explicitly get iterator from iterable (for does this implicitly)
x = next(iterobj, sentinel) # Get next object or sentinel
while x is not sentinel: # Keep going until we exhaust iterator
...
if shouldredo:
continue
...
if shouldcontinue:
x = next(iterobj, sentinel) # Explicitly advance loop for continue case
continue
...
if shouldbreak:
break
...
# Advance loop
x = next(iterobj, sentinel)
The above could also be done with a try/except StopIteration: instead of two-arg next with a sentinel, but wrapping the whole loop with it risks other sources of StopIteration being caught, and doing it at a limited scope properly for both inner and outer next calls would be extremely ugly (much worse than the sentinel based approach).
No, it doesn't. I would suggest using a while loop and resetting your check variable to the initial value.
count = 0
reset = 0
while count < 9:
print 'The count is:', count
if not someResetCondition:
count = count + 1
This is my solution using iterators:
class redo_iter(object):
def __init__(self, iterable):
self.__iterator = iter(iterable)
self.__started = False
self.__redo = False
self.__last = None
self.__redone = 0
def __iter__(self):
return self
def redo(self):
self.__redo = True
#property
def redone(self):
return self.__redone
def __next__(self):
if not (self.__started and self.__redo):
self.__started = True
self.__redone = 0
self.__last = next(self.__iterator)
else:
self.__redone += 1
self.__redo = False
return self.__last
# Display numbers 0-9.
# Display 0,3,6,9 doubled.
# After a series of equal numbers print --
iterator = redo_iter(range(10))
for i in iterator:
print(i)
if not iterator.redone and i % 3 == 0:
iterator.redo()
continue
print('---')
Needs explicit continue
redone is an extra feature
For Python2 use def next(self) instead of def __next__(self)
requires iterator to be defined before the loop
I just meet the same question when I study perl,and I find this page.
follow the book of perl:
my #words = qw(fred barney pebbles dino wilma betty);
my $error = 0;
my #words = qw(fred barney pebbles dino wilma betty);
my $error = 0;
foreach (#words){
print "Type the word '$_':";
chomp(my $try = <STDIN>);
if ($try ne $_){
print "Sorry - That's not right.\n\n";
$error++;
redo;
}
}
and how to achieve it on Python ??
follow the code:
tape_list=['a','b','c','d','e']
def check_tape(origin_tape):
errors=0
while True:
tape=raw_input("input %s:"%origin_tape)
if tape == origin_tape:
return errors
else:
print "your tape %s,you should tape %s"%(tape,origin_tape)
errors += 1
pass
all_error=0
for char in tape_list:
all_error += check_tape(char)
print "you input wrong time is:%s"%all_error
Python has not the "redo" syntax,but we can make a 'while' loop in some function until get what we want when we iter the list.
Not very sophiscated but easy to read, using a while and an increment at the end of the loop. So any continue in between will have the effect of a redo. Sample to redo every multiple of 3:
redo = True # To ends redo condition in this sample only
i = 0
while i<10:
print(i, end='')
if redo and i % 3 == 0:
redo = False # To not loop indifinively in this sample
continue # Redo
redo = True
i += 1
Result: 00123345667899
There is no redo in python.
A very understandable solution is as follow:
for x in mylist:
redo = True
while redo:
redo = False
If should_redo:
redo = True
It's clear enough to do not add comments
Continue will work as if it was in the for loop
But break is not useable, this solution make break useable but the code is less clear.
Here is a solution for python 3.8+ since now we have the := operator:
for key in mandatory_attributes: # example with a dictionary
while not (value := input(f"{key} (mandatory): ")):
print("You must enter a value")
mandatory_attributes[key] = value
I'm wondering how to do the following in Python.
If I have a function with a for loop, it is possible to with an if statement to skip certain numbers.
This is an implementation of fisher-yates d got from activestate.com.
import random
def shuffle(ary):
a=len(ary)
b=a-1
for d in range(b,0,-1):
e=random.randint(0,d)
if e == d:
continue
ary[d],ary[e]=ary[e],ary[d]
return ary
Now continue simply goes to the next value for d. How can I, instead of doing continue, rerun the function with the original parameter ary?
Note that the function is just some example code, I'm curious on how to do this in general.
Also, maintaining a copy of the array might not be possible if the list is big, so thats not really a solution imo.
This is a common recursive pattern. However, your case is a little different than usual because here you need to make a copy of your input list to use when you recurse if the shuffling fails.:
import random
def shuffle(ary):
initial = ary[:]
a=len(ary)
b=a-1
for d in range(b,0,-1):
e=random.randint(0,d)
if e == d:
return shuffle(initial)
ary[d],ary[e]=ary[e],ary[d]
return ary
ary = [1,2,3,4,5,6]
print shuffle(ary)
Also note that Wikipedia gives a (non-recursive) python implementation of the very similar Sattolo's algorithm.
from random import randrange
def sattoloCycle(items):
i = len(items)
while i > 1:
i = i - 1
j = randrange(i) # 0 <= j <= i-1
items[j], items[i] = items[i], items[j]
return
If I read the article correctly, to re-acquire Fisher-Yates, you'd just do one simple change:
from random import randrange
def FisherYates(items):
i = len(items)
while i > 1:
i = i - 1
j = randrange(i+1) # 0 <= j <= i
items[j], items[i] = items[i], items[j]
return
def function(list):
len(list)-1
for i in range(len(list)-1,0,-1):
e= randint(0,i)
while e > i:
e= randint(0,i)
"do something to the list"
return array
?
def function(list):
for i in (a for a in range(len(list)-1,0,-1) if randint(0,a) > a):
#do something with list
#do something else with remainder.
Not exactly what you asked for. Just wanted to remind you of this possibility.
you can copy the parameter to a temp variable. then call the function with the temp variable and use return;
def function(list):
listCopy = list;
len(list)-1
for i in range(len(list)-1,0,-1):
e= randint(0,i)
if e > i:
return function(listCopy)
else
"do something with the list"
return array
How can you continue the parent loop of say two nested loops in Python?
for a in b:
for c in d:
for e in f:
if somecondition:
<continue the for a in b loop?>
I know you can avoid this in the majority of cases but can it be done in Python?
Break from the inner loop (if there's nothing else after it)
Put the outer loop's body in a function and return from the function
Raise an exception and catch it at the outer level
Set a flag, break from the inner loop and test it at an outer level.
Refactor the code so you no longer have to do this.
I would go with 5 every time.
Here's a bunch of hacky ways to do it:
Create a local function
for a in b:
def doWork():
for c in d:
for e in f:
if somecondition:
return # <continue the for a in b loop?>
doWork()
A better option would be to move doWork somewhere else and pass its state as arguments.
Use an exception
class StopLookingForThings(Exception): pass
for a in b:
try:
for c in d:
for e in f:
if somecondition:
raise StopLookingForThings()
except StopLookingForThings:
pass
You use break to break out of the inner loop and continue with the parent
for a in b:
for c in d:
if somecondition:
break # go back to parent loop
from itertools import product
for a in b:
for c, e in product(d, f):
if somecondition:
break
use a boolean flag
problem = False
for a in b:
for c in d:
if problem:
continue
for e in f:
if somecondition:
problem = True
Looking at All the answers here its all different from how i do it\n
Mission:continue to while loop if the if condition is true in nested loop
chars = 'loop|ing'
x,i=10,0
while x>i:
jump = False
for a in chars:
if(a = '|'): jump = True
if(jump==True): continue
lista = ["hello1", "hello2" , "world"]
for index,word in enumerate(lista):
found = False
for i in range(1,3):
if word == "hello"+str(i):
found = True
break
print(index)
if found == True:
continue
if word == "world":
continue
print(index)
Now what's printed :
>> 1
>> 2
>> 2
This means that the word no.1 ( index = 0 ) appeard first (there's no way for something to be printed before the continue statement). The word no.2 ( index = 1 ) appeared second ( the word "hello1" managed to be printed but not the rest ) and the word no.3 appeard third what mean's that the words "hello1" and "hello2" managed to be printed before the for loop reached this said third word.
To sum up it's just using the found = False / True boolean and the break statement.
Hope it helps!
#infinite wait till all items obtained
while True:
time.sleep(0.5)
for item in entries:
if self.results.get(item,None) is None:
print(f"waiting for {item} to be obtained")
break #continue outer loop
else:
break
#continue
I wish there could be a labeled loop ...
I'm a big fan of Python's for...else syntax - it's surprising how often it's applicable, and how effectively it can simplify code.
However, I've not figured out a nice way to use it in a generator, for example:
def iterate(i):
for value in i:
yield value
else:
print 'i is empty'
In the above example, I'd like the print statement to be executed only if i is empty. However, as else only respects break and return, it is always executed, regardless of the length of i.
If it's impossible to use for...else in this way, what's the best approach to this so that the print statement is only executed when nothing is yielded?
You're breaking the definition of a generator, which should throw a StopIteration exception when iteration is complete (which is automatically handled by a return statement in a generator function)
So:
def iterate(i):
for value in i:
yield value
return
Best to let the calling code handle the case of an empty iterator:
count = 0
for value in iterate(range([])):
print value
count += 1
else:
if count == 0:
print "list was empty"
Might be a cleaner way of doing the above, but that ought to work fine, and doesn't fall into any of the common 'treating an iterator like a list' traps below.
There are a couple ways of doing this. You could always use the Iterator directly:
def iterate(i):
try:
i_iter = iter(i)
next = i_iter.next()
except StopIteration:
print 'i is empty'
return
while True:
yield next
next = i_iter.next()
But if you know more about what to expect from the argument i, you can be more concise:
def iterate(i):
if i: # or if len(i) == 0
for next in i:
yield next
else:
print 'i is empty'
raise StopIteration()
Summing up some of the earlier answers, it could be solved like this:
def iterate(i):
empty = True
for value in i:
yield value
empty = False
if empty:
print "empty"
so there really is no "else" clause involved.
As you note, for..else only detects a break. So it's only applicable when you look for something and then stop.
It's not applicable to your purpose not because it's a generator, but because you want to process all elements, without stopping (because you want to yield them all, but that's not the point).
So generator or not, you really need a boolean, as in Ber's solution.
If it's impossible to use for...else in this way, what's the best approach to this so that the print statement is only executed when nothing is yielded?
Maximum i can think of:
>>> empty = True
>>> for i in [1,2]:
... empty = False
... if empty:
... print 'empty'
...
>>>
>>>
>>> empty = True
>>> for i in []:
... empty = False
... if empty:
... print 'empty'
...
empty
>>>
What about simple if-else?
def iterate(i):
if len(i) == 0: print 'i is empty'
else:
for value in i:
yield value