我只是在研究Python 3,以及他的代码中的一些%
,请参见下文:
def main():
maxwidth = 100 # limita o numero de caracteres numa célula
print_start() # chama a função print_start
count = 0 # cria uma variavel cont
while True:
try:
line = input()
if count == 0:
color = "lightgreen"
elif count % 2:
color = "white"
else:
color = "lightyellow"
print_line(line, color, maxwidth)
count += 1
except EOFError:
break
print_end() # chama a função print_end
这elif count % 2:
行是什么意思?
这
称为模或模运算符。
它将"左"值除以"右"值并返回余数(偶数除法后剩余的金额)。
它通常用于解决每 N 次迭代或循环执行一次操作的问题。如果我想每 100 次循环打印一条消息,我可以这样做:
for i in xrange(10000):
if i % 100 == 0:
print "{} iterations passed!".format(i)
我会看到:
0 iterations passed!
100 iterations passed!
200 iterations passed!
300 iterations passed!
400 iterations passed!
500 iterations passed!
...
在代码中,if count % 2
将作用于每隔一次迭代:1、3、5、7、9。如果count
为 0、2、4、6 或 8,则count % 2
将返回 0,表达式将为 False
。
这是一个模运算。将其除以 2,如果您的余数为零,则它是一个偶数。它在编程中经常使用,对于任何程序员来说都是必须知道的。