我不明白代码是如何得到 56、49
I don’t understand how the code is getting 56, 49
num = 0
even = 0
odd = 0
for num in range(0, 15):
if (num /2 == int(num /2)):
even += num
else:
odd += num
print("even:",even,"odd:",odd,"num:",num)
我对如何得到结果感到困惑,有人可以为我分解一下吗?
此程序正在将 0-14 之间的所有奇数和偶数相加。
这就是 for 循环背后的内容:
num=0, if-statement (true), even=0+0=0
num=1, else-statement (true), odd=0+1=0;
num=2, if-statement (true), even=0+2=2
num=3, else-statement (true), odd=1+3=4;
num=4, if-statement (true), even=2+4=6
num=5, else-statement (true), odd=4+5=9;
num=6, if-statement (true), even=6+6=12
num=7, else-statement (true), odd=9+7=16;
num=8, if-statement (true), even=12+8=20
num=9, else-statement (true), odd=16+9=25;
num=10, if-statement (true), even=20+10=30
num=11, else-statement (true), odd=25+11=36;
num=12, if-statement (true), even=30+12=42
num=13, else-statement (true), odd=36+13=49;
num=14, if-statement (true), even=42+14=56
num = 0
even = 0
odd = 0
for num in range(0, 15):
if (num /2 == int(num /2)):
even += num
else:
odd += num
print("even:",even,"odd:",odd,"num:",num)
我对如何得到结果感到困惑,有人可以为我分解一下吗?
此程序正在将 0-14 之间的所有奇数和偶数相加。 这就是 for 循环背后的内容:
num=0, if-statement (true), even=0+0=0
num=1, else-statement (true), odd=0+1=0;
num=2, if-statement (true), even=0+2=2
num=3, else-statement (true), odd=1+3=4;
num=4, if-statement (true), even=2+4=6
num=5, else-statement (true), odd=4+5=9;
num=6, if-statement (true), even=6+6=12
num=7, else-statement (true), odd=9+7=16;
num=8, if-statement (true), even=12+8=20
num=9, else-statement (true), odd=16+9=25;
num=10, if-statement (true), even=20+10=30
num=11, else-statement (true), odd=25+11=36;
num=12, if-statement (true), even=30+12=42
num=13, else-statement (true), odd=36+13=49;
num=14, if-statement (true), even=42+14=56