鍍金池/ 問答/Python  Linux/ 關(guān)于Python中判斷語句的使用

關(guān)于Python中判斷語句的使用

我寫了一個方法,如下:

file = None
for f in os.listdir(os.getcwd()):
    if os.path.splitext(f)[1] == '.*' and os.path.splitext(f)[0] == os.getenv('') or 'text':
        file = f
return file

期望是,如果文件不存在,返回None,實際返回了__pycache__。

我修改了方法,如下:

file = None
for f in os.listdir(os.getcwd()):
    if os.path.splitext(f)[1] == '.*':
        if os.path.splitext(f)[0] == os.getenv('') or 'text':
            file = f
return file

這樣就能返回期望值None。

請問是為什么?

回答
編輯回答
心夠野

and 優(yōu)先級高于 or

你的第一個方法稍作修改,

file = None
for f in os.listdir(os.getcwd()):
    if os.path.splitext(f)[1] == '.*' and (os.path.splitext(f)[0] == os.getenv('') or 'text'):
        file = f
return file

應(yīng)該就符合你的預(yù)期了.

2018年3月28日 20:17