Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
683 views
in Technique[技术] by (71.8m points)

if statement - Else Syntax Error Python

if len(user_hash) > 0:
  with open(log_file, "w") as log_f:
    for name in user_hash:
        log_f.write("Name:%s 
 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...