如何编写内联if语句用于打印?

本文翻译自:How to write inline if statement for print?

I need to print some stuff only when a boolean variable is set to True . 我只需要在布尔变量设置为True时打印一些东西。 So, after looking at this , I tried with a simple example: 所以,看后这个 ,我试图用一个简单的例子:

>>> a = 100
>>> b = True
>>> print a if b
  File "<stdin>", line 1
    print a if b
             ^
SyntaxError: invalid syntax  

Same thing if I write print a if b==True . 如果我写print a if b==True一样的东西。

What am I missing here? 我在这里错过了什么?


#1楼

参考:https://stackoom.com/question/nqdq/如何编写内联if语句用于打印


#2楼

Inline if-else EXPRESSION must always contain else clause, eg: 内联if-else EXPRESSION必须始终包含else子句,例如:

a = 1 if b else 0

If you want to leave your 'a' variable value unchanged - assing old 'a' value (else is still required by syntax demands): 如果你想保持'a'变量值不变 - 确定旧的'a'值(语法要求仍然需要):

a = 1 if b else a

This piece of code leaves a unchanged when b turns to be False. 这段代码留下不变当b变成是假的。


#3楼

You always need an else in an inline if: 如果出现以下情况,您总是需要内联else

a = 1 if b else 0

But an easier way to do it would be a = int(b) . 但更简单的方法是a = int(b)


#4楼

The 'else' statement is mandatory. 'else'语句是强制性的。 You can do stuff like this : 你可以做这样的事情:

>>> b = True
>>> a = 1 if b else None
>>> a
1
>>> b = False
>>> a = 1 if b else None
>>> a
>>> 

EDIT: 编辑:

Or, depending of your needs, you may try: 或者,根据您的需要,您可以尝试:

>>> if b: print(a)

#5楼

For your case this works: 对于您的情况,这适用:

a = b or 0

Edit: How does this work? 编辑:这是如何工作的?

In the question 在问题中

b = True

So evaluating 所以评估

b or 0

results in 结果是

True

which is assigned to a . 分配给a

If b == False? 如果b == False? , b or 0 would evaluate to the second operand 0 which would be assigned to a . b or 0将评估将分配给a的第二个操作数0


#6楼

Python does not have a trailing if statement . Python 没有尾随if 语句

There are two kinds of if in Python: 在Python中有两种if

  1. if statement: if声明:

     if condition: statement if condition: block 
  2. if expression (introduced in Python 2.5) if 表达式 (在Python 2.5中引入)

     expression_if_true if condition else expression_if_false 

And note, that both print a and b = a are statements. 请注意, print ab = a都是语句。 Only the a part is an expression. 只有a部分是表达式。 So if you write 所以,如果你写

print a if b else 0

it means 它的意思是

print (a if b else 0)

and similarly when you write 而且当你写作时也是如此

x = a if b else 0

it means 它的意思是

x = (a if b else 0)

Now what would it print/assign if there was no else clause? 现在,如果没有else条款,它会打印/分配else The print/assignment is still there . 打印/分配仍在那里

And note, that if you don't want it to be there, you can always write the regular if statement on a single line, though it's less readable and there is really no reason to avoid the two-line variant. 请注意,如果您不希望它出现在那里,您总是可以在一行上编写常规if语句,尽管它的可读性较差,并且没有理由避免使用两行变体。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值