简体   繁体   中英

Python if statement syntax error problems

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?

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]

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM