2016-11-27 12 views
0
while True: 
    num=raw_input("Please enter a number.") 
    if (num == 1): 
     print "Sunday" 
    elif (num==2): 
     print "Monday" 
    elif (num==3): 
     print "Tuesday" 
    elif (num==4): 
     print "Wednesday" 
    elif (num==5): 
     print "Thursday" 
    elif (num==6): 
     print "Friday" 
    elif (num==7): 
     print "Saturday" 
    else: 
     print "Invalid Choice!" 

    option = raw_input("Would you like to continue playing?") 
    if (option=="yes"): 
     continue 
    elif (option=="no"): 
     break 

このマイコード。何らかの理由でそれを実行すると、最初の部分(曜日)の出力が「無効な選択」である「else」オプションとして表示されます。そしてelse文を削除したところ、出力は空白になりました。なぜこれが起こっているのか、少し混乱しています。Pythonプログラミングブランク出力

+0

インデントを修正しました。 –

答えて

5

raw_inputは、strとして入力を返します。 ifステートメントの条件として使用する場合は、intに変換する必要があります。

num=int(raw_input("Please enter a number.")) 

ユーザーが数字を入力しないと、エラーが発生することに注意してください。

+0

Pythonを使って入力を検証するには、次のことを見てください:[有効な応答が得られるまで入力を求める](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they -give-a-valid-response) –

1

プログラムを作成する際に、「無効な選択」に情報を追加することをおすすめします。反応。たとえば:

print("You entered `{entry}` ({entry_type}), which is an invalid choice!".format(entry=num, entry_type=type(num))) 

が無効な選択である、あなたは(<クラスのstr 'は>)3` `入っあなた

を言っただろう!

これは、文字列と比較するか、入力を整数にキャストする必要があるかもしれないことを示唆している可能性があります。