Issue
I want to convert a loop-based script containing if
, elif
and else
into a list comprehension but I cannot figure out how to do it.
Here is the script I wrote (it prints the numbers from 1 to 100, but for multiples of 3 it prints 'fizz', for multiples of 5 it prints 'buzz' and for multiples of both 3 and 5 it prints 'fizzbuzz'):
for num in range(1, 101):
if num % 3 == 0 and num % 5 == 0:
print('fizzbuzz')
elif num % 3 == 0:
print('fizz')
elif num % 5 ==0:
print('buzz')
else:
print(num)
Solution
elif
is not part of the if-else short-hand, aka if else conditional operator, but you can achieve the same logic by chaining these operators, for example:
if A:
v = a
elif B:
v = b
else:
v = c
turns into
v = a if A else b if B else c
And you can use a conditional operator expression in your list comprehension:
[a if A else b if B else c for something in someiterator]
Note that things can become unreadable quite quickly, for example this may not be recommended in your example:
['fizzbuzz' if num%3 == 0 and num%5 == 0 else 'fizz' if num%3 == 0 else 'buzz' if num%5 == 0 else num for num in range(1, 101)]
Answered By - bonnal-enzo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.