其他语法错误Python

use*_*549 -1 python if-statement

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 :("
Run Code Online (Sandbox Code Playgroud)

我一直在else语句中遇到语法错误,我不确定为什么它会一直产生这个错误.我在同一个def中没有任何其他语句,但仍然会出错.我该怎么办?

pra*_*nsg 8

在Python中,else语句不带条件:

if condition:
   do_1()
else:
   do_else()
Run Code Online (Sandbox Code Playgroud)

在您的情况下,因为您想要评估另一个条件,在之后if,使用elif:

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

注意:阅读文档.


小智 5

你的log_f.write语句也缺少一个尾随')',这可能会使解析器混乱......并且缩进看起来不正确.剪切和粘贴问题?