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

标签 python while-loop modulo continue

试图完成要求我完成的任务:

“编写一个 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)

预期的答案应该是:

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

最佳答案

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

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()。在这里,我们只是忽略可被 3 整除的 x

total, x = 0, 1
for x in range(1, 21):
    if x%3 != 0:
        print(x)
        x+=1
        total+=x
print(total)

关于Python While 循环,也使用取模和继续命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56311077/

相关文章:

python - Pandas 和 groupby 计算两个不同列中的匹配项数

python - 编辑 pickle 数据

javascript - Node.js 文件系统 - 保存唯一的文件名

带 if 条件的 SQL 插入

iOS objective-C : using modulo on a float to get "inches" from Feet

python - 使用 Pyramid 事件和多线程

python - 将 pygames 事件数据发送到扭曲服务器?

c++ - cin.fail while循环输入再入

Python:语句中使用的循环变量未更新

java - Java 中的文件年龄