2017-03-02 37 views
2

我在if語句中有很長的一組表達式。但顯然我不允許分裂我的if語句,即使我沒有爲顯而易見的python原因將縮進分塊。我是一個Python新手,所以我很抱歉,如果我的問題很煩人。if block的可讀性

理想情況下,我想有if聲明安排是這樣的:

if (expression1 and expression2) or 
(
expression2 and 
(
(expression3 and expression4) or 
(expression3 and expression5) or 
(
expression4 and (expression6 or expression7) 
) 
): 
    pass 

現在這一切都在同一行並沒有很多的可讀性。

+2

您_could_包裹在括號整個事情,但有很多表情似乎有點像一個代碼味道給我的。 –

+0

試開關箱; ref:http://stackoverflow.com/questions/11479816/what-is-the-python-equivalent-for-a-case-switch-statement – CSK

+0

嘗試完全改變它。使它成爲一個局部變量或幾個局部變量,爲您檢查的每個條件提供一個名稱。然後你可以分解它,並使其更短,同時更具可讀性。 – dsh

回答

1

Python有幾種方法可以允許多行語句。你的情況,你可以簡單的包裝你的整個if條件括號:

if ((expression1 and expression2) or 
(
expression2 and 
(
(expression3 and expression4) or 
(expression3 and expression5) or 
(
expression4 and (expression6 or expression7) 
) 
)): 
    pass 

我必須留意,在一個單一的if聲明有很多條件似乎有點像一個代碼味道給我的。也許可以考慮創建幫助函數來封裝某些邏輯,或者使用多個語句。

3

你可以使用舊式backslashing的第一線,別人並不需要它,因爲你使用括號:

if (expression1 and expression2) or \ 
(
expression2 and 
(
(expression3 and expression4) or 
(expression3 and expression5) or 
(
expression4 and (expression6 or expression7) 
) 
) 
): 
    pass 

請注意,例如必須是固定的,因爲有一個右括號失蹤。

1

使用\擁有多條線路上你的表情,你甚至可以IDENT它更易讀:

if (expression1 and expression2) or \ 
(expression2 and \ 
    (\ 
    (expression3 and expression4) or \ 
    (expression3 and expression5) or \ 
     (\ 
     expression4 and (expression6 or expression7) \ 
     )\ 
     ): 
    pass 
+3

這是因爲OP留下語法錯誤(省略了一個右括號)只是爲了誤導我們。 –

+0

你的權利,我的壞@LoicM。我會刪除我的評論。 –

0

你可以這樣做:

t1_2=(expression1 and expression2) 
t3_4=(expression3 and expression4) 
t3_5=(expression3 and expression5) 
t6_7=(expression6 or expression7) 
if test1 or(expression2 and (t3_4 or t3_5 or(expression4 and t6_7)): 
    pass