Using continue in while loop for python - python

My initial code...
name="LOVE"
i=0
while i < len(name):
i=i+1
if name[i] == "V":
print('Hi')
continue
print('Hello')#never printed
print(name[i])
print("The end")
The desired outcome is
L
O
Hi
E
The end
I have read other answers on this topic and I was either unable to understand or didn't find the answer I was looking for.
I know writing continue in while loop is bad practice, even so I wanted to know whether there was a way to use it without throwing an error(logical or IndexError) or going to an infinite loop.
'while'
as of my knowledge, doesn't have an option of
while(i++<len(name))
in python, so that didn't work.
Since the control is transferred to the beginning of the loop and test expression is not evaluated again,
I tried keeping the increment statement above the continue block and the print statement below to be logically consistent with the desired output.
First I lost 'L' in my output with 'IndexError' at 'if' statement and I was expecting the same error at print statement in the end. So I tried to improve by beginning index from -1 instead and catching my error.
name="LOVE"
i=-1
try:
while i < len(name):
i=i+1
if name[i] == "V":
print('Hi')
continue
print('Hello')#never printed
print(name[i])
except IndexError:
print()
print("The end")
In using for, the continue statement transfers control simply to next iteration in which by virtue of being the next iteration the counter(val) is already incremented so it works fluidly. Like below,
for val in "LOVE":
if val == "V":
print('Hi')
continue
print('Hello')#never printed
print(val)
print("The end")
Again I know of this but that is not what I am interested in...
In summary what I would like to know is if there is a more elegant way to do this without a try catch block, some other kind of implementation of continue in while to reach desired output in Python 3.x?
P.S:-this is my first question on this forum, so please go a bit easy on me.

You don't really need continue, just an else clause on your if statement. (Also, since i == 0 to start, you need to wait until you've used i as an index before incrementing it.)
name="LOVE"
i=0
while i < len(name):
if name[i] == "V":
print('Hi')
else:
print(name[i])
i=i+1
print("The end")
or
for c in name:
if c == "V":
print('Hi')
else:
print(c)

This really is a for job. You want an end to the looping, represented by both the except clause and the i < len(name) condition, and a loop increment, presented by the i=i+1 increment. Both of these tasks are typically performed by an iterator, and strings are iterable. It is possible to rewrite a for in while form, but it's not terribly meaningful:
i = iter(name)
while True:
try:
c = next(i)
except StopIteration:
break
print('Hi' if c == 'V' else c)
It's just much easier to write for c in name.
You could also use a finally, which should execute no matter how the try is left:
i = 0
while i < len(name):
try:
if ...:
continue
finally:
i += 1

The elegant (pythonic) way to solve this problem is to use for-loop, like others have suggested. However, if you insist on using while-loop with continue, you should try to tweak the condition of the while-loop. For example like this:
name="LOVE"
i=-1
while i < len(name)-1:
i=i+1
if name[i] == "V":
print('Hi')
continue
print('Hello')#never printed
print(name[i])
print("The end")

string="LOVE"
i=0
while i<len(string):
if string[i]=="V":
print("HI")
i+=1
continue
else:print(string[i])
i+=1
print("Thank You")

Related

Get stuck in a 'while True' loop python

I just learned about break and return in Python.
In a toy code that I wrote to get familiar with the two statements, I got stuck in a loop, but I don't know why. Here is my code:
def break_return():
while True:
for i in range(5):
if i < 2:
print(i)
if i == 3:
break
else:
print('i = ', i)
return 343
break_return()
I'm new to programming, any suggestions will be appreciated.
With the for-else construct you only enter the else block if the for loop does not break, which your for loop always does because i inevitably becomes 3 with your range generator. Your infinite while loop is therefore never able to reach the return statement, which is only in the said else block.
nvm I'm super wrong here
First of all, when you define a function in Python, any code that belongs in the function should be in the same indentation block. With this in mind, your code would look like this:
def break_return():
while True:
for i in range(5):
if i < 2:
print(i)
if i == 3:
break
else:
print('i = ', i)
return 343
break_return()
The next problem I see is that your else statement isn't correctly formatted with an if statement. If you mean for it to go on the 2nd if statement, your code would look like this:
def break_return():
while True:
for i in range(5):
if i < 2:
print(i)
if i == 3:
break
else:
print('i = ', i)
return 343
break_return()
This is only formatting. But in this example, the code would only run once because it immediately returns and exits the function.
I think this may be a better example of using both break and return:
def break_return(value):
for i in range(5):
print(i)
if i == 3:
break #This exits the for loop
if i == 4:
print("This won't print!")
#Won't print because the loop "breaks" before i ever becomes 4
return value * 2 #Returns the input value x 2
print(break_return(30)) #Display the return value of break_return()
This demonstrates how break exits a for loop and how return can return a value from the function.
The output of the code above is:
0 #Value of i
1 #Value of i
2 #Value of i
3 #Value of i
60 #The value returned by the function
Glad to hear you're learning Python! It's a lot of fun, and super useful.

Python continue Not Working Properly

I am writing a method using Python and I believe that the continue statement is not working properly. Can some explain to me what is wrong there?
The method code is below:
def xlToLinkedDt(lst1, lst2, name1, name2):
logging.info(">> New iteration")
dates1, times1, dates2, times2 = [], [], [], []
for i, (dt1, dt2) in enumerate(zip(lst1, lst2)):
if bool(dt1) + bool(dt2) == 1:
name = name1 if not dt1 else name2
issues.append("The %s date of trip no. %d must be provided." %(name, i+1))
dates1.append("")
dates2.append("")
times1.append("")
times2.append("")
logging.info("Exiting loop")
continue
logging.info(Continued after bool condition.)
raise AssertionError("Stop!")
When I run this code I get an error and the following logging in one of the iterations:
>> New iteration
>> Exiting loop
>> Continued after bool condition
The code is not supposed to log both messages, only one of them. Also when I replaced continue with break it worked well. What am I missing?
The code is not supposed to log both messages.
Yes, it is.
After your code executes continue, the loop moves back to the beginning of the block inside the for-loop, in the next iteration. If the condition in your if-block is not met at the next iteration, you will get exactly the behaviour you describe.
In [5]: for i in range(10):
print("Trying with i={:d}".format(i))
if i%2 == 0:
print("`i` even, continuing")
continue
print("What am I doing here?")
...:
Trying with i=0
`i` even, continuing
Trying with i=1
What am I doing here?
Trying with i=2
`i` even, continuing
Trying with i=3
What am I doing here?
Trying with i=4
`i` even, continuing
Trying with i=5
What am I doing here?
Trying with i=6
`i` even, continuing
Trying with i=7
What am I doing here?
Trying with i=8
`i` even, continuing
Trying with i=9
What am I doing here?
As you can see, there is still a What am I doing here? printed after the i even, continuing notification, but it belongs to a later iteration of the loop. If we replace continue by break, we get very different behaviour:
In [6]: for i in range(10):
print("Trying with i={:d}".format(i))
if i%2 == 0:
print("`i` even, not continuing")
break
print("What am I doing here?")
...:
Trying with i=0
`i` even, not continuing
As you can see, it stops immediately because (by our definition), 0 is even.
You used continue, I guess you meant break.
continue will skip to the next iteration of your for loop.
break will leave the for loop.
Try that :
def test():
print("Function start")
for i in range(10):
if i == 1:
print("Exiting loop")
continue
print("Am I printed or not ?")
print("I'm out of the loop")
Then replace continue by break and see what happens.
Since print("Am I printed or not ?") is part of the for loop, it will be executed on next for iteration after "Exiting loop", if you use continue. If you use break, it will be skipped.

Is the continue statement necessary in a while loop?

I'm confused about the use of the continue statement in a while loop.
In this highly upvoted answer, continue is used inside a while loop to indicate that the execution should continue (obviously). It's definition also mentions its use in a while loop:
continue may only occur syntactically nested in a for or while loop
But in this (also highly upvoted) question about the use of continue, all examples are given using a for loop.
It would also appear, given the tests I've run, that it is completely unnecessary. This code:
while True:
data = raw_input("Enter string in all caps: ")
if not data.isupper():
print("Try again.")
continue
else:
break
works just as good as this one:
while True:
data = raw_input("Enter string in all caps: ")
if not data.isupper():
print("Try again.")
else:
break
What am I missing?
Here's a really simple example where continue actually does something measureable:
animals = ['dog', 'cat', 'pig', 'horse', 'cow']
while animals:
a = animals.pop()
if a == 'dog':
continue
elif a == 'horse':
break
print(a)
You'll notice that if you run this, you won't see dog printed. That's because when python sees continue, it skips the rest of the while suite and starts over from the top.
You won't see 'horse' or 'cow' either because when 'horse' is seen, we encounter the break which exits the while suite entirely.
With all that said, I'll just say that over 90%1 of loops won't need a continue statement.
1This is complete guess, I don't have any real data to support this claim :)
continue just means skip to the next iteration of the loop. The behavior here is the same because nothing further happens after the continue statement anyways.
The docs you quoted are just saying that you can only use continue inside of a loop structure - outside, it's meaningless.
continue is only necessary if you want to jump to the next iteration of a loop without doing the rest of the loop. It has no effect if it's the last statement to be run.
break exits the loop altogether.
An example:
items = [1, 2, 3, 4, 5]
print('before loop')
for item in items:
if item == 5:
break
if item < 3:
continue
print(item)
print('after loop')
result:
before loop
3
4
after loop

If and elif in Python for good programming practices

Hello there I'm currently trying to get a good grasp of the if, elif, else structure in Python. I'm trying some weird combinations in python having a test program to know the output in this if, if, elif, elif, else code. However I'm getting weird results such as this
input = raw_input('Please enter the required digit: ')
intput = int(input)
if intput == 0:
print 'if1'
if intput == 1:
print 'if2'
elif intput == 0:
print 'elif1'
elif intput == 1:
print 'elif2'
else:
print 'else'
if I in put 1 it will print "if2", I thought that it will also print "elif2" and other shenanigans when I try to change the "intput == n" code. So my question is do I have to stick to the if,elif, elif, .... n * elifs, else method which seems to me working alright than working with the wacky if,if.... n * ifs, elif, elif, ...n* elifs, else.
Thanks
The elif tree is designed such that at anywhere along if one of the statement turns out to be True, the rest of the elifs will not be evaluated.
Here's a tutorial that might help you understand if else better.
this may be more clear to understand:
if input == 0:
print "if1"
switch(input):
case 1:
print "if2"
break
case 0:
print "elif1"
break
case 1:
print "elif2"
break
default:
print "else"
break
of course, the code does not work.

Else clause on Python while statement

I've noticed the following code is legal in Python. My question is why? Is there a specific reason?
n = 5
while n != 0:
print n
n -= 1
else:
print "what the..."
Many beginners accidentally stumble on this syntax when they try to put an if/else block inside of a while or for loop, and don't indent the else properly. The solution is to make sure the else block lines up with the if, assuming that it was your intent to pair them. This question explains why it didn't cause a syntax error, and what the resulting code means. See also I'm getting an IndentationError. How do I fix it?, for the cases where there is a syntax error reported.
The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won't be executed.
One way to think about it is as an if/else construct with respect to the condition:
if condition:
handle_true()
else:
handle_false()
is analogous to the looping construct:
while condition:
handle_true()
else:
# condition is false now, handle and go on with the rest of the program
handle_false()
An example might be along the lines of:
while value < threshold:
if not process_acceptable_value(value):
# something went wrong, exit the loop; don't pass go, don't collect 200
break
value = update(value)
else:
# value >= threshold; pass go, collect 200
handle_threshold_reached()
The else clause is executed if you exit a block normally, by hitting the loop condition or falling off the bottom of a try block. It is not executed if you break or return out of a block, or raise an exception. It works for not only while and for loops, but also try blocks.
You typically find it in places where normally you would exit a loop early, and running off the end of the loop is an unexpected/unusual occasion. For example, if you're looping through a list looking for a value:
for value in values:
if value == 5:
print "Found it!"
break
else:
print "Nowhere to be found. :-("
Allow me to give an example on why to use this else-clause. But:
my point is now better explained in Leo’s answer
I use a for- instead of a while-loop, but else works similar (executes unless break was encountered)
there are better ways to do this (e.g. wrapping it into a function or raising an exception)
Breaking out of multiple levels of looping
Here is how it works: the outer loop has a break at the end, so it would only be executed once. However, if the inner loop completes (finds no divisor), then it reaches the else statement and the outer break is never reached. This way, a break in the inner loop will break out of both loops, rather than just one.
for k in [2, 3, 5, 7, 11, 13, 17, 25]:
for m in range(2, 10):
if k == m:
continue
print 'trying %s %% %s' % (k, m)
if k % m == 0:
print 'found a divisor: %d %% %d; breaking out of loop' % (k, m)
break
else:
continue
print 'breaking another level of loop'
break
else:
print 'no divisor could be found!'
The else-clause is executed when the while-condition evaluates to false.
From the documentation:
The while statement is used for repeated execution as long as an expression is true:
while_stmt ::= "while" expression ":" suite
["else" ":" suite]
This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.
The else clause is only executed when the while-condition becomes false.
Here are some examples:
Example 1: Initially the condition is false, so else-clause is executed.
i = 99999999
while i < 5:
print(i)
i += 1
else:
print('this')
OUTPUT:
this
Example 2: The while-condition i < 5 never became false because i == 3 breaks the loop, so else-clause was not executed.
i = 0
while i < 5:
print(i)
if i == 3:
break
i += 1
else:
print('this')
OUTPUT:
0
1
2
3
Example 3: The while-condition i < 5 became false when i was 5, so else-clause was executed.
i = 0
while i < 5:
print(i)
i += 1
else:
print('this')
OUTPUT:
0
1
2
3
4
this
My answer will focus on WHEN we can use while/for-else.
At the first glance, it seems there is no different when using
while CONDITION:
EXPRESSIONS
print 'ELSE'
print 'The next statement'
and
while CONDITION:
EXPRESSIONS
else:
print 'ELSE'
print 'The next statement'
Because the print 'ELSE' statement seems always executed in both cases (both when the while loop finished or not run).
Then, it's only different when the statement print 'ELSE' will not be executed.
It's when there is a breakinside the code block under while
In [17]: i = 0
In [18]: while i < 5:
print i
if i == 2:
break
i = i +1
else:
print 'ELSE'
print 'The next statement'
....:
0
1
2
The next statement
If differ to:
In [19]: i = 0
In [20]: while i < 5:
print i
if i == 2:
break
i = i +1
print 'ELSE'
print 'The next statement'
....:
0
1
2
ELSE
The next statement
return is not in this category, because it does the same effect for two above cases.
exception raise also does not cause difference, because when it raises, where the next code will be executed is in exception handler (except block), the code in else clause or right after the while clause will not be executed.
I know this is old question but...
As Raymond Hettinger said, it should be called while/no_break instead of while/else.
I find it easy to understeand if you look at this snippet.
n = 5
while n > 0:
print n
n -= 1
if n == 2:
break
if n == 0:
print n
Now instead of checking condition after while loop we can swap it with else and get rid of that check.
n = 5
while n > 0:
print n
n -= 1
if n == 2:
break
else: # read it as "no_break"
print n
I always read it as while/no_break to understand the code and that syntax makes much more sense to me.
thing = 'hay'
while thing:
if thing == 'needle':
print('I found it!!') # wrap up for break
break
thing = haystack.next()
else:
print('I did not find it.') # wrap up for no-break
The possibly unfortunately named else-clause is your place to wrap up from loop-exhaustion without break.
You can get by without it if
you break with return or raise → the entire code after the call or try is your no-break place
you set a default before while (e.g. found = False)
but it might hide bugs the else-clause knows to avoid
If you use a multi-break with non-trivial wrap-up, you should use a simple assignment before break, an else-clause assignment for no-break, and an if-elif-else or match-case to avoid repeating non-trival break handling code.
Note: the same applies to for thing in haystack:
Else is executed if while loop did not break.
I kinda like to think of it with a 'runner' metaphor.
The "else" is like crossing the finish line, irrelevant of whether you started at the beginning or end of the track. "else" is only not executed if you break somewhere in between.
runner_at = 0 # or 10 makes no difference, if unlucky_sector is not 0-10
unlucky_sector = 6
while runner_at < 10:
print("Runner at: ", runner_at)
if runner_at == unlucky_sector:
print("Runner fell and broke his foot. Will not reach finish.")
break
runner_at += 1
else:
print("Runner has finished the race!") # Not executed if runner broke his foot.
Main use cases is using this breaking out of nested loops or if you want to run some statements only if loop didn't break somewhere (think of breaking being an unusual situation).
For example, the following is a mechanism on how to break out of an inner loop without using variables or try/catch:
for i in [1,2,3]:
for j in ['a', 'unlucky', 'c']:
print(i, j)
if j == 'unlucky':
break
else:
continue # Only executed if inner loop didn't break.
break # This is only reached if inner loop 'breaked' out since continue didn't run.
print("Finished")
# 1 a
# 1 b
# Finished
The else: statement is executed when and only when the while loop no longer meets its condition (in your example, when n != 0 is false).
So the output would be this:
5
4
3
2
1
what the...
Suppose you've to search an element x in a single linked list
def search(self, x):
position = 1
p =self.start
while p is not None:
if p.info == x:
print(x, " is at position ", position)
return True
position += 1
p = p.link
else:
print(x, "not found in list")
return False
So if while conditions fails else will execute, hope it helps!
The better use of 'while: else:' construction in Python should be if no loop is executed in 'while' then the 'else' statement is executed. The way it works today doesn't make sense because you can use the code below with the same results...
n = 5
while n != 0:
print n
n -= 1
print "what the..."
As far as I know the main reason for adding else to loops in any language is in cases when the iterator is not on in your control. Imagine the iterator is on a server and you just give it a signal to fetch the next 100 records of data. You want the loop to go on as long as the length of the data received is 100. If it is less, you need it to go one more times and then end it. There are many other situations where you have no control over the last iteration. Having the option to add an else in these cases makes everything much easier.

Categories