Python While循环,也使用模和继续命令

时间:2019-05-26 06:04:36

标签: python while-loop modulo continue

尝试完成要求我执行的任务:

“编写一个while循环,该循环计算1到20(包括20)之间的整数之和,不包括那些被3整除的整数。(提示:您会发现模运算符(%)和continue语句对于这个。)

我尝试自己构造代码,但是对代码的评估超时。我猜我的语法不正确,并导致无限循环

    total, x = 0, 1
    while x >=1 and x <= 20:
        if x%3==0:
            continue
        if x%3 != 0:
            print(x)
            x+=1
            total+=1
    print(total)

期望的答案应该是:

20 19 17 16 14 13 11 10 8 7 5 4 2 1

但我只是收到“超时”错误

***最新::

尝试过:

total, x = 0, 1
while x>=1 and x<=20:
    if x%3 == 0:
        x+=1
        continue
    if x%3 != 0:
       print(x)
       x+=1
       total=+1
print(total)

收到此信息::

Traceback (most recent call last):
   File "/usr/src/app/test_methods.py", line 23, in test
    self.assertEqual(self._output(), "147\n")
AssertionError:     '1\n2\n4\n5\n7\n8\n10\n11\n13\n14\n16\n17\n19\n20\n1\n' != '147\n'

-1 -2 -4 -5 -7 -8 -10 -11 -13 -14 + 147 ? + -16 -17 -19 -20 -1

2 个答案:

答案 0 :(得分:5)

您没有在第一个x语句中递增if,因此它停留在该值并永远循环。你可以试试看。

total, x = 0, 1
while x >=1 and x <= 20:
    if x%3==0:
        x+=1  # incrementing x here
        continue
    elif x%3 != 0:  # using an else statement here would be recommended
        print(x)
        x+=1
        total+=x  # we are summing up all x's here
print(total)

或者,您可以在if语句外增加x。您也可以使用range()。在这里,我们只是忽略了x可被3整除的total, x = 0, 1 for x in range(1, 21): if x%3 != 0: print(x) x+=1 total+=x print(total)

m = df['X1'].shift().eq(df['X1'])
df['Y'] = np.where(m, df['X2'].shift().add(1), 0).astype(int)
print (df)
   X1  X2  Y
0   1   1  0
1   1   2  2
2   1   3  3
3   2   2  0
4   2   2  3
5   1   2  0

答案 1 :(得分:0)

尝试一下

>>> lst = []
>>> while x >=1 and x <= 20:
    if x%3==0:
        x+=1  # this line solve your issue
        continue
    elif x%3 != 0:   # Use elif instead of if
        lst.append(x) # As your expected output is in reverse order, store in list
        x+=1
        total+=1

一个衬里:(另一种方式)

>>> [x for x in range(20,1,-1) if x%3 != 0]
[20, 19, 17, 16, 14, 13, 11, 10, 8, 7, 5, 4, 2]

输出:

>>> lst[::-1] # reverse it here
[20, 19, 17, 16, 14, 13, 11, 10, 8, 7, 5, 4, 2, 1]