尝试将“ if”更改为“ elif”时出现错误。当我使用if时,代码可以完美地工作,但是如果我尝试使用“ elif”,则会引发语法错误。我需要使用“ elif”,因为我只希望其中一个if语句运行,而不是两个都运行。这段代码可以正常工作:
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
但是,如果我将第二个或第三个“ if”更改为“ 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
我收到语法错误。帮助?
elif
不是单独的声明。elif
是现有if
语句的选项部分。
因此,您只能在一个块之后elif
直接使用if
:
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
块之间执行。
你将需要转移这些print()
要运行的功能后的if...elif...else
statemement:
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)
或将其缩进固定为if
和elif
块的一部分。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句