2014-03-19 29 views
1

我正在編寫一個簡單的控制檯程序來幫助我自己和一些地質學家進行岩石樣本分析。我們的講師爲我們提供了一個流程圖,有助於指定樣本的特徵。我正在試圖把它變成一個控制檯程序。如果在Python中有兩個條件的語句

我的問題是第9行的if語句是否有可能採用兩個條件,如果有,我是否正確寫入?

def igneous_rock(self): 
    print "Welcome to IgneousFlowChart" 
    print "Assuming you are looking at an igneous rock, please choose the " 
    print "option which best describes the sample:" 
    print "1. Coherent 2. Clastic" 

    choice1 = raw_input("> ") 

    if choice1 = '1', 'Coherent': # this is the line in question! 
     return 'coherent' 
    elif choice1 = '2', 'Clastic': 
     return 'clastic' 
    else: 
     print "That is not an option, sorry." 
     return 'igneous_rock' 

在此先感謝:-)

+0

你可能從來沒有多於或少於一個條件創造set秒。 –

+0

'如果choice1 ='1'',如果沒有別的,則使用賦值運算符('=')而不是等價運算符('==')。你可以用'if choice1 =='1'或choice1 =='Coherent''鏈接它們,或者像其他優秀答案一樣使用'in'。 –

+0

你的代碼hs是錯誤的語法,比較你應該使用'=='運算符,'='是一個分配 –

回答

4

您可以構建其if條件應該求Truthy元素的列表,然後用in運營商這樣的,以檢查是否choice1的價值在元素列表中,這樣

if choice1 in ['1', 'Coherent']: 
... 
elif choice1 in ['2', 'Clastic']: 
... 

取而代之的列表,你可以使用元組以及

if choice1 in ('1', 'Coherent'): 
... 
elif choice1 in ('2', 'Clastic'): 
... 

如果要檢查的項目清單是巨大的,那麼你就可以建立一套這樣的

if choice1 in {'1', 'Coherent'}: 
... 
elif choice1 in {'2', 'Clastic'}: 
... 

set的報價速度比查找列表或元組。您可以在`if`或`while`語句set literal syntax {}

+1

爲什麼列表而不是元組? –

+0

不要花括號創建字典嗎?我想你使用Set([..])創建一個集合? –

+1

@BenEchols:用逗號分隔的項目序列中的花括號創建一個集合。 – user2357112

2
if choice1 in ('1', 'Coherent'):