2016-03-29 9 views
0

Pythonでクラス用の簡単なメニューを作成しようとしていますが、例えば、1〜5などの選択肢を入力すると、次のif文私のコードで "間違った選択、最初から" 私の質問はなぜ私は1つから5までの選択肢を保存する代わりに入力すると、私のコードで "if answer、そしてここにあなたの状態のために収入Pythonメニューコードを次のコード行に移動

def main(): 
    print("\t\t\tMain Menu") 
    print("\t\t\t=========") 
    print ("\n\t\t1- Single") 
    print ("\t\t2- Jointley (Married)") 
    print ("\t\t3- Married Filing Seperatley") 
    print ("\t\t4- Head of HouseHold") 
    print ("\t\t5- Quit") 


    choice = input("\n\n\t\t\tEnter your choice : ").upper()[0] 
    if (choice == '1'): 
     choice = 'S' 
    elif (choice == '2'): 
     choice = 'J' 
    elif (choice == '3'): 
     choice = 'M' 
    elif (choice == '4'): 
     choice = 'H' 
    elif (choice == '5'): 
     choice = 'Q' 
    if (choice != 'S' or choice != 'J' or choice != 'M' or choice != 'H' or choice != 'Q'): 
     print("wrong Choice, Start over") 
    else: 
     income = float (input("Enter your Gross Income from Your W-2 form: ")) 


main() 
input("Press Enter to Continue") 

答えて

1

入力する必要があります私のコードの次の行に移動:

if (choice != 'S' or choice != 'J' or choice != 'M' or choice != 'H' or choice != 'Q'): 

は、あなたは、単に選択肢は、あなたが期待する文字のいずれかでないかどうかを確認するために探しているので、あなたがnot inでこれをやっている必要があります。

if choice not in ('S', 'J', 'M', 'H', 'Q'): 

さらに、あなたはここでやっていることのために:

input("\n\n\t\t\tEnter your choice : ").upper()[0] 

選択肢全体を入力しないでください。ちょうど番号。だから、あなただけの入力を取り、それは数の文字列表現になるため、upperする必要はありません、次のいずれか

input("\n\n\t\t\tEnter your choice : ") 
+0

ありがとう、私の質問に答えました – red

+0

@celotよろしくお願いします。これが助けになった場合は、それを受け入れて、それが有用であり、問​​題を解決したことを示してください。 – idjaw

+0

助けてくれたことを示してくれるのはどういうことですか、ごめんなさい、ありがとうございました – red

0

あなたのコードは、最後のifステートメントに動いている理由は、orではありません。例えば

if (choice != 'S' or choice != 'J' or choice != 'M' or choice != 'H' or choice != 'Q'): 

choice == 'S'がtrueの場合、それもまた真であるので、どんなchoiceあり、その行が真生じないだろうchoice != 'J'を意味します。 andに変更すると問題が解決されます。

if choice != 'S' and choice != 'J' and choice != 'M' and choice != 'H' and choice != 'Q': 

それをテストしないために小さな例:

>> choice = 'S' 

>> print(choice == 'S') 
>> print(choice != 'Q') 
>> print(choice == 'Q') 
>> print(choice != 'S' or choice != 'Q') 

True 
True 
False 
True 

をまた、Pythonであなたのif文に対して括弧のための必要性を、彼らは冗長です。

関連する問題