2

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.

asked Mar 17, 2020 at 12:32
1
  • some remarks. continue is not bad practice, but you have to understand how it affects the control flow. for, rather than while is the way to go in Python loops. if, for some reason, within a for loop you not only need the current element, but also its index, use enumerate i.e. for i, char in enumerate(name): Commented Mar 17, 2020 at 15:45

4 Answers 4

2

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)
answered Mar 17, 2020 at 12:37
Sign up to request clarification or add additional context in comments.

2 Comments

as mentioned in my question I know how to do it using for...also something really similar to this is literally a part of my question where I have written that I am not asking about 'this' -implementation.
still I appreciate your answer
2

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")
answered Mar 17, 2020 at 13:06

Comments

0

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
answered Mar 17, 2020 at 12:51

4 Comments

thanks for this new and informative answer, I have just begun leearning to code, and am currently running on 3.7.x, will update and try this
I realized the assignment expression was actually a mistake. It has the side effect that the loop is aborted if any c value is false (doesn't happen for strings, but could for e.g. an array or list).
oh so like a list having True and False values would skip iteration for False values in the list?
It would stop the entire loop. It's a while condition, not a filter condition as in [c for c in name if c].
0
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")
answered May 21, 2020 at 15:25

1 Comment

While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.