简体   繁体   中英

Is there any shorthand if statement in python? (Be specific I didn't mean shorthand if-else statement)

Is there any shorthand for if statements?

print('Bla-Bla-Bla') if true    # like this
print('Bla-Bla-Bla') if true else print('Bla-Bla')    # not this

Use a conditional:

print('Bla-Bla-Bla' if True else 'Bla-Bla')
print('Bla-Bla-Bla' if False else 'Bla-Bla')

Basically, if the statement for the if is True then it will print whatever is in front of it. If not, it will print whatever is after else . If you don't need the else statement, you can do a one-liner (though try avoiding them):

if True: print "true"

This is often to save bytes since more characters (like spaces) means more bytes.

Short answer:

What you want is spelled:

if condition:
    do_something()

IOW, no, what you're asking for doesn't exist.

Long answer

You could write it either as

print("foo") if condition else 1 # or whatever

or

if condition: print("foo")

but both are considered bad style (and even quite WTF'y for the first one) and any pythonista working on your code will immediatly replace it with the proper idiom (cf "short answer") so it doesn't hurt his/her eyes.

Use the conditional to generate the argument to the print function:

print('Bla-Bla-Bla' if True else 'Bla-Bla')
print('Bla-Bla-Bla' if False else 'Bla-Bla')

prints:

Bla-Bla-Bla
Bla-Bla
bar > foo and x or y

where bar > foo is an expression/condition
and works when the condition is True (positive value)
or when False (negative value).

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