-2
votes
if len(user_hash) > 0:
  with open(log_file, "w") as log_f:
    for name in user_hash:
        log_f.write("Name:%s \n Email: %s" % (name, email)

    else len(user_hash) < 0:
       print "Nothing happened :("

I keep getting a syntax error on the else statement and I am unsure why it keeps producing this error. I don't have any other else statements in the same def and it still gives error. What do I do?

6
You need to indent the code. - Linuxios
Please read the formatting help to get an understanding of how to format code in your posts. Don't insert all those <br> tags. - BrenBarn

6 Answers

7
votes

Your log_f.write statement is also missing a trailing ')', which is likely confusing the parser...and the indentation doesn't look right. Cut and paste problem?

8
votes

In Python, the else statement takes no conditions:

if condition:
   do_1()
else:
   do_else()

In your case, since you want to evaluate another condition, after the if, use an elif:

if condition1:
    do_1()
elif condition2:
    do_2()
... # you can have as many elifs as you want
else:
    do_else()

Note: Read the docs.

1
votes

You can't do else like that in Python. You should do (assuming your tabs are correct in real life):

elif len(user_hash) < 0:

and as mentioned, you're missing a close paren.

1
votes

You can't supply a condition with an else statement. else means "everything else" --- that is, everything else but whatever conditions you specified in an earlier if. It's not clear what you're trying to accomplish with that else, but perhaps you mean it to be an if.

It could also be an elif ("else if"), but if you mean it to be an else for the earlier if clause, then you need to unindent it so it's at the same indentation level as the if. An if and it's else/elif have to line up at the same indentation level.

(There is such a thing as an else clause for a for statement, but it doesn't look like that's what you want here.)

1
votes

You can do else with for loops in Python, but you'll need to balance your parentheses on:

log_f.write("Name:%s \n Email: %s" % (name, email)

which should actually be

log_f.write("Name:%s \n Email: %s" % (name, email))

(Note the extra final parenthesis.)

0
votes

if and else must be in the same column align, this work for me.