2012-11-29 50 views
1

這是我在Python中的第二個程序。我似乎對我的進步感到滿意。問題是我試圖做的是:如何檢查用戶輸入是否有這些行?

choice=eg.ynbox(msg='wat to do') 
for["true","1"] in choice: 
     print("yes") 
for["false","0"] in choice: 
     print("no") 

問題是,這對於條件不起作用。我在查看前一個問題的答案時看到過這樣的代碼,但我忘記了。我試着用搜索引擎,但我不知道如何把這個words..A小語法幫助是必要的 BTW:它與easygui 0.96 GUI程序..

+2

我不明白你想要的代碼做什麼。 –

+0

其實它是一個幫助我的朋友的測試程序。我只是想確保這部分代碼在他的程序中起作用。因爲他正在做一個gui程序並被卡住了,所以我學會了easygui的基本知識,並幫助他,在那裏我被困在這個部分:P- @ KarlKnechtel –

+0

如果你不告訴任何人,你想怎麼做?關於** choice **可能需要的值?我們並不都知道** easygui ** – eyquem

回答

0

我假設eg.ynbox(msg='wat to do')你的意思是你正在創建一個是/否對話框。這意味着存儲在choice值是一個Integer其中表示和表示。這是雙方的Python 2.x和Python 3.x都有只要尚未在Python 2.x中被重新分配TrueFalse被保留在Python 3.x的關鍵字,從而保證正確的不要改變。因此,你只需有一個工程,並使用此值的if聲明:

if choice: 
    print 'Yes' 
else: 
    print 'No' 

你並不需要匹配10因爲它們代表了兩種TrueFalse

+0

ya但新版本的Python表示Yes和N o正確和錯誤。如果發生這種情況,我的程序不會工作。 –

+0

我不明白你爲什麼要在多個版本的Python上運行?當然你運行一個版本的Python,你不會繼續在2.x和3.x之間切換? – BeRecursive

+0

是的,但我的朋友正在創建的程序是準備運行在任何蟒蛇版本 我的電腦是Windows和python 3.x,但我的朋友是python 2.x ubuntu..so我需要此代碼工作在兩個版本... 除了列表不是這些2.正如我前面提到的,這是一個測試程序... –

1
choice = eg.ynbox(msg='wat to do') 
if any(word in choice for word in ["true","1"]): 
    print('yes') 
elif any(word in choice for word in ["false","0"]): 
    print('no') 
else: 
    print('invalid input') 

,或者,如果列表很短:

choice = eg.ynbox(msg='wat to do') 
if 'true' in choice or '1' in choice:: 
    print('yes') 
if 'false' in choice or '0' in choice:: 
    print('no') 
else: 
    print('invalid input') 
+0

我試過這段代碼,但是它在遊戲中是這樣的: Traceback(最近呼叫的最後一個): 文件「E:\ misc \ 1.py」,行7, 如果有的話(單詞在[「true」,「1」]中的單詞): 文件「E:\ misc \ 1.py」,第7行, 如果有for word in [「true」,「1」]): TypeError:int類型的參數不可迭代 @eumiro –

0

你可以嘗試下面的代碼來代替你的:

def is_accept(word): 
    return word.lower() in {'true', '1', 'yes', 'accept'} 

def is_cancel(word): 
    return word.lower() in {'false', '0', 'no', 'cancel'} 

def get_choice(prompt=''): 
    while True: 
     choice = eg.ynbox(msg=prompt) 
     if is_accept(choice): 
      print('Yes') 
      return True 
     if is_cancel(choice): 
      print('No') 
      return False 
     print('I did not understand your choice.') 
相關問題