elif引发语法错误,但是如果没有

戴维

尝试将“ 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

我收到语法错误。帮助?

马丁·彼得斯(Martijn Pieters)

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...elsestatemement:

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块的一部分

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章