Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why "return 100 if i < 10 else pass" is not valid in python?

All;

def foo(i):
    return 100 if i < 10 else pass
    return 200 if i < 20 else pass
    return 1

Why this not works in python? I suppose this code may works same as:

def foo(i):
    if i < 10:
        return 100
    elif i < 20:
        return 200
    else: 
        return 1

Thanks!

like image 570
user478514 Avatar asked Nov 08 '10 09:11

user478514


Video Answer


3 Answers

In the documentation you will see that the "ternary operator" should be like this:

conditional_expression ::=  or_test ["if" or_test "else" expression]
expression             ::=  conditional_expression | lambda_expr

and pass is a statement not an expression

like image 147
mouad Avatar answered Nov 10 '22 07:11

mouad


return 100 if i < 10 else pass

you should read it as return (100 if i < 10 else pass) so pass isn't a value

like image 26
Abyx Avatar answered Nov 10 '22 08:11

Abyx


read your code like this:

return (100 if (i < 10) else pass)

pass is not a value you can return. The following code would work:

def foo(i):  
    return 100 if i < 10 else (200 if i < 20 else 1) 
like image 45
Florianx Avatar answered Nov 10 '22 07:11

Florianx