2016-09-23 3 views
0

"if"를 "elif"로 변경하려고하면 오류가 발생합니다. 이 코드는 if를 사용할 때 완벽하게 작동하지만 대신 "elif"를 사용하려고하면 구문 오류가 발생합니다. if 문 중 하나만 실행하기를 원하기 때문에 "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 

을하지만 2 또는 3 "의 경우"을 "의 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 문에 중요하지 않습니다; unentented print() 문은 if 블록 사이에서 실행됩니다.

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 블록의 일부가 자신의 들여 쓰기를 수정 :

당신은 그 print() 기능을 이동해야합니다

if...elif...else statemement 후 를 실행합니다.

+0

감사합니다! 나는 당신의 권고에 따라 그것을 고쳤으며, 이제는 완벽하게 작동합니다! – Davy

관련 문제