111k views
0 votes
Python - Please help!

Convert the following while loop to its corresponding for loop :

i= 1
while i*i<n:
print(2* i + 1)
i += 1
else:
print('Hakuna Matata')​

User Rico Chan
by
5.1k points

1 Answer

4 votes

Answer:

i= 1

for i in range(1,n):

if i * i < n:

print(2* i + 1)

i += 1

else:

print('Hakuna Matata')

Step-by-step explanation:

First, there's a need to rewrite the code segment in your question (because of indentation)

i= 1

while i*i < n:

print(2* i + 1)

i += 1

else:

print('Hakuna Matata')

The explanation of the equivalent of the above while loop is as follows

This line initializes i to 1

i= 1

This line iterates from 1 to n-1

for i in range(1,n):

This line checks if i * i is less than n

if i * i < n:

The following line is executed if the above condition is satisfied; otherwise, nothing is done

print(2* i + 1)

The value of i is incremented by 1 using this line

i += 1

The following is executed at the end of the iteration

else:

print('Hakuna Matata')

Note: Assume any value of n, both programs display the same output

User Robert Newton
by
4.7k points