Is there a way to get a for loop to start again at any point within the loop? Say line has a length of three. If the if statement is satisfied and my index increments, I want everything to start checking again at the first value of line.
(Note this whole thing is part of a while True loop).
for line in library:
if message[index:index + len(line)-2] == line[2:]:
ans += line[0]
index += len(line)-2 + 1
I think you need another while True above the for loop.
For example, this is a continuous loop unless there is a break condition
x = [1, 2, 3, 4, 5, 6]
restart = True
while restart:
for i in x:
# add any exit condition!
# if foo == bar:
# restart = False
# break
if i == value: # add your message condition
break
You could replace x with library in your case and i with line. Then instead if i == 4 you add your break condition that resets the loop and if you do have an actual break condition, you set the restart flag to False
Another option would be using a loop counter like n = 2 and use while n < 2: and then set n += 1 whenever your condition mets or n = 0 whenever you want to reset.
If I'm reading it right you want to entirely restart the loop when you find a match. Easiest way to do this is by breaking out of the for loop as you stated you have a while loop above it which remains True and will restart the for loop:
for line in library:
if message[index:index + len(line)-2] == line[2:]:
ans += line[0]
index += len(line)-2 + 1
break
Related
I'm working with while loops and I'm just a bit confused on how to break out of it in the way that I want. So I've nested a for loop within a while loop:
x = True
y = 0
while x:
if y >= 5:
x = False
print('break')
else:
for x in range(7):
y += 1
print('test')
The output that I'm looking for is 5 tests printed out and one break. However, every time I run the program it prints out 7 tests before it goes to the break. I'm not exactly sure, but I think I'm just confused about something within while loops! If someone could explain this to me please let me know :) I have found ways around this, but I'd like to get an understanding of why it doesn't work.
This is because it's performing the entire for loop within the while loop therefore y will become 7 before it checks again. Removing the for loop will resolve this.
x = True
y = 0
while x:
if y >= 5:
x = False
print('break')
else:
y += 1
print('test')
y = 0
while y < 5:
print("test")
y += 1
print("break")
Would work.
There is no point in having another variable like "x" for the while loop when it allows for you to set the condition directly.
Because inner loop will complete before the next iteration of the outer loop. I.e. once the inner loop starts it does all 7 iterations before starting the next iteration of the while loop.
You can do this by just using one loop. Print out “test” increase counter and put in an if condition to break when counter is 5.
The reason 7 tests print rather than 5 is that your entire for loop is executed before you go back to the beginning of your while statement. I think your understanding is that, after one iteration of a for loop, you go back to the beginning of the while loop, but this is incorrect: your for loop is executed completely before going back to the beginning of the while loop.
After you step into the for loop, you increment y 7 times and print test 7 times. y is now >= 5, and you go back into your if statement. The if statement turns x false, thereby "turning off" the while loop, and a break statement is printed. If you just want to print out 5 tests and one break, it would be much easier to simplify your code as such:
y = 0
while True:
if y < 5:
print('test')
y += 1
else:
print('break')
break
Try
i = 0
while True:
if i == 5:
break
print('test')
i = i + 1
I expected that in this If statement, the variable 'i' would increment until it eventually equals 10, and subsequently 'if 10 < 10' would return False, breaking my while loop. But this code seems print until 10 and then get stuck in an infinite loop unless I add an else: break. Why?
i=0
while True:
if i < 10:
i = i + 1
print(i)
while X repeats when X equals to True so in while True it's always True. It only breaks with break statement.
In your code, you only check the value inside the while loop with if so neither you break the while loop nor you change True to False in while True.
If you want to use while:
i = 0
while i < 10:
i += 1
print(i)
Or
i = 0
while True:
if i < 10:
i += 1
print(i)
else:
break
Without while:
for i in range(10):
print(i)
while True
will make the loop run forever because "true" always evaluates to true. You can exit the loop with a break.
To achieve what you want to do, I would use
while i < 10:
print (i)
i++
That is because there isn't anything telling you to terminate the loop. So it will continue even after the if statement isn't satisfied.
This is why it is generally not a great practice to use while True
You can achieve the same thing with a for loop when the break condition is built into the loop:
for i in range(0, 10):
print(i)
If you want to use while True then you can go for:
i=0
while True:
i = i + 1
print(i)
if i == 10:
break
I think you need to understand a few things here, as you have set while True which means statement will never gets false so there is never end to while loop even if if condition gets fail. So the while loop will continue running till you interrupt.
The only way you can achieve this without break is like this, where you have a variable which will reset the condition of while loop to false when if loop fails
i=0
condition = True
while condition:
if i<10:
i=i+1
print(i)
else:
condition=False
I have a bit of code and I'm having trouble understanding why the loop is an infinite loop even though I have an else condition which should end the loop.
def add1(*args):
total = 0
add = True
for num in args:
while add == True:
if num!=6:
total = total + num
else:
add = False
return total
add1(1,2,3,6,1)
My question is, I have an else statement that changes the add to 'False' hence the loop should stop but for some reason it doesn't.
However, if I make a slight alteration to the code as such, it stops:
def add1(*args):
total = 0
add = True
for num in args:
while add == True:
if num!=6:
total = total + num
break
else:
add = False
return total
add1(1,2,3,6,1)
basically, adding a break.
I don't understand how expert python coders actually interpret 'break' in their minds. I've read articles on break, but still can't seem to understand it quite as well.
I don't understand why the 'break' is needed and why the 'else' can't suffice.
When you enter the for loop, num gets the value 1 (the first value in args). Then you enter the while loop (since add is True). Now, because num does not equal 6, you enter the if block, so the else block does NOT executes. Then, you just return to the while loop, and the value of num doesn't change. Then, because num does not equal 6 (remember it didn't change, it is still 1), once again you enter the if block, and so on until you terminate the program.
When you add the break, you exit the closest loop, which in this case is the while loop, so the for loop continues, until num gets the value 6, and add becomes False. When that happens, the while loop never executes again.
def add1(*args):
total = 0
add = True
for num in args:
if add == True:
if num!=6:
total = total + num
else:
add = False
break #breaking the for loop for better performance only.
return total
add1(1,2,3,6,1)
this adds till 6 is not encountered. you are using while loop unnecessarily. you have to break the infinite loop by some condition and that condition is when num!=6. even your else part can break the infinite while loop, but according to me the while loop itself is unnecessary.
I believe the purpose of your code is to sum up elements in *args up to first occurrence of number 6. If that is the case, the while loop is redundant here. Changing the first code snippet:
def add1(*args):
total = 0
for num in args:
if num != 6:
total = total + num
else:
break
return total
add1(1, 2, 3, 6, 1)
What actually happens in your original code is that the num variable doesn't change in any way when iterating in while loop, so it never enters the else part, effectively getting stuck on the first input argument that is not 6, see below:
def add1(*args): # [1, 2, 3, 6, 1]
total = 0
add = True
for num in args: # first element is 1. num = 1
while add == True:
if num != 6: # num = 1 always
total = total + num
# adding break here gets out of the while loop on first iteration, changing num = 2
# and later to 3, 6...
else: # else is never reached
add = False
return total
add1(1, 2, 3, 6, 1)
You should change the below codes:
from
if num != 6:
to
if total != 6:
Imagine I have the following code:
i=0
while True:
if flag==True and i=i+5:
func()
.
.
.
i+=1
break
shouldn't be i==i+5?
I want to run func() each 5 times.
i = i + 5 is always true unless previous value of i is -5. However, if i = i + 5 is invalid syntax. i == i + 5 is always false. In if flag == True portion explicit comparing with True is redundant. if flag is sufficient.
Now come to the main question. If you want to call func in every five iteration of the loop then you have to use modules operator.
while True:
if flag and i % 5 == 0:
func()
# Other stuffs that you want to run at each iteration
And if you have a break at end of while loop then it will immediately break after first iteration. Ideally, a break/continue statements should be inside an if block.
If i is divisible by 5:
i % 5 == 0
Im currently using a for loop.
it iterates through a bunch of commands
and at the end, I want it to print something.
within this for loop, is a if-else statement.
I use break to break out the if- statement, then it goes straight to the else portion.
for x in list:
if x is 1:
do a bunch of commands
break
else:
do a bunch of other commands
print 'Success'
I need the print statement to stay in the If-loop so it is conditional, but out of the for loop so it doesn't repeat a ton of times.
any ideas?
I want it to print 'Success' when ONLY when x does not equal 1. But only once at the end.
You can use a flag -- a variable that you set to indicate that an event occurred (in this case, that the else branch was reached).
success = False
for x in list:
if x is 1:
do a bunch of commands
break
else:
do a bunch of other commands
success = True
if success:
print 'Success'
What's happening here is that the else case may be reached multiple times in the loop, setting the success variable to True (potentially) multiple times. The if statement at the end checks if the flag is True at the end, so 'Success' is printed at most once.
You don't need a flag in this case, python have you covered, use the for else
for x in list:
if x is 1:
# do a bunch of commands
break
else:
# do a bunch of other commands
else:
# only if we didn't break from the loop (no 1 in the list)
print 'Success'
must set flag
flag = 0
def findlength(s):
length = len(s)
for p in password:
if(length >= 6):
flagA = 1
else:
flagA = 0
return flagA
def findupper(u):
for p in password:
if(p.isupper() == 1):
flagB = 0
else:
flagB = 1
return flagB
def findlower(l):
for p in password:
if(p.islower()):
flagC = 0
else:
flagC = 1
return flagC
def findnumber(d):
for p in password:
if(p.isdigit()):
flagD = 1
else:
flagD = 0
return flagD