2016-09-23 5 views
0

"if"を "elif"に変更しようとするとエラーが発生します。私がifを使用しているときにコードは完全に機能しますが、代わりに "elif"を使用しようとすると構文エラーが発生します。私はif文の1つだけを実行したいので、 "elif"を使う必要があります。このコードは正常に動作します:elifは構文エラーを発生させますが、そうでない場合

guess_row=0 
guess_col=0 
ship_location=0 
number_of_attempts=3 

guess_location = input("Guess :").split(",") 
guess_row,guess_col = int(guess_location[0]),int(guess_location[1]) 
if guess_row not in range(1,6): 
    print("Out of range1.") 
print(guess_location) 
print(ship_location)   
if guess_col not in range(1,6): 
    print("Out of range2.") 
print(guess_location) 
print(ship_location) 
if ship_location == guess_location: 
    print("You sunk my battleship! You win!") 
else: 
    print ("You missed!") 
    print ("You have " + str(number_of_attempts-1) + " attempt(s) left!") 
    print ("Try again!") 
    number_of_attempts-=1 

しかし、私は「elifの」を「場合」第二または第三を変更した場合:

guess_row=0 
guess_col=0 
ship_location=0 
number_of_attempts=3 

guess_location = input("Guess :").split(",") 
guess_row,guess_col = int(guess_location[0]),int(guess_location[1]) 
if guess_row not in range(1,6): 
    print("Out of range1.") 
print(guess_location) 
print(ship_location)   
elif guess_col not in range(1,6): 
    print("Out of range2.") 
print(guess_location) 
print(ship_location) 
elif ship_location == guess_location: 
    print("You sunk my battleship! You win!") 
else: 
    print ("You missed!") 
    print ("You have " + str(number_of_attempts-1) + " attempt(s) left!") 
    print ("Try again!") 
    number_of_attempts-=1 

私は、構文エラーが発生します。助けて?

+0

あなたは 'if/elif/else'スコープを終了しましたprintステートメント – MikeTheLiar

答えて

4

elifは別個のステートメントではありません。 elifは、既存のifステートメントのオプション部分です。

そのように、あなただけのifブロックの後elif直接を使用することができます:あなたのコードで

if sometest: 
    indented lines 
    forming a block 
elif anothertest: 
    another block 

、しかし、elifはない直接すでにif文の一部をブロックに従っありません。あなたは、もはやそれらがifブロックレベルにインデントされていないので、もはやブロックの一部である間の行を持っている:

if guess_row not in range(1,6): 
    print("Out of range1.") # part of the block 
print(guess_location)  # NOT part of the block, so the block ended 
print(ship_location)   
elif guess_col not in range(1,6): 

これは別々if文には関係ありません。ブロックされていないprint()ステートメントは、ブロックifの間で実行されます。

あなたはif...elif...else statemement実行されるように、これらのprint()機能を移動する必要があります:

if guess_row not in range(1,6): 
    print("Out of range1.") 
elif guess_col not in range(1,6): 
    print("Out of range2.") 
elif ship_location == guess_location: 
    print("You sunk my battleship! You win!") 
else: 
    print ("You missed!") 
    print ("You have " + str(number_of_attempts-1) + " attempt(s) left!") 
    print ("Try again!") 
    number_of_attempts-=1 

print(guess_location) 
print(ship_location)   

またはifelifブロックの一部であることを彼らのインデントを修正します。

+0

ありがとう!私はあなたの推薦に従ってそれを修正し、今は完全に動作します! – Davy

関連する問題