Home > database >  Transform For loop into while loop
Transform For loop into while loop

Time:12-04

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.

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

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

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