[英]Python statement of short 'if-else'
C++ 中是否有以下if
- else
语句或类似语句的 Python 版本:
int t = 0;
int m = t==0?100:5;
您所指的构造称为三元运算符。 Python 有一个版本(从 2.5 版开始),如下所示:
x if a > b else y
t = 0
if t == 0:
m = 100
else:
m = 5
美丽总比丑陋好。
显式优于隐式。
简单胜于复杂。
来自PEP 20 。
或者,如果你真的,真的必须(在 Python >= 2.5 中工作):
t = 0
m = 100 if t == 0 else 5
还有:
m = t==0 and 100 or 5
由于 0 是一个假值,我们可以这样写:
m = t and 5 or 100
这相当于第一个。
我发现关键字传入中的第一个速记很方便。 下面的示例显示它在 tkinter 网格几何管理器中使用。
class Application(Frame):
def rcExpansion(self, rows, cols, r_sticky, c_sticky):
for r in range(rows):
self.rowconfigure(r, weight=r)
b = Button(self, text = f"Row {r}", bg=next(self.colors))
b.grid(row=r, column= 0, sticky = N+S+E+W if r_sticky == True else None)
for c in range(cols):
self.columnconfigure(c, weight=c)
b = Button(self, text = f"Column {c}", bg=next(self.colors))
b.grid(row=rows, column = c, sticky = N+S+E+W if c_sticky == True else None)
app = Application(root=Tk())
app.rcExpansion(3, 4, True, False)
用于打印语句
a = input()
b = input()
print(a) if a > b else print(b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.