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

时间:2017-08-04 12:30:32

标签: python python-3.x

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

4 个答案:

答案 0 :(得分:1)

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.

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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.

答案 3 :(得分:0)

bar > foo and x or y

其中bar > foo是表达式/条件
当条件为“真”(正值)时,and有效
or为False(负值)时。