Transform For loop into while loop
Question:
s=0
for i in range(3,20,2):
if i>10:
break
else:
s=s+i
print(s)
how can i transform this code into a while loop?
I don’t know how to include the step.
Answers:
s = 0
i = 3
while i<10:
s+=i
i+=2
print(s)
If you want to break the loop when i>10, then why you’re running the loop till 20? Any way you can try this
s,i=0,3
while i<=20:
if i>10:
break
else:
s=s+i
i+=2
print(s)
Here’s how you can transform the for loop into a while loop:
s = 0
i = 3
while i < 20:
if i > 10:
break
else:
s = s + i
i += 2
print(s)
Why reinvent something when you could do this using a range
and the sum
functions:
>>> sum(range(3,10, 2))
24
s=0
for i in range(3,20,2):
if i>10:
break
else:
s=s+i
print(s)
how can i transform this code into a while loop?
I don’t know how to include the step.
s = 0
i = 3
while i<10:
s+=i
i+=2
print(s)
If you want to break the loop when i>10, then why you’re running the loop till 20? Any way you can try this
s,i=0,3
while i<=20:
if i>10:
break
else:
s=s+i
i+=2
print(s)
Here’s how you can transform the for loop into a while loop:
s = 0
i = 3
while i < 20:
if i > 10:
break
else:
s = s + i
i += 2
print(s)
Why reinvent something when you could do this using a range
and the sum
functions:
>>> sum(range(3,10, 2))
24