CodeX
Published in

CodeX

One-Line FizzBuzz Solution in Python 3

“FizzBuzz in One Line” Blog Banner. The title overlays the Python code solution and includes the Python logo.

Introduction

The FizzBuzz Problem

Example Printout

1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16

98
fizz
buzz

Multiple Line Solution

for x in range(1, 101):
if x%15 == 0:
print('fizzbuzz')
elif x%5 == 0:
print('buzz')
elif x%3 == 0:
print('fizz')
else:
print(x)

One line FizzBuzz Example

print('\n'.join(['fizzbuzz' if x%15 == 0 else 'buzz' if x%5 == 0 else 'fizz' if x%3 == 0 else str(x) for x in range(1,101)]))
[x for x in range(1, 101)]
['fizzbuzz' if x%15==0 else x for x in range(1, 101)]
['fizzbuzz' if x%15==0 else "buzz" if x%5 == 0 else "fizz" if x%3 == 0 else x for x in range(1, 101)]
['fizzbuzz' if x%15==0 else "buzz" if x%5 == 0 else "fizz" if x%3 == 0 else str(x) for x in range(1, 101)]
'\n'.join(['fizzbuzz' if x%15==0 else "buzz" if x%5 == 0 else "fizz" if x%3 == 0 else str(x) for x in range(1, 101)])
print('\n'.join(['fizzbuzz' if x%15==0 else "buzz" if x%5 == 0 else "fizz" if x%3 == 0 else str(x) for x in range(1, 101)]))

Conclusion

--

--

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
David Sanchez

Computer Scientist, MS, interested in machine learning, data driven automation, nature, and whiskey. CEO and founder of the DNS AI, LLC software company.