如何写内联 if 语句进行打印?

How to write inline if statement for print?

提问人:Ricky Robinson 提问时间:8/9/2012 最后编辑:Karl KnechtelRicky Robinson 更新时间:4/4/2023 访问量:1284552

问:

只有当布尔变量设置为 时,我才需要打印一些东西。所以,看完这个,我试着举了一个简单的例子: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

我在这里错过了什么?

python if-statement 内联 条件语句

评论

1赞 kenorb 5/3/2015
Python 是否有三元条件运算符的可能副本?
7赞 mins 8/8/2018
好问题,复杂的答案......一个直接的将是“其他部分是强制性的”。
0赞 Ginger 3/13/2021
需要注意的一点是,if 表达式在 中起作用,但在单行语句中不起作用lambda
0赞 Karl Knechtel 9/28/2022
@mins接受的答案对我来说似乎很简单。对于如此重要的问题,顶级答案应包括此类信息。
0赞 Karl Knechtel 9/28/2022
...这是说同一件事的两种方式,问题中的方式可以更好地证明要求的合理性。表达式必须计算为一个值(即“等于”是没有意义的)的原因是因为“表达式”正是那些可以分配其结果的东西。void

答:

139赞 Rostyslav Dzinko 8/9/2012 #1

内联 if-else EXPRESSION 必须始终包含 else 子句,例如:

a = 1 if b else 0

如果你想保持你的'a'变量值不变 - 评估旧的'a'值(否则语法要求仍然需要):

a = 1 if b else a

当 b 变为 False 时,这段代码使 a 保持不变。

评论

1赞 Ricky Robinson 8/9/2012
哦。但是,如果我不希望在 else 分支中发生任何事情怎么办?我需要以下内容:print a if b
2赞 aneroid 8/9/2012
else a那就更好了else 0
20赞 jamylak 8/9/2012
if b: print a在这种情况下,只需要一个简单的 if
4赞 Jan Hudec 8/9/2012
修复答案,因为如果不是因为“声明”这个词让它变得非常糟糕,它几乎是好的。问题的要点是它不是一个声明。
1赞 sancho.s ReinstateMonicaCellio 1/10/2014
+1-1:可以指出 else 表达式是强制性的,但不能为所讨论的情况提供答案:打印“nothing”(类似于 or 的内容,请参阅其他答案中的详细信息)。""None
3赞 Daniel Roseman 8/9/2012 #2

如果出现以下情况,则始终需要内联:else

a = 1 if b else 0

但更简单的方法是.a = int(b)

评论

4赞 Jan Hudec 8/9/2012
-1:更容易。而且完全不可读。反正不是提问者想要的。
0赞 glglgl 8/22/2013
ITYM的。a = int(bool(b))
35赞 Alexis Huet 8/9/2012 #3

“else”语句是强制性的。你可以做这样的事情:

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

编辑:

或者,根据您的需要,您可以尝试:

>>> if b: print(a)
6赞 user647772 8/9/2012 #4

对于您的情况,这有效:

a = b or 0

编辑:这是如何工作的?

在问题中

b = True

所以评估

b or 0

结果

True

分配给 。a

如果 ,将计算结果为将分配给 的第二个操作数。b == False?b or 00a

评论

3赞 Jan Hudec 8/9/2012
这个表达式的丑陋和容易出错是我们首先有条件表达式的原因。
1067赞 Jan Hudec 8/9/2012 #5

Python 没有尾随语句if

Python 中有两种:if

  1. if陈述:

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

    expression_if_true if condition else expression_if_false
    

请注意,两者都是语句。只有零件是表达式。所以如果你写print ab = aa

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

评论

1赞 Val 11/8/2013
我认为这在多行语句的情况下不起作用。if condition: statement
3赞 mbomb007 9/27/2015
@JanHudec 如果 Python 没有尾随,那么为什么这样做: print [i for i in range(10) if i%2]?我希望他们能在理解之外允许它......if
4赞 Jan Hudec 9/29/2015
@mbomb007,这也不是尾随 if 语句。它只是列表(或生成器)理解的一部分。请注意,if 前面的东西不是语句,而是两个介于两者之间的表达式。for
2赞 Jan Hudec 12/16/2016
@AlexandervonWernherr,是的,这听起来很合理。
1赞 CodeMantle 2/13/2019
@KaranSingh,在Python中,“不是表达式”是一种有用的语法工具,并且是从其他语言(C)中学习的,在这些语言中,赋值和测试可以混合在一起。a=b
6赞 SkariaArun 8/9/2012 #6

试试这个。它可能会对您有所帮助

a=100
b=True

if b:
   print a
-2赞 IcyFlame 2/26/2013 #7

好吧,你为什么不简单地写:

if b:
    print a
else:
    print 'b is false'
24赞 Noelkd 5/2/2013 #8

如果您不想这样做,可以执行以下操作: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”)

我没有使用或像线程中的其他人一样使用的原因是因为使用会导致程序或在这种情况下。None0None/0print Noneprint 0bFalse

如果您想阅读有关此主题的信息,我提供了指向此功能已添加到 Python 的补丁的发行说明的链接

上面的“模式”与 PEP 308 中显示的模式非常相似:

这种语法可能看起来很奇怪和倒退;为什么会出现这种情况 在表达式的中间,而不是像 C 的 c 那样在前面?x : 是吗?通过将新语法应用于 标准库中的模块,并查看生成的代码如何 读。在许多情况下,使用条件表达式,一个值 似乎是“常见情况”,一个值是“特殊情况”, 仅在不满足条件的极少数情况下使用。这 条件语法使这种模式更加明显:

contents = ((doc + '\n') if doc else '')

所以我认为总的来说,这是一种合理的应用方式,但你不能反驳以下简单性:

if logging: print data

评论

0赞 Ricky Robinson 6/2/2013
谢谢。这里的问题是,它仍然会打印一些东西:一个空行。print ""
0赞 Ricky Robinson 6/2/2013
谢谢。中的 argumnt 只出现在 Python 3.x 中,对吧?endprint
1赞 Noelkd 6/2/2013
是的,我更像是一个 2.7 岁的人,因此from __future__ import print_function
6赞 Nande 6/1/2013 #9

你只是过于复杂了。

if b:
   print a

评论

1赞 Ricky Robinson 6/2/2013
当然,这是最简单的选择。我想当时(2012 年 8 月)我想做一些类似的事情:if DEBUG: print something
0赞 sancho.s ReinstateMonicaCellio 1/10/2014
重复的答案?请参阅 SkariaArun 的那句话,以及评论。
14赞 Eduardo 3/20/2014 #10

您可以使用:

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.
13赞 kenorb 5/3/2015 #11

从 2.5 开始,您可以使用等效的 C 的 “?:” 三元条件运算符,语法为:

[on_true] if [expression] else [on_false]

所以你的例子很好,但你必须简单地添加,比如:else

print a if b else ''

评论

2赞 yoniLavi 3/10/2016
请注意,will 仍然会打印一个换行符,Noelkd 在答案中避免了这一点。print ''
15赞 Eric Ed Lohmar 2/24/2017 #12

这可以通过字符串格式来完成。它适用于 % 表示法以及 .format() 和 f 字符串(3.6 的新功能)

print '%s' % (a if b else "")

print '{}'.format(a if b else "")

print(f'{a if b else ""}')

评论

0赞 melpomene 2/24/2017
这与格式无关;你可以做.这正是 Noelkd 的答案。print a if b else ""
0赞 m3nda 5/30/2017
@melpomene但打印 “” 广告一个新行,可以避免对 Python2 使用 (colon),对 Python3 使用 (colon)。print "",print("", end="")
2赞 George Mogilevsky 9/13/2018 #13

嗯,你可以用列表推导来做到这一点。只有当你有一个真实的范围时,这才有意义。但它确实可以完成这项工作:

print([a for i in range(0,1) if b])

或者只使用这两个变量:

print([a for a in range(a,a+1) if b])
19赞 Mussa Charles 5/5/2021 #14

您可以编写一个内联三元运算符,如下所示:

sure = True

# inline operator
is_true = 'yes' if sure else 'no'

# print the outcome
print(is_true)
6赞 mins 9/28/2022 #15
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 .bifbelse

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 .printb


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.ifprint

  • 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.printprint(a if b else '')printifprintprint


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==Trueb