This question already has answers here:
How can I make a function that will called from inside a loop and that will indicate whether to continue?
(2 answers)
Closed 13 days ago.
Here i created some function like
def common_function():
if i==3:
continue
and
for i in range(0,10):
common_function(i)
this is simple example, In my code i create common function later i want to used that on multiple place but this cannot be applied.
Is there any way to do that..
If you want to continue a for-loop in certain situations, you can use this code snippet:
def action_inside_loop(i):
if i == 3:
return
print(f'Doing something with index {i}')
for i in range(5):
action_inside_loop(i)
This results in the output:
Doing something with index 0
Doing something with index 1
Doing something with index 2
Doing something with index 4
If on the other hand, you want to break out of a for-loop in certain situations, you can use this code snippet:
def action_inside_loop(i):
if i == 3:
return False
print(f'Doing something with index {i}')
return True
for i in range(5):
should_continue = action_inside_loop(i)
if not should_continue:
break
This results in the output:
Doing something with index 0
Doing something with index 1
Doing something with index 2
Related
This question already has answers here:
How to change index of a for loop?
(5 answers)
Closed last year.
By "counter" I mean the "i" in the code I attached. I just picked up Python for University, and I was wondering if i could maniuplate the counter just like you can in C++
n=5
for i in range(n):
print("Test")
i=i-1
The result of this code is
Test
Test
Test
Test
Test
but i was wondering if you could manipulate the "i" so it is an infinite loop
Feel free to ask questions about what I mean if it is not clear enough
The problem is that python uses iterators, which aren't meant to be manipulated while getting iterated. A good rule is, if you need to manipulate a for loop, you shouldn't use a for loop. The better way would be, using a while loop. An example:
n = 10
while n > 5:
print("Test " + n)
n -= 2
if n == 6:
n += 1
Or the infinite loop:
while True:
print("Test")
Take a look at this for more information.
This question already has answers here:
Convert from "For-loops" to "While-loops"
(3 answers)
Closed 4 years ago.
For a school work, we have to create a function that determines if a list is injective, which returns True or False. 2 ways of doing the job are recommended : with 'for' loops and with 'while' loops. I managed to program with 'for' loops, but I'm having issues with 'while' loops, as i cannot figure out why mine is infinite.
I'll put my code below. I already tried getting rid of few variables that where needless, and as I modify the value of 'a' within the loop, it seems to me there is nothing wrong on paper.
def injective(x):
i=0
k=i+1
a=True
while i<len(L)-1 : #L is the name of the list
while k<len(L) :
if L[i]==L[k] :
a=False
else :
a=True
i+=1
return a
I expect to get True when the list is injective and False when not
It is because the value of k in the inner loop is not changing, I think you are missing k+=1 somewhere.
Code
def injective(x):
i=0
k=i+1
while i<len(L)-1 : #L is the name of the list
while k<len(L) :
if L[i]==L[k] :
return False
k+=1
i+=1
return True
I have taken the liberty to optimize the code a bit (it will decrease your iterations drastically for a non-injective function). You can use the same in your other program with the for loop.
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 7 years ago.
I am not sure if it is iterating through the list or being called multiple times... in either case it shouldn't be doing either of those things. I am pretty new to python and programming in general. Here is the function:
"""
Gets the mass that may have an isotope of +1 neutron for C,N or O (if there is one)
#param mass the mass
#return the mass +1
"""
def getMassPlus(mass):
if (mass)+1 in mass_old2:
return (mass)+1
elif (mass)+1.1 in mass_old2:
return (mass)+1.1
elif (mass)+1.2 in mass_old2:
return (mass)+1.2
elif (mass)+.9 in mass_old2:
return (mass)+.9
and here is the function call:
if ((14.00674*multiplyByN)+(15.994915*multiplyByO)+(1.00794*multiplyByH)) == isotope_masses[i]+.5 or isotope_masses[i]-.5:
if isotope_masses[i]+1 or isotope_masses[i]+1.1 or isotope_masses[i]+1.2 or isotope_masses[i]+.9 in mass_old2:
nextMass = getMassPlus(isotope_masses[i])
What happens is that when I call the function, it somehow iterates through the list isotope_masses (which looks like this: isotope_masses = [1,2,3,4,...]) ten times and assigns nextMass ten values as well. It might also help you to know that the second block of code is part of a larger loop that iterates through the length of isotope_masses. I am not really sure why this issue happening, any ideas would be appreciated. Thanks in advance.
Loop:
for i in range(len(isotope_masses)):
if not noNitrogen(molecules[i]): #molecule has nitrogen and possibly hydrogen
if hasDoubleDig('N'):
multiplyByN = int(molecules[i][3:5])
multiplyByH = int(molecules[i][8:])
else:
multiplyByN = int(molecules[i][3])
multiplyByH = int(molecules[i][7:])
if ((14.00674*multiplyByN)+(1.00794*multiplyByH)) == isotope_masses[i]+.5 or isotope_masses[i]-.5:
if isotope_masses[i]+1 or isotope_masses[i]+1.1 or isotope_masses[i]+1.2 or isotope_masses[i]+.9 in mass_old2:
nextMass = getMassPlus(isotope_masses[i])
if float(intensities[mass_old2.index(nextMass)])/float(intensities[mass_old2.index(isotopes_masses[i])]) == multiplyByN * .00364:
file_isotopes.append("Isotope: is N-15")
else:
file_isotopes.append("Mix of isotopes")
elif not noCarbon(molecules[i]): #molecule has carbon and possibly hydrogen
if hasDoubleDig('C'):
multiplyByC = int(molecules[i][1:3])
multiplyByH = int(molecules[i][8:])
else:
multiplyByC = int(molecules[i][1])
multiplyByH = int(molecules[i][7:])
if ((12.0107*multiplyByC)+(1.00794*multiplyByH)) == isotope_masses[i]+.5 or isotope_masses[i]-.5:
if isotope_masses[i]+1 or isotope_masses[i]+1.1 or isotope_masses[i]+1.2 or isotope_masses[i]+.9 in mass_old2:
print isotope_masses[i]
nextMass = getMassPlus(isotope_masses[i])
if float(intensities[mass_old2.index(nextMass)])/float(intensities[mass_old2.index(isotope_masses[i])]) == multiplyByC * .0107:
file_isotopes.append("Isotope is: C-13")
else:
file_isotopes.append("Mix of isotopes")
There is more to the loop but its just repetitive so I only gave two cases in the loop for the sake of brevity.
I think your if statements are always equating to True.
instead of:
if ((14.00674*multiplyByN)+(15.994915*multiplyByO)+(1.00794*multiplyByH)) == isotope_masses[i]+.5 or isotope_masses[i]-.5
you need the second part of the conditional to also be a full comparison:
if ((14.00674*multiplyByN)+(15.994915*multiplyByO)+(1.00794*multiplyByH)) == isotope_masses[i]+.5 or ((14.00674*multiplyByN)+(15.994915*multiplyByO)+(1.00794*multiplyByH)) == isotope_masses[i]-.5
same thing with the second conditional you have in there.
if isotope_masses[i]+1 or isotope_masses[i]+1.1 or isotope_masses[i]+1.2 or isotope_masses[i]+.9 in mass_old2:
equivalent to:
if a or b or c in x:
is being evaluated as
if (bool(a) or bool(b) or bool(c)) in x:
You need to change it to the following form:
if a in x or b in x or c in x:
Pretty sure this is a duplicate of How do I test one variable against multiple values?
This question already has answers here:
break and continue in function
(4 answers)
Closed 3 years ago.
My question is how can you break from outside a loop. If i can't is there a work around?
def breaker(numberOfTimesYouWantToBreak):
for i in range(0,numberOfTimesYouWantToBreak+1):
return break
while True:
for i in range(0,100000):
breaker(10)
print(i)
The result i want is:
11,12,13,14...
You cannot use the break statement anywhere else but directly in the loop. You cannot return it from another function, it is not an object to be passed around.
You appear to want to skip, not break from the loop, however. You are looking for the continue keyword instead:
for i in range(0,100000):
if i < 10:
continue
print(i)
If you must use a separate function, then have that function return True or False and use an if test to conditionally use continue:
def should_skip(i):
return i < 10
for i in range(0,100000):
if should_skip(i):
continue
print(i)
It's impossible.
The workaround is to put your code into a function and return from the function.
You can't break externally, however, for the same effect you can do this:
for i in range(0,100000):
i += 10 + 1 #(10 is the number you wanted in the break function)
print(i)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
find the maximum number in a list using a loop
I'm finding the maximum number in a list on Python by using a loop. In order to do that, I need to have a loop where it goes through the entire list. What loop can I use that runs through the entire list? I'm new to Python.
You can go through a list with a for loop like:
for item in lst:
# do something with item
However, an easier way to get the maximum item in a list (which appears to be what you want) is:
max(lst)
Repeating a block of code n times, where n is the length of some_list is done like this:
for i in xrange(len(some_list)):
# block of code
or...
i = 0
while i < len(some_list):
# block of code
i = i + 1
max = None
for e in lst:
if max is None or e > max: max = e
But as David already stated, simply calling max(lst) would do the job.