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 l
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.
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.
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.)
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.)
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?
if and else must be in the same column align, this work for me.