小编Cha*_*ins的帖子

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

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

“编写一个while循环,该循环计算1到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)
Run Code Online (Sandbox Code Playgroud)

预期的答案应该是:

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)
Run Code Online (Sandbox Code Playgroud)

收到此::

Traceback (most recent call last):
   File "/usr/src/app/test_methods.py", line 23, in test
    self.assertEqual(self._output(), …
Run Code Online (Sandbox Code Playgroud)

python continue modulo while-loop

1
推荐指数
1
解决办法
149
查看次数

标签 统计

continue ×1

modulo ×1

python ×1

while-loop ×1