Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python not implement the elif statement on try statement?

So let's make a quick example.

my_list = [
    {"name": "toto", "value": 3},
    {"name": "foo", "value": 42},
    {"name": "bar", "value": 56}
]

def foo(name):
    try:
        value = next(e["value"] for e in my_list if e["name"] == name)
    except StopIteration:
        print "Uuuh not found."
    else:
        if value % 2:
            print "Odd !"
        else:
            print "Even !"

As you can see, the above code works :

>>> foo("toto")
Odd !
>>> foo("foo")
Even !
>>> foo("kappa")
Uuuh not found.

I was just wondering if there is a particular reason about why we can't use the elif statement with the try statement like this :

try:
    value = next(e["value"] for e in my_list if e["name"] == name)
except StopIteration:
    print "Uuuh not found."
elif value % 2:
    print "Odd !"
else:
    print "Even !"

Of course, this would not work because as it is defined in the try statement documentation, the elif statement is not defined. But why ? Is there a particular reason (like bound / unbound variable) ? Is there any sources about this ?

(Side note: no elif-statement tag ?)

like image 259
FunkySayu Avatar asked Aug 20 '15 10:08

FunkySayu


People also ask

Why Elif is not working in Python?

But when running if... elif...else statements in your code, you might get an error named SyntaxError: invalid syntax in Python. It mainly occurs when there is a wrong indentation in the code. This tutorial will teach you to fix SyntaxError: invalid syntax in Python.

Why is my else statement not working in Python?

The keyword else needs to be followed by a colon : . Any code that is included as part of the else statement must be indented the same amount. Since a=5 assigns a value to a that is less than 10, a>10 is False and the code under the if statement does not run.

Can we use else with try in Python?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error.

Why is Elif invalid syntax in Python?

In Python code in a file, there can't be any other code between the if and the else . You'll see SyntaxError: invalid syntax if you try to write an else statement on its own, or put extra code between the if and the else in a Python file.

Why can't I type Elif or else in Python?

The problem is the blank line you are typing before the else or elif. Pay attention to the prompt you're given. If it is >>>, then Python is expecting the start of a new statement. If it is ..., then it's expecting you to continue a previous statement.

Why does Python expect a new statement to start before Elif?

The problem is the blank line you are typing before the else or elif. Pay attention to the prompt you're given. If it is >>>, then Python is expecting the start of a new statement.

What is a try-except statement in Python?

Try-except statements are another selection structure in Python. Like if, elif and else statements, a try-except statements select a particular block of code to run based on a condition. Unlike if, elif and else clauses, try-except blocks are not based on logical conditions.

What is the difference between if elif Elif and else?

Like if, elif and else statements, a try-except statements select a particular block of code to run based on a condition. Unlike if, elif and else clauses, try-except blocks are not based on logical conditions. Try-except blocks are based upon whether a line or section of code returns an error.


1 Answers

If you are asking why then that is a question for the python devs, the syntax is clearly defined in the docs you linked to.

Apart from that what you are trying to do can obviously all be done inside the try/except. If you use an else it belongs to the try the same as when you use an else with a for loop, I think it makes perfect sense to only use else and not allow elif, elif's are there to behave like switch/case statements in other languages.

From an old thread on gossamer-threads Why no 'elif' in try/except? :

Because it makes no sense?

The except clauses are for handling exceptions, the else clause is for handling the case when everything worked fine.

Mixing the two makes no sense. In an except clause, there is no result to test; in an else clause, there is. Is the elif supposed to execute when there are exceptions, or when there aren't? If it's simply an extension to the else clause, then I suppose it doesn't harm anything, but it adds complexity to the language definition. At this point in my life, I tend to agree with Einstein - make everything as simple as possible, but no simpler. The last place (or at least one of the many last places) I want additional complexity is in exception handling.

You always need at least one if to use an elif, it is simply invalid syntax without. The only thing that could end up not being defined is value, you should move the logic inside the try/except using if/else:

try:
    value = next(e["value"] for e in my_list if e["name"] == name)
    if value % 2:
        print("Odd !")
    else:
        print("Even !")
except StopIteration:
    print("Uuuh not found.")

If value = next... errors your print("Uuuh not found.") will be executed, if not your then your if/else will.

You can have multiple elif's but you must start with an if:

if something:
  ...
elif something_else:
   ....
elif .....

Another option is to use a default value with next then use if/elif/else, if we get no name matched next will return None so we check if value is not None, if it is we print "Uuuh not found." or else we got a matched name so we go to the elif/else :

value = next((e["value"] for e in my_list if e["name"] == name), None)
if value is None:
    print("Uuuh not found.")
elif value % 2:
    print("Odd !")
else:
    print("Even !")
like image 127
Padraic Cunningham Avatar answered Sep 28 '22 17:09

Padraic Cunningham