user12212977
user12212977

Reputation: 1

How can I run a while loop inside a for loop

I'm new to Python3. The code below is just for easy illustration of this question. I'm wondering is there anyway I can run a while loop inside a for loop. It seems whenever the while loop return false it will end everything.

x = 0
for i in range (2):
    while x < 2:
        print ('I')
        x +=1

The outcome I want is to iterate the while loop twice so that it should print 'I' 4 times.

Thank you

Upvotes: 0

Views: 1419

Answers (3)

John
John

Reputation: 21

We can also reset x at the beginning of the loop:

for i in range(2):
    x = 0
    while x < 2:
        print('I')
        x += 1

Upvotes: 1

John
John

Reputation: 21

To do this, we can use the same range function that we used for i.

for i in range(2):
    for x in range(2):
        print('I')

Upvotes: 1

curusarn
curusarn

Reputation: 403

Like this:

for i in range (2):
    x = 0  
    while x < 2:
        print ('I')
        x +=1

You need to reset x right before the while loop because otherwise, x will stay equal to 2 after the first iteration of the for loop and the while loop will exit instantly because 2 < 2 == False.

Upvotes: 2

Related Questions