简体   繁体   中英

Python 3 if-else short-hand command syntax error

Python 3 is showing syntax error whenever I write sys.exit() if condition else return .

Why is this a syntax error? If it can't be fixed is there any way to do the same operation in one line?

return is a statement keyword that can't be used in an x if y else z expression .

Due to sys.exit() never actually returning (since it internally raises a SystemExit exception) and None being the implicit return value if you do return , you could do

return sys.exit() if condition else None

but that's hard to understand and you shouldn't strive to do things in one line for the sake of doing them in one line.

if condition:
    sys.exit()
return

is that much more readable.

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