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.

Asked By: maria carolina

||

Answers:

s = 0
i = 3
while i<10:
    s+=i
    i+=2
print(s)
Answered By: islam abdelmoumen

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)
Answered By: Vimal Vambaravelli

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)
Answered By: Ruslan

Why reinvent something when you could do this using a range and the sum functions:

>>> sum(range(3,10, 2))
24
Answered By: Jab
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.