Using continue in loops


#1

usernames = [‘maclover’, ‘linuxjane’, ‘windowseightforever’, ‘osagnostic’]

if len(item)>10:
print “Too long”
continue
else:
for i in usernames:
print “Welcome”
print i

The error says:
File “python”, line 5
SyntaxError: ‘continue’ not properly in loop

I am trying to skip if a string has a length more than 10 in the list.I can’t figure out where i’m doing wrong.
Could you help me?


#2

trying to skip what? When the if condition is true, the else clause won’t execute. I don’t see the problem? continue is when you want a loop iteration to do nothing


#3

The key here is in the error you’re getting from Python:

SyntaxError: ‘continue’ not properly in loop

In your code, you have the continue statement on line 5, but your loop doesn’t start until two lines afterwards on line 7. Remember that an if-else statement is for conditional flow, which is different to a loop like for.

Your code overall looks OK to me, it’s just not quite in the right order for it to do what you want. It would only take a little change to get that code to run how you want it to run. :slight_smile:


#4

I wanted the string length to be less than 10.
I made it like this and it works now. Thank you for your help, i understood the continue now :slight_smile:

usernames = [‘maclover’, ‘linuxjane’, ‘windowseightforever’, ‘osagnostic’]

for i in usernames :

if len(i)>10:
    print("Too long!")
    continue
else:
    print("Welcome")
    print(i)

#5

I’m glad you got your code working.

As a side note: in your particular case I don’t believe you need the continue statement, because your if-else statement will produce your intended result on its own.

If your for loop contained more code after your if-else, which you didn’t want to run if i was longer than 10 characters, then you might need to use the continue statement but for the code you’ve posted here I think you could get away without it. :slight_smile:


#6

yes exactly, continue is useful when nothing has to be done. But in this case a message is already being printed that the users username is too long, so continue can be omitted


#7

Always good to know I’m not telling people the wrong thing! :slight_smile:


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.