2016-06-15 89 views
-1

作爲學校項目的一部分,我們正在創建故障排除程序。我遇到了一個我無法解決的問題:測試列表中的項目 - Python 3

begin=['physical','Physical','Software','software',] 
answer=input() 
if answer in begin[2:3]: 
    print("k") 
    software() 
if answer in begin[0:1]: 
    print("hmm") 
    physical() 

當我嘗試輸入軟件/軟件時,沒有輸出被創建。任何人都可以在我的代碼中看到一個洞,因爲它是?

+1

我看到很多洞,你的輸入是什麼?提供樣本輸入和預期輸出。看看什麼是[mcve]。 –

+0

當我嘗試輸入軟件/軟件 –

+0

也輸入分配給答案 –

回答

3

在Python中,切片結束值爲獨佔。你是切片比你認爲你是一個小清單:

>>> begin=['physical','Physical','Software','software',] 
>>> begin[2:3] 
['Software'] 
>>> begin[0:1] 
['physical'] 

使用begin[2:4]begin[0:2]甚至begin[2:]begin[:2]獲得從3日到結尾的所有元素,並從一開始,直到2日(含):

>>> begin[2:] 
['Software', 'software'] 
>>> begin[2:4] 
['Software', 'software'] 
>>> begin[:2] 
['physical', 'Physical'] 
>>> begin[0:2] 
['physical', 'Physical'] 
更好

然而,使用str.lower()來限制你需要提供的輸入數量:

if answer.lower() == 'software': 

只有一個字符串需要測試,現在可以將你的函數放入字典中;這可讓您選擇列出各種有效回答過:

options = {'software': software, 'physical': physical} 

while True: 
    answer = input('Please enter one of the following options: {}\n'.format(
     ', '.join(options)) 
    answer = answer.lower() 
    if answer in options: 
     options[answer]() 
     break 
    else: 
     print("Sorry, {} is not a valid option, try again".format(answer)) 
0

你的列表切片是錯誤,請嘗試以下腳本。

begin=['physical','Physical','Software','software',] 
answer=input() 
if answer in begin[2:4]: 
    print("k") 
    software() 
if answer in begin[0:2]: 
    print("hmm") 
    physical()