I have a piece of code. Here, I am running a for loop. If the if statement is not met, I want to restart that for loop. How should I do this? sp is a library btw.
for i in range (10000):
#my codes
a= sp.levene(#my variables)
if a[1] < 0.05:
#I want to restart for loop again
else:
#doing something
You probably don't want to use a for loop, since you aren't iterating over a particular sequence of numbers (i is going to jump around based on what happens inside the loop). Using a while you'd do:
i = 0:
while i < 10000:
# my code
a = sp.levene() # my variables
if a[1] < 0.05:
i = 0
continue
i += 1
# doing something
continue restarts the loop at the beginning of the loop body, and having set i = 0 it's now in the same state it was in at the first iteration.
The simplest way to handle this is:
while True:
for i in range(100000):
...
if a[1] < 0.05:
# this will exit out of the for loop, but the while
# loop will keep going
break
else:
....
# if we've successfully finished the "for" loop, then break out of
# the while loop
break
If your logic is a little bit more complicated:
done = False
while not done:
for i in range(100000):
...
if a[1] < 0.05:
# this will exit out of the for loop, but the while
# loop will keep going
break
else:
# set done to True if you've decided you don't need to perform
# the outer loop any more
other stuff
# likewise, set done to True if you're done with the outer while loop
To build on Frank Yellin's answer if you don't want to use break else break.
continueloop=True
while(continueloop):
for i in range (10000):
#my codes
a=sp.levene #my variables
if a[1] < 0.05:
#I want to restart for loop again
continueloop=True
else:
continueloop=False
#doing something
Hope you find a suitable answer!
I think what you are looking to do is have that function inside a loop. If the statement fails then on the else statement call the function again with new parameters. Basically, you want recursion on your loop is what I'm understanding.
def RecursionFunc() #3) when this function is called code runs from here
for i in range (10000):
#my codes
a= sp.levene(#my variables)
if a[1] < 0.05:
RecursionFunc() #2) will make you jump to the top again basically calling itself
break #4) will exit the current loop
else:
RecursionFunc() # 1)This will be the first code that gets executed
And the recursion will keep the function going and you can do plenty of other stuff with this. I know you want to break the loop and run again you can also change the "i" value on the next recursion run. If you give recursionFunc(int i) then you can basically set yours for loop to a new I value on the next run too. Can do a lot of cool things like this.
Related
Hi if i want to know when i reached the last iteration of my
for c in text:
In C it will seem like :
for (int i=0;i<strlen(str);i++)
if (i == strlen(str))
printf("The last index");
The idiomatic way to test whether a loop finished completely (i.e. exhausted its iterable) is to use for with else:
s = 'Hello World!'
for c in s:
# do something with character c, your code might break the loop
pass
else:
# the loop did not break, and iterated over all characters
print('The loop finished!')
My solution would be to create a counter outside the loop and increment it every time the loop iterates so you can have a reference of what the loop index is.
Check out the Python built-in function "enumerate", here is a link: http://book.pythontips.com/en/latest/enumerate.html
You can use the enumerate statement. It is written like this:
for index, val in enumerate(N):
if index + 1 == len(N):
print('The last index')
If you want see in console the state of your loop, you can use tqdm,
from tqdm import tqdm
for i in tqdm(range(N)):
#Some logic here
I'm new to a programming language and wanted to start with Python as its the recommendation of most people (as far as i see).
So, im practising on some functions to improve my understanding on loops, and basic statements etc. Though i'm not very good at it yet, i do believe that i'll improve sooner or later.
Here is an example where i'm stuck at:
def L():
List = []
TauS = []
a = 12
for i in range(1,a+1):
if a % i == 0:
List.append(i)
if a % len(List) == 0:
TauS.append(a)
print(List)
print(TauS)
L()
This is the function i want to have and the output is:
[1, 2, 3, 4, 6, 12]
[12]
As i expected.However, the problem is that i want "a" to be a variable instead of a constant.Something like:
def L():
List = []
TauS = []
for a in range(2,20):
for i in range(1,a+1):
if a % i == 0:
List.append(i)
if a % len(List) == 0:
TauS.append(a)
print(List)
print(TauS)
L()
Fails because it seems like for loop is working before the 2nd if statement (if a % len(list)) == 0: TauS.append(a)).I have also tried a "while" loop instead of a "for" loop as:
a = 2
while a <= 20:
for i in range(1,a+1):...(The rest is the same)
It would be a better idea if your help focus on the basic ideas instead of just giving the right function.
Thanks a lot from now!
Regards.
Python uses indention levels to tell whether code is in within a function, loop or condition, the general thing being that if there is a : then all the code indented underneath it is within that statement.
The problem with your code is that the second if statement is on the same indention level as the for loop rather than being on the indention level below the for loop. This means that rather than running in the for loop it runs after it.
So to fix your code all you need to do is select the if statement and press crtl + ] which is pythons keyboard shortcut for indent code section.
edit:
I think what you're asking for is to get all the factors of numbers from 2 to 19 and then print numbers where the number of factors is a factor of that number.
def L():
List = []
TauS = []
for a in range(2,20):
l=[] #this is the list for each individual number
#if i is a factor of a add it to l
for i in range(1,a+1):
if a % i == 0:
l.append(i)
#if length of l is a factor of a add a to TauS
if a % len(l) == 0:
TauS.append(a)
List.append(l)
print(List)
print(TauS)
L()
It fails because of variable scope.
Python uses indention to represent code block. So, here for loop and 2nd if condition has same indention which means they belong to same code block and can access variables defined in the same or the outer code block. "List" & "Taus" in this case.
However, Variable "a" is localize to outer for loop and can be access in the same or inner for loop and cant be access from outside. Similarly variable "i" is specific to inner for loop and cant be access outside of the loops block, not even from outer for loop.
Hope it helps...
I am practicing Python with Project Euler, question 1, but the function I wrote to solve it is taking way too long.
I figure it's because the way I coded it not the actual method itself.
When I run this function with 10 or 15 iterations it spits out an answer instantly, but as soon as I jump it up to even 20, it doesn't show me anything for even minutes.
This is obviously a big problem if I need to go to 1000 iterations.
def pe1(n):
counter = 1
total = 0
while counter < n:
if counter%3==0:
total=total+counter
if counter%5==0:
if counter%3==0:
continue
total=total+counter
if counter % 25 == 0:
print (total)
counter=counter+1
return (total)
Because as soon as counter hits 15, your loop goes into an infinite continue - it's always going to hit the second if statement's case.
You need to move your counter = counter + 1 line before the continue, or better yet, use something like for counter in range(1,n).
Consider the case if counter equals 15 and look at what happens where counter%5==0 and counter%3==0, which will first occur at that time.
Consider also what will not happen for that value of counter, specifically, the line counter=counter+1 won't be executed.
To avoid traps like this one, consider using
if ...
elif ...
elif ...
else ...
You can use table-driven. Like this.
counter_map = {3:fun1, 5:func2, 25:fun3} # key is remainder.Of course,fun can be replaced with lambda.
So I want to do something like this:
for i in range(5):
print(i);
if(condition==true):
i=i-1;
However, for whatever reason, even though I'm decrementing i, the loop doesn't seem to notice. Is there any way to repeat an iteration?
for loops in Python always go forward. If you want to be able to move backwards, you must use a different mechanism, such as while:
i = 0
while i < 5:
print(i)
if condition:
i=i-1
i += 1
Or even better:
i = 0
while i < 5:
print(i)
if condition:
do_something()
# don't increment here, so we stay on the same value for i
else:
# only increment in the case where we're not "moving backwards"
i += 1
Python loop using range are by-design to be different from C/C++/Java for-loops. For every iteration, the i is set the the next value of range(5), no matter what you do to i in between.
You could use a while-loop instead:
i = 0
while i<5:
print i
if condition:
continue
i+=1
But honestly: I'd step back and think again about your original problem. Probably you'll find a better solution as such loops are always error-prone. There's a reason why Python for-loops where designed to be different.
You have a misunderstanding about loops in Python. The for loop doesn't care what you do with i at each iteration, because it is not related to the logic of the loop at all. Modifying i just rebinds a local variable.
You would need to use a while loop to achieve the behaviour you're expecting, where the state of i does affect the control flow of the loop:
import random
i = 0
while i < 5:
print(i)
i += 1
if random.choice([True, False]):
i -= 1
range(5) creates a list with numbers 0 thru 4 in it - [0, 1, 2, 3, 4].
When you run a for loop over it, you are iterating over the list. Doing i-= 1 will only decrement the value of that particular element of the list, and the iteration will continue.
Like the other answers here have suggested, you should use a while loop.
i= 0
while i<5:
# do stuff
if #condition:
i-= 1 # or +
i+= 1
Repeating many other answers, and just for completeness, you will need to use a while loop.
i = 0
while i < 5:
print(i)
if (not condition):
i+=1
If you want to move back an iteration in the loop (instead of repeating an iteration), then use this:
i = 0
while i < 5:
print(i)
if (condition):
i -= 1
else:
i += 1
Essentially, while i < 5 evaluates upon each iteration, and checks if i < 5. Thus by decrementing/not changing i, we get something like this: (values of i)
Not changing: 1->2->3-(condition satisfied)> 3 -> 4 -> 5
Decrementing: 1->2->3-(condition satisfied)>2 -> 3 -> 4 -> 5
The reason why i=i-1 in your for loop doesn't make it repeat the iteration is simple. In the for loop, i is assigned the value of the next item in the for loop. Python could care less about what you do with i, as long as it is able to assign the next item to it. Thus, the for loop for i in <your_iterable>:<do whatever> is closer to this:
_i = 0
_length = len(<your_iterable>)
while _i < _length:
i = _i
_i += 1
<do whatever>
However, in this analogy, you wouldn't be able to access the _ predicated variables (_i,_length). This is how I simplify the logic of the for loop. Note that regardless of what i is assigned to, it will be assigned to _i upon the next iteration, and the loop really doesn't care about what i is.
Utilize a while loop:
i = 0
while i < 5:
print(i)
if condition:
i -= 1
i += 1
As has been mentioned, this is rather unidiomatic Python. Perhaps if you post what you are trying to achieve we can give some better advice.
In Python it's possible to set up a two-way exchange between an iterator (what comes after in in a for..in loop) and its consumer (code inside the loop). To achieve this, you can use send in the consumer code to "inject" a value in a generator. In your case, you can simply send back the current value once the condition is met and wrap the range call in a generator that repeats whatever is sent back to it. Here's some code for you to play, intentionally verbose for clarity:
def repeateble(it):
buf, it = None, iter(it)
while True:
if buf is None:
# the buffer is empty, send them the next elem
val = next(it)
else:
# there's something in the buffer
# let's send that back
val = buf
# send the value and wait what they say
back = yield val
if back:
# they've sent us something!
# give them some dummy value as a result of send()
yield None
# and save what they've sent in a buffer
# for the next iteration
buf = back
else:
# they haven't sent anything
# empty the buffer
buf = None
from random import randint
# create a repeateble generator
rng = repeateble(range(100))
for x in rng:
print(x)
# check "some condition"...
if randint(1, 100) > 80:
print('repeat:')
# send the current value back to the generator
# it will be returned on the next iteration
rng.send(x)
You can use readlines if you're iterating through a file and pull out the previous lines based on a condition.
with open("myfile.txt", "r") as f:
text = f.readlines()
for row in range(0, len(text)):
if re.search("Error", text[row]):
print(text[row-1].strip())
#hello , i wounder why my code keep stoping at the secound while loop and doesn't do anything
print"*******************************"
a = 0
deg_list =[]
deg_list_a=[]
deg_list_b=[]
deg_list_c=[]
degree=input("Enter the students Degree:")
while a<=degree:
deg_list.append(degree);
degree=input("Enter the students Degree:")
print "Degree List :",deg_list
print len(deg_list)
while len(deg_list)>=0:
if deg_list[a]>=16:
deg_list_a.append(deg_list[a])
x=+1
elif 15>deg_list[a]>=10:
deg_list_b.append(deg_list[a])
x=+1
else :
deg_list_b.append(deg_list[a])
x=+1
print deg_list_a
print deg_list_b
print deg_list_c
Your code enters an endless loop.
Both of your while loops have problems with the condition which allows them to terminate. Since your code never changes the value of a, the first loop becomes while 0<=degree, and so the first loop terminates when the user inputs a negative value. But the variable a can be removed from your program.
The while loop continues as long as len(deg_list) >= 0. However, no code within the loop decreases the length of deg_list, so the while loop continues forever.
The code below could help you get this working:
deg_list =[]
deg_list_a=[]
deg_list_b=[]
deg_list_c=[]
degree=input("Enter the students Degree:")
while degree > 0:
deg_list.append(degree);
degree=input("Enter the students Degree:")
print len(deg_list)
while len(deg_list) > 0: # Strictly greater than 0, not equal to 0.
if deg_list[0] >= 16:
# Use pop to access first element
deg_list_a.append(deg_list.pop(0))
elif deg_list[0] >= 10: # One comparison per statement, only.
deg_list_b.append(deg_list.pop(0))
else:
deg_list_c.append(deg_list.pop(0)) # c, not b.
print deg_list_a
print deg_list_b
print deg_list_c
You're never modifying deg_list, so your loop becomes infinite. Even removing all elements wouldn't help since you're comparing against 0 -- the loop condition will never be false.
Well.
It looks to me that a is set to 0 in the beginning and then never changed, so doing something with deg_list[a], that is the first element in the list, isn't going to do very much. In addition, your looping condition is len(deg_list) >= 0, and len(deg_list) will never change.
But there are more fundamental issues with your code. Imagine you were changing the length of deg_list: in this case you would be changing the very list you're looping over, which is usually (if you are not very very certain what you're doing) a recipe for disaster. What I think you should envisage doing is a loop along the lines of:
for degree in deg_list:
if [degree fulfils some condition]:
[do something with degree]
elif [degree fulfils some other condition]:
[do something else]
...
else:
[whatever]
Last, from your comparison it seems that the "degrees" are all small integers. You may want to test for that -- it's user input and you have to expect anything being thrown at your input -- before doing things like if degree >= 16.
It looks like you are trying to loop through all the members of deg_list, but you are waiting for deg_list to be empty, and each time through the loop you are incrementing "x," which is never even read.
If you really are trying to traverse through deg_list, try this for your second loop:
for degree in deg_list:
if degree >= 16:
deg_list_a.append(degree)
elif degree >= 10:
deg_list_b.append(degree)
else :
deg_list_c.append(degree)