有没有可能在elif内部写一个for?我有很多elif语句,我希望我的最后一个elif语句在elif内部有一个for,如何用PYTHON编写嵌套的elif
def victory(see,z):
if see[0]==see[1]==see[2]==z:
print(z,"wins")
elif see[3]==see[4]==see[5]==z:
print(z,"wins")
elif see[6]==see[7]==see[8]==z:
print(z,"wins")
elif see[0]==see[3]==see[6]==z:
print(z,"wins")
elif see[1]==see[4]==see[7]==z:
print(z,"wins")
elif see[2]==see[5]==see[8]==z:
print(z,"wins")
elif see[0]==see[4]==see[8]==z:
print(z,"wins")
elif see[2]==see[4]==see[6]==z:
print(z,"wins")
elif for blank in see if blank=="_" or"__"or"___":
print("game not finished")
发布于 2020-06-19 01:49:34
因为这是您的最后一个elif,所以将其更改为else,并在else块中创建一个for循环。然后您可以在for循环中检查您的条件。
此外,您可以尝试使用switch语句,如代码,而不是大量的if elif else语句
else: [print('game not finished') for blank in see if <condition>]
发布于 2020-06-19 01:51:09
我认为你需要一个列表理解:
elif [blank for blank in see if blank in ["_", “__", “___"] ]:
print("some text")
如果列表理解最终什么都没有,它就被认为是“错误的”,elif将不会被接受。
发布于 2020-06-19 02:06:16
如果要检查列表中的某些值,可以使用in
而不是遍历整个列表:
if see[0]==see[1]==see[2]==z:
print(z,"wins")
elif see[3]==see[4]==see[5]==z:
print(z,"wins")
# ... lots of other elifs here
elif "_" in see or "__" in see or "___" in see:
print("game not finished")
https://stackoverflow.com/questions/62456155
复制相似问题