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
Comments
Leave a comment