Else Syntax Error Python

后端 未结 6 1918
心在旅途
心在旅途 2020-12-07 06:27
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         


        
相关标签:
6条回答
  • 2020-12-07 06:52

    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.

    0 讨论(0)
  • 2020-12-07 06:59

    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.

    0 讨论(0)
  • 2020-12-07 06:59

    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.)

    0 讨论(0)
  • 2020-12-07 07:08

    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 讨论(0)
  • 2020-12-07 07:14

    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?

    0 讨论(0)
  • 2020-12-07 07:15

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

    0 讨论(0)
提交回复
热议问题