Python elif会引发语法错误,但如果没有,则会引发语法错误
当我尝试将“if”更改为“elif”时,会出现一个错误。当我使用if时,代码可以完美地工作,但如果我尝试使用“elif”,则会引发语法错误。我需要使用“elif”,因为我只想运行一个if语句,而不是两个。此代码工作正常:Python elif会引发语法错误,但如果没有,则会引发语法错误,python,python-3.x,if-statement,Python,Python 3.x,If Statement,当我尝试将“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_
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”:
我得到一个语法错误。帮助?
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
块之间执行
您需要将那些print()
函数移动到if…elif…else
语句之后运行:
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
块的一部分。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
块之间执行
您需要将那些print()
函数移动到if…elif…else
语句之后运行:
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
块的一部分。您的打印语句结束if/elif/else
范围您的打印语句结束if/elif/else
范围谢谢!我按照你的建议修复了它,现在它工作得很好!非常感谢。我按照你的建议修复了它,现在它工作得很好!