提问人:Ricky Robinson 提问时间:8/9/2012 最后编辑:Karl KnechtelRicky Robinson 更新时间:4/4/2023 访问量:1284552
如何写内联 if 语句进行打印?
How to write inline if statement for print?
问:
只有当布尔变量设置为 时,我才需要打印一些东西。所以,看完这个,我试着举了一个简单的例子:True
>>> a = 100
>>> b = True
>>> print a if b
File "<stdin>", line 1
print a if b
^
SyntaxError: invalid syntax
如果我写同样的事情.print a if b==True
我在这里错过了什么?
答:
内联 if-else EXPRESSION 必须始终包含 else 子句,例如:
a = 1 if b else 0
如果你想保持你的'a'变量值不变 - 评估旧的'a'值(否则语法要求仍然需要):
a = 1 if b else a
当 b 变为 False 时,这段代码使 a 保持不变。
评论
print a if b
else a
那就更好了else 0
if b: print a
在这种情况下,只需要一个简单的 if
""
None
如果出现以下情况,则始终需要内联:else
a = 1 if b else 0
但更简单的方法是.a = int(b)
评论
a = int(bool(b))
“else”语句是强制性的。你可以做这样的事情:
>>> b = True
>>> a = 1 if b else None
>>> a
1
>>> b = False
>>> a = 1 if b else None
>>> a
>>>
编辑:
或者,根据您的需要,您可以尝试:
>>> if b: print(a)
对于您的情况,这有效:
a = b or 0
编辑:这是如何工作的?
在问题中
b = True
所以评估
b or 0
结果
True
分配给 。a
如果 ,将计算结果为将分配给 的第二个操作数。b == False?
b or 0
0
a
评论
Python 没有尾随语句。if
Python 中有两种:if
if
陈述:if condition: statement if condition: block
if
表达式(在 Python 2.5 中引入)expression_if_true if condition else expression_if_false
请注意,两者都是语句。只有零件是表达式。所以如果你写print a
b = a
a
print a if b else 0
这意味着
print (a if b else 0)
同样,当你写
x = a if b else 0
这意味着
x = (a if b else 0)
现在,如果没有子句,它会打印/分配什么?打印/作业仍然存在。else
请注意,如果你不希望它在那里,你总是可以把常规语句写在一行上,尽管它的可读性较差,而且真的没有理由避免两行变体。if
评论
if condition: statement
print [i for i in range(10) if i%2]
?我希望他们能在理解之外允许它......if
for
a=b
试试这个。它可能会对您有所帮助
a=100
b=True
if b:
print a
好吧,你为什么不简单地写:
if b:
print a
else:
print 'b is false'
如果您不想这样做,可以执行以下操作:from __future__ import print_function
a = 100
b = True
print a if b else "", # Note the comma!
print "see no new line"
其中打印:
100 see no new line
如果您不喜欢或正在使用 python 3 或更高版本:from __future__ import print_function
from __future__ import print_function
a = False
b = 100
print(b if a else "", end = "")
添加 else 是使代码语法正确所需的唯一更改,您需要 else 作为条件表达式(“in line if else blocks”)
我没有使用或像线程中的其他人一样使用的原因是因为使用会导致程序或在这种情况下。None
0
None/0
print None
print 0
b
False
如果您想阅读有关此主题的信息,我提供了指向此功能已添加到 Python 的补丁的发行说明的链接。
上面的“模式”与 PEP 308 中显示的模式非常相似:
这种语法可能看起来很奇怪和倒退;为什么会出现这种情况 在表达式的中间,而不是像 C 的 c 那样在前面?x : 是吗?通过将新语法应用于 标准库中的模块,并查看生成的代码如何 读。在许多情况下,使用条件表达式,一个值 似乎是“常见情况”,一个值是“特殊情况”, 仅在不满足条件的极少数情况下使用。这 条件语法使这种模式更加明显:
contents = ((doc + '\n') if doc else '')
所以我认为总的来说,这是一种合理的应用方式,但你不能反驳以下简单性:
if logging: print data
评论
print ""
end
print
from __future__ import print_function
你只是过于复杂了。
if b:
print a
评论
if DEBUG: print something
您可以使用:
print (1==2 and "only if condition true" or "in case condition is false")
同样,您可以继续这样做:
print (1==2 and "aa" or ((2==3) and "bb" or "cc"))
真实世界的例子:
>>> print ("%d item%s found." % (count, (count!=1 and 's' or '')))
1 item found.
>>> count = 2
>>> print ("%d item%s found." % (count, (count!=1 and 's' or '')))
2 items found.
从 2.5 开始,您可以使用等效的 C 的 “?:” 三元条件运算符,语法为:
[on_true] if [expression] else [on_false]
所以你的例子很好,但你必须简单地添加,比如:else
print a if b else ''
评论
print ''
这可以通过字符串格式来完成。它适用于 % 表示法以及 .format() 和 f 字符串(3.6 的新功能)
print '%s' % (a if b else "")
或
print '{}'.format(a if b else "")
或
print(f'{a if b else ""}')
评论
print a if b else ""
print "",
print("", end="")
嗯,你可以用列表推导来做到这一点。只有当你有一个真实的范围时,这才有意义。但它确实可以完成这项工作:
print([a for i in range(0,1) if b])
或者只使用这两个变量:
print([a for a in range(a,a+1) if b])
您可以编写一个内联三元运算符,如下所示:
sure = True
# inline operator
is_true = 'yes' if sure else 'no'
# print the outcome
print(is_true)
print a if b
File "<stdin>", line 1
print a if b
^
SyntaxError: invalid syntax
Answer
If your statement must print an empty line when the expression is false, the correct syntax is:print
print(a if b else '')
The reason is you're using the conditional expression which has two mandatory clauses, one when is true preceding , one when is false following .b
if
b
else
Both clauses are themselves expressions. The conditional expression is also called the ternary operator, making it clear it operates on three elements, a condition and two expressions. In your code the part is missing.else
However I guess your idea was not to print an empty line when the expression was false, but to do nothing. In that case you have to use within a conditional statement, in order to condition its execution to the result of the evaluation of .print
b
Details: Expression vs. statement
The conditional statement can be used without the part:else
The statement is a compound statement with further instructions to execute depending on the result of the condition evaluation.
if
It is not required to have an clause where the appropriate additional instructions are provided. Without it, when the condition is false no further instructions are executed after the test.
else
The conditional expression is an expression. Any expression must be convertible to a final value, regardless of the subsequent use of this value by subsequent statements (here the statement).
print
Python makes no assumption about what should be the value of the expression when the condition is false.
You could have used an statement this way:if
if b: print(a)
Note the difference:
There is no instructions executed by the statement when the condition is false, nothing is printed because is not called.
if
print
In a statement with a conditional expression , is always executed. What it prints is the conditional expression. This expression is evaluated prior to executing the statement. So outputs an empty line when the condition is false.
print
print(a if b else '')
print
if
print
print
Note your other attempt is just equivalent to the first one.print(a if b==True)
Since is syntactically equivalent to , I guess Python interpreter just replaces the former by the latter before execution. Your second attempt likely comes down to a repeat of the first one.b==True
b
评论
lambda
void