Using counter in condition in python - python

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

Related

While Loop Counter Confusion

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

If statement returning False in While True loop (Python)

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

While loop that's meant to be infinite freezes after first cycle

My goal is to make a program that prints onscreen all of the prime numbers it can find, however I have this issue where the while loop runs only once, instead of repeating forever.
def isPrime(num):
if num < 2:
return False
if num == 2:
return True
if num % 2 == 0:
return False
i = 3
while i * i <= num:
if num % i == 0:
return False
i += 2
x = 1
while True:
x += 1
if isPrime(x):
print (x)
I also have tried adding print("You can see this.") at the very end of the code, and it runs, but only once.
I'm sure it's a common mistake, since Python is very strict on indentation, but could you guys help me discover it? Thanks in advance.
You need to return True at the very end, after and outside the final loop. Otherwise the function ends without explicitly returning anything, so it implicitly returns None which is interpreted as false.
The i +=2 is indented too deep, the inner loop never quits.
It should read
while i * i <= num:
if num % i == 0:
return False
i += 2
Otherwise i never increases and the loop goes on and on and on.

getting a for loop to restart if a condition is satisfied

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

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

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

Categories

Resources