How continue works in while loop

name = 'Jesaa29 Roy'
size = len(name)
i = 0
while i < size:
    if name[i].isspace():
        continue 
    print(name[i], end=' ')
    i = i + 1

#it’s supposed to print name without space “Jessa29Roy”, but the output is blank

Pease use code formatting.

What will happen if you reach space? Counter is not advanced so it will loop endlessly.

First step of getting information about continue could be interactive interpreter built-in help:

>>> help('continue')
The "continue" statement
************************

   continue_stmt ::= "continue"

"continue" may only occur syntactically nested in a "for" or "while"
loop, but not nested in a function or class definition within that
loop.  It continues with the next cycle of the nearest enclosing loop.

When "continue" passes control out of a "try" statement with a
"finally" clause, that "finally" clause is executed before really
starting the next loop cycle.

Related help topics: while, for
4 Likes

Yes, iterating using index easily leads to errors. Fortunately in Python we have much better means of iteration. One of the possibilities to explore after fixing the original program:

name = 'Jesaa29 Roy'
for character in name:
    ...                               # What code should be inside the loop?

While not directly related to the question’s title, it’s worth mentioning that if your goal is to remove spaces from a string, you don’t need to use a loop:

>>> name = "Jesaa29 Roy"
>>> name = name.replace(" ", "")
>>> print(name)
Jesaa29Roy
3 Likes

There is also string method .isspace which could be used:

>>> name = "Jesaa29 Roy"
>>> ''.join(char for char in name if not char.isspace())
'Jesaa29Roy'

That’s what OP is already using. And still a loop, even if it’s only on one line :wink:

No doubt about it this is loop and OP already used it.

However, .replace and .isspace snippets do very different things. It can be demonstrated by following:

>>> text = """This
... is
... several
... rows
... """
>>> text
'This\nis\nseveral\nrows\n'
>>> print(text)
This
is
several
rows

>>> print(text.replace(" ", ""))
This
is
several
rows

>>> ''.join(char for char in text if not char.isspace())
'Thisisseveralrows'

Which kind of behavior is desired in this case is up to debate :smiley:

1 Like

To try and directly answer your question:

If your code is:

name = 'Jesaa29 Roy'
size = len(name)
i = 0
while i < size:
    if name[i].isspace():
        continue
    print(name[i], end='')
    i = i + 1

… (which I’m unsure about, because you didn’t post formatted code), then i will never get past a value of 7, therefore you’ll have an infinite loop. So, you’ll need to increment i in the if branch:

name = 'Jesaa29 Roy'
size = len(name)
i = 0
while i < size:
    if name[i].isspace():
        i = i + 1
        continue
    print(name[i], end='')
    i = i + 1

Output: Jesaa29Roy

You can (and maybe should) use i += 1 instead of i = i + 1

3 Likes

I’m just posting because nobody has answered your original question,
though Rob’s example code hints at it.

The continue statement causes execution to jump to the next loop
iteration i.e. to the top of the loop, where the condition is tested.

The problem with your code:

 name = 'Jesaa29 Roy'
 size = len(name)
 i = 0
 while i < size:
     if name[i].isspace():
         continue
     print(name[i], end=' ')
     i = i + 1

is that when your if-statement fires because name[i].isspace() is
true, control jumps back to the top of the loop. Importantly, the
i=i+1 does not run, and so i never changes, so name[i] stays on
the same isspace() chararacter… forver.

Rob’s code put an i=i+1 in the if-statement “true” branch before the
continue to solve this issue.

The core thing to fix is that the increment has to always happen.

There are three variations on this with the code you’ve got:

  • Rob’s extra i=i+1 statement inside the if-statement
  • just use the if-statement to skip the print() instead of using a
    continue
  • use a different loop construct such as a for-loop

The second approach looks like this:

 while i < size:
     if not name[i].isspace():
         print(name[i], end=' ')
     i = i + 1

See how (a) the print() only happens for the characters you want and
(b) the i=i+1 always happens? No continue here.

The third approach is usually done with a for-loop, which will always
advance to the next character. The direct translation of your code looks
like this:

 for i in range(size):
     if not name[i].isspace():
         print(name[i], end=' ')

or:

 for i in range(size):
     if name[i].isspace():
         continue
     print(name[i], end=' ')

In both cases, because i is advanced by the for-loop itself, there’s
no opportunity to fail to i=i+1, and there’s no overt i=i+1
statement. The range(size) function produces values from 0 up to
size-1, thus counting the value of i the way you want.

You could also iterate over the string directly:

 for name_i in name:
     if not name_i.isspace():
         print(name_i, end=' ')

Which puts the strings 'J', 'e', 's' etc into name_i on each
iteration. The variable name name_i was chosen purely to match up with
the previous name[i] expression, and could as well be a better name
like character.

Cheers,
Cameron Simpson cs@cskk.id.au

7 Likes

Your explanation is much better than YouTube vids :sparkles:-
Please keep helping me in future

Yes the explanations by Cameron are great!

To strongly defend the first reply by Aivar:
He was directing you to the problem in your code to find it out by yourself. In the learning process it is usually much better if you figure it our by yourself.

2 Likes

I’m grateful to all those why reply my questions, they all help me in solving my problem and understanding basics :sparkles:

1 Like