为什么将所有值都附加到列表winning_numbers?

时间:2018-08-20 23:28:10

标签: python python-3.x if-statement jupyter-notebook

我正在使用Python 3.6在Jupyter Notebook中工作。我不明白为什么所有的值都被附加到winning_numbers而不是应有的lost_numbers。

我的代码:

import numpy as np

winning_numbers = []
losing_numbers = []

limit = 11

for x in range(1, limit):

    if x%2 == 0:

        if x-1 or x/2 in losing_numbers:
            winning_numbers.append(x)

        elif x-1 and x/2 in winning_numbers:
            losing_numbers.append(x)

    if x%2 == 1:

        if x-1 == 0:
            winning_numbers.append(x)

        elif x-1 or (x-1)/2 in losing_numbers:
            winning_numbers.append(x)

        elif x-1 and (x-1)/2 in winning_numbers:
            losing_numbers.append(x)

print("Winning Numbers: ", winning_numbers)
print("Losing Numbers: ", losing_numbers)

我的输出是:

Winning Numbers:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Losing Numbers:  []

输出应为:

Winning Numbers: [1, 3, 4, 5, 7, 9]
Losing Numbers: [2, 6, 8, 10]

1 个答案:

答案 0 :(得分:0)

问题在于您在or语句中组织if的方式:

if x-1 or x/2 in losing_numbers:

这意味着:

if (x-1) or (x/2 in losing_numbers):

由于对于x的所有整数值(除1之外,x-1truthy),该值始终为true,并且x将附加到{{1} }。

您应该将其重写为:

winning_numbers

或:

if x-1 in losing_numbers or x/2 in losing_numbers: