Search code examples
pythonmanim

lambda with condition x: 1/x if x!= 0 not work


I want to draw an inverse proportional function with GraphScene, everything works, However when I set condition of x != 0, a SyntaxError pops:

f11 = self.get_graph(lambda x: 1/x if x!= 0)

SyntaxError: invalid syntax 

the error indicates the last parenthesis

I searched a lot, the lambda x: 1/x if x!= 0 should be a correct python syntax, don't know why it not work! thanks for any help.


Solution

  • Add an else telling what the lambda should evaluate to when x==0, and suddenly you have valid syntax:

    lambda x: 1/x if x != 0 else 0
    

    This syntax construct was added in PEP-308, which was adopted in Python 2.5. From the PEP, the grammar changes are described as follows:

    test: or_test ['if' or_test 'else' test] | lambdef
    or_test: and_test ('or' and_test)*
    ...
    testlist_safe: or_test [(',' or_test)+ [',']]
    ...
    gen_for: 'for' exprlist 'in' or_test [gen_iter]
    

    As you can see, else is mandatory; there's no way to have a test without both an if and an else.