[英]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.