Python if,else语句

时间:2013-10-20 06:06:29

标签: python if-statement

我已经开始自己学习python以获得乐趣,而我正在写这篇并没有得到我想要的结果:

if no1234 == 0:
     print "Player and Computer tie!\n"
elif no1234 == 1 or 2:
     print "Player wins!\n"
elif no1234 == 3 or 4:
     print "Computer wins!\n"

计算机胜利不会出现,是否有遗忘

2 个答案:

答案 0 :(得分:5)

elif no1234 == 1 or 2:被解析为elif (no1234 == 1) or (2):

始终为True,因为bool(2) == True并且您正在使用or声明。

你可能想要:

elif no1234 == 1 or no1234 == 2:

甚至:

elif no1234 in (1, 2):

对于您的其他elif,这是相同的。


总而言之:

if no1234 == 0:
     print "Player and Computer tie!\n"
elif no1234 in (1, 2):
     print "Player wins!\n"
elif no1234 in (3, 4):
     print "Computer wins!\n"

答案 1 :(得分:3)

你需要这个:

if no1234 == 0:
     print "Player and Computer tie!\n"
elif no1234 == 1 or no1234 == 2:
     print "Player wins!\n"
elif no1234 == 3 or no1234 == 4:
     print "Computer wins!\n"