0

I don't get some syntax for if statements in python:

>> z=[0 if all([2<3,6<7]) else sth]    #Correct
>>
>> z=[0 if all([2<3,6<7])]             #Wrong
  File "<stdin>", line 1
    z=[0 if all([2<3,6<7])]
                          ^
SyntaxError: invalid syntax
>>

I don't know this syntax and difference between Correct line and Wrong line?

1
  • 3
    To clarify, suppose that the all condition was false. What value would you want assigned to z? Commented Jan 20, 2015 at 6:33

3 Answers 3

4

You're using the A if condition else B syntax in the correct one, which returns an expression to be assigned to your z variable

In the wrong one you're omitting the else clause, so Python can't guess what to put in case your condition all([2<3,6<7]) is not met, which isn't workable so it's not allowed

if you only want to set a value in that case then:

if <condition>:
   z = [0]

or if you like one-liners: if <condition>: z = [0]

Sign up to request clarification or add additional context in comments.

Comments

2

You cannot skip else while using this syntax. See: http://en.wikipedia.org/wiki/%3F:#Python

Comments

1

List comprehensions doesn't work that way, you thought it like;

def sm():
    if somethingelse:
        return something
    return something1

Probably? In this case we dont have to write else because if if statement works, function is done by return something. But in list comprehensions it's not like that. As you know you don't have to write else in lambda too because lambda is a function too, like the example above.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.