2017-06-16 78 views
0

我有這樣的代碼:PYTHON我做錯了什麼?循環和if語句

methods = ["SNMP", "SUDP","ESSYN", "SSYN", "HTTP"] 

print("Methods: {}".format(', '.join(methods))) 
method = input("Enter method: ") 
method = method.upper() 

while method != methods: 
    print("ERROR: Method unknown") 
    method = input("Enter method: ") 
    method = method.upper() 

if method in methods: 
    print("Method: {}".format(method)) 

print("" 
     "" 
     "") 

seconds = input("Enter length in seconds: ") 
    print("{} seconds".format(seconds)) 

,你可以看到我試圖從用戶那裏得到的答案則顯示答案,並繼續到下一個任務。但是如果答案不在方法列表中,我希望它再次提出這個問題。但我無法弄清楚如何。我現在使用的代碼給了我錯誤消息「錯誤:方法未知」,當它最終確實說:方法(用這裏的方法)它不會進入下一個任務。任何人都可以告訴我該做什麼或在這段代碼中出了什麼問題?

+0

是你縮進你的代碼完全一樣,因爲它是在這裏嗎? – JoshKopen

+3

'方法!=方法'沒有做你認爲的事情 - 嘗試'方法不在方法中' – asongtoruin

+1

請修復你的縮進,以便清楚實際問題是什麼。 – Carcigenicate

回答

0

怎麼能

while method != methods: 

永遠做有意義嗎?

也許你想:

while method not in methods: 
+0

這將如何解決問題? –

+0

嗯,謝謝我剛開始。它的工作,但我不知道如何與變量做到這一點。 – FluffyMe

+0

@JonClements - 它如何解決這個問題?呃,「立即」? 「儘快」? – Malvolio

1
methods = ["SNMP", "SUDP","ESSYN", "SSYN", "HTTP"] 

print("Methods: {}".format(', '.join(methods))) 
ans = None 
while ans is None: # when ans is set as method or any other value loop will stop asking for methods 
    method = input("Enter method: ") 
    if method.upper() in methods: 
     ans = method # when you set ans it will not ask again 
     print("Method: {}".format(method)) 
     # rest of code here.... even another while loop for your input 
    else: 
     print("ERROR: Method unknown") 
+0

看看鏈接的副本 - 這裏不需要初始值並檢查它 - 正確使用「continue」或「break」更適合。 –