关于python:多个elif语句未运行

multiple elif statements not running

本问题已经有最佳答案,请猛点这里访问。

我在做一个骰子游戏,当玩家的角色是一个偶数时,分数会增加10。但是,如果这个数字是奇数,你的分数就会减少5。如果用户角色加倍,则允许掷一个额外的骰子-其他语句适用于3个骰子的总分。我的if语句没有运行。我试图将列表中的数字改为字符串,但不起作用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def Player_1_Roll():
    global Player_1_Score
    Player_1_Score = 0
    Player_1_Roll_1 = random.randint(1, 6)
    print(Player_1_Name,"'s first roll is", Player_1_Roll_1)
    time.sleep(1)
    Player_1_Roll_2 = random.randint(1, 6)
    print(Player_1_Name,"'s second roll is", Player_1_Roll_2)


    Player_1_Score = Player_1_Roll_1 + Player_1_Roll_2

    if Player_1_Score == [2, 4, 6, 8, 10, 12, 14, 16, 18]:
        Player_1_Score = Player_1_Score + 10
        print(Player_1_Name,"'s Score is", Player_1_Score)

    elif Player_1_Score == [1, 3, 5, 7, 9, 11, 13, 15, 17]:
        Player_1_Score = Player_1_Score - 5
        print(Player_1_Name,"'s Score is", Player_1_Score)

    elif Player_1_Score < 0:
        Player_1_Score = 0
        print(Player_1_Name,"'s Score is", Player_1_Score)

    elif Player_1_Roll_1 == Player_1_Roll_2:
        print("")
        print(Player_1_Name,"rolled doubles!")
        print("")
        Player_1_Roll_3 = random.randint(1, 6)
        print(Player_1_Name,"'s bonus roll is", Player_1_Roll_3)
        Player_1_Score = Player_1_Score + Player_1_Roll_3 + Player_1_Roll_1 + Player_1_Roll_2
        print(Player_1_Name,"'s Score is", Player_1_Score)


看来你在找in接线员。现在,您正在尝试验证分数是否与整个列表相同。改为使用:

1
if Player_1_Score in [2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 18]:

正如评论中提到的,这是不有效的。而是使用元组或集合。

1
if Player_1_Score in {2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 18}:

如果你只有一个要求,那就是分数是偶数,你可以使用模运算符。

1
if Player_1_Score % 2 == 0: