将For循环转换为while循环


s=0
for i in range(3,20,2):
if i>10:
break
else:
s=s+i

print(s)

如何将此代码转换为while循环?

我不知道如何包含这个步骤。

s = 0
i = 3
while i<10:
s+=i
i+=2
print(s)

如果您想在i>10时中断循环,那么为什么要运行到20呢?无论如何,你可以尝试这个

s,i=0,3
while i<=20:
if i>10:
break
else:
s=s+i
i+=2
print(s)

如何将for循环转换为while循环:

s = 0
i = 3
while i < 20:
if i > 10:
break
else:
s = s + i
i += 2
print(s)

当你可以使用rangesum函数时,为什么要重新发明一些东西呢?

>>> sum(range(3,10, 2))
24

最新更新