Python中%的意义是什么[关闭]

2024-03-01

我对编程语言和 Python 都是全新的。

尽管我已经阅读了 3 个简短的教程来解释它,但我仍然无法理解 % 的意义。

有人能分解一下 % 在这段代码中到底做了什么吗?

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print n, "=", x, "*", n/x

对于数字,它返回除法的余数(正如 squiguy 指出的那样)。

10 / 3 等于 3 余数为 1。

So 10 % 3 == 1.


It's most common use is to check for divisibility. For example, in that loop it checks if n is divisible by x. For example it can be use to do something every nth time.

for i in range(1, 10):
   if i % 3 == 0:
       print "I love cats and dogs"
   else:
       print "I love cats"

Outputs,

I love cats
I love cats
I love cats and dogs
I love cats
I love cats
I love cats and dogs
I love cats
I love cats
I love cats and dogs
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python中%的意义是什么[关闭] 的相关文章

随机推荐