Answer to Question #123993 in Python for Lebenis

Question #123993
Give an example of a while loop, then provide the equivalent do-while loop and for loop. Then give a different example of a do-while loop, along with the equivalent while loop and for loop. Finally, give an example of a for loop, along with the equivalent while loop and do-while loop. Use your examples to illustrate the advantages and disadvantages of each looping structure, and describe those advantages and disadvantages.
1
Expert's answer
2020-06-29T08:20:14-0400

1) print the powers of two

while loop

i = 0
while i <= 10:
    print(2**i)
    i += 1

do-while loop

i = 0
while True:
    print(2**i)
    i += 1
    if i > 10:
        break

for loop

advantage: it's not needed to explicitly update counter variable

for i in range(11):
    print(2**i)


2) write a non-negative number in reverse

do-while loop

advantage: differentiates between input and intermediate data (when 0 is given as input)

n = int(input())
while True:
    print(n % 10, end='')
    n //= 10
    if n == 0:
        break

while loop

n = int(input())
if n == 0:
    print(0)
while n != 0:
    print(n % 10, end='')
    n //= 10

for loop

disadvantage: for loop is for iteration only; while and do-while are general purpose loops

from math import ceil, log10
n = int(input())
if n == 0:
    print(0)
else:
    for i in range(ceil(log10(n))):  # how many digits in the number
        print(n % 10, end='')
        n //= 10


3) print elements of a list

for loop

advantage: it's not necessary to know iterable length when using for loop

l = input().split()
for n in l:
    print(n)

while loop

disadvantage: counter variable is needed to cycle through a list

l = input().split()
i = 0
while i < len(l):
    print(l[i])
    i += 1

do-while loop

disadvantage: without additional check there is IndexError when blank input is given

l = input().split()
i = 0
while len(l) > 0 and True:
    print(l[i])
    i += 1
    if i >= len(l):
        break

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS