0

Hi I just got a confusion in this thing. How do i convert for loop to equivalent while loop? Suppose can anyone give me example by solving this..

for number in range(20,2,-2):
    print("number",number)

will be really appreciated

1

4 Answers 4

2

You can solve this doing loop like this

x = 20
while x >= 4:
    print("number", x)
    x -= 2
Sign up to request clarification or add additional context in comments.

Comments

0

simply, you add count variable.

e.g

for number in range(20,2,-2):
 print(number)
count = 2
while True:
 if(count < 2):
 break
print(number)
count -=2

Comments

0

For your particular example, this is the equivalent using a while loop:

number = 20
while(number > 2):
    print("number",number)
    number -= 2

Comments

0

For a more adaptable sequence, you can use the following code. It uses an iterator to make the loop using a while. You just need to set up the numbers of the sequence.

from_number = 20
to_number = 2
step = -2

print("Loop with for")
for number in range(from_number, to_number, step):
    print("number",number)


print("Loop with while")
iterator = iter(range(from_number, to_number, step))
number = next(iterator)
while number:
    print("number",number)
    try:
        number = next(iterator)
    except StopIteration:
        number = None

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.