在Python中将for循环转换为while循环

在Python中将for循环转换为while循环,python,loops,for-loop,while-loop,sum,Python,Loops,For Loop,While Loop,Sum,在准备考试时,我被困在将“for”转换为“While”语句的过程中 a= int(input('type to calculate the sum of multiples')) total =0 for i in range(1,101,1): if i %a==0: total= total+i else: continue print('the sum of multiple numbers from 1 to ', a, 'is', to

在准备考试时,我被困在将“for”转换为“While”语句的过程中

a= int(input('type to calculate the sum of multiples'))

total =0
for i in range(1,101,1):
    if i %a==0:
        total= total+i
    else:
        continue
print('the sum of multiple numbers from 1 to ', a, 'is', total)


a= int(input('type to calculate the sum of multiples'))

ntotal =0
i=1
while i<101: 
    if i %a==0:
        ntotal = ntotal + i
    else:
        continue
print('the sum of multiple numbers from 1 to ', a, 'is', total)
a=int(输入('type以计算倍数之和'))
总数=0
对于范围(1101,1)内的i:
如果i%a==0:
总计=总计+i
其他:
持续
打印('从1到',a'是',总计的多个数字之和)
a=int(输入(‘输入以计算倍数之和’)
ntotal=0
i=1

而i所有循环都是在一个数字的重复增量上工作,或者通过一个列表(元素集合)进行迭代

在while循环中,如果
i%a
等于或不等于
0
,则
i
的值保持不变。无论如何,
i
保持不变,即使
ntotal
增加。因此,循环的条件始终保持为
1<101
,即
True

要纠正这一点,您应该将步长值增量添加到
i
,如下所示:

while i<101: 
    if i %a==0:
        ntotal = ntotal + i
    else:
        pass
    i = i + 1
您甚至不必使用
continue
,因为在else条件之后,循环的控制将返回到
循环的条件(它将重复)。如果您想在
if-else
之后添加一些其他代码,但在循环中,我就把它放在那里了

此外,正如评论中指出的,没有必要使用
else
子句,因为其中没有任何操作。因此,您的代码可以如下所示:

while i<101: 
    if i %a==0:
        ntotal = ntotal + i

    i = i + 1

while if
语句的缩进。将
i+=1
添加到while循环中,否则我将永远等于1。为什么需要
否则:继续
<代码>继续
仅当您希望在不执行正文其余部分的情况下重新启动循环时才需要,但没有正文的其余部分。如果
i%a
等于0,它也保持不变。那项测试与此无关。如果
else:
子句只包含
pass
,那么在
if
else
中重复
i+=1
并不能使它变得更好,这是没有用的…@Thierrylahuille我知道,但我认为保留OP对if-else的使用将有助于他更好(或更快)地理解。我还建议删除原始代码中的
else
子句,因为它们没有任何用途,只会让阅读变得更困难。@Thierrylahuille已考虑在内-现在编辑!
while i<101: 
    if i %a==0:
        ntotal = ntotal + i

    i = i + 1