I had the opportunity to teach the basics to python beginners, and I had them do it with the aim of getting used to intensional expressions in the Fizzbuzz problem. This time I decided to try from 1 to 30. The environment is Python 3.5.0
Ordinary
fizzbuzz.py
for n in range(1, 31):
if n % 3 == 0 and n % 5 == 0:
print("FizzBuzz")
elif n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
else:
print(n)
Example of one-line binding (3 and 5 are annoying, so set it to 15)
fizzbuzz2.py
["FizzBuzz" if n % 15 == 0 else "Fizz" if n % 3 == 0 else "Buzz" if n % 5 == 0 else n for n in range(1,31)]
This is a little improved because it only creates a list and is not displayed
fizzbuzz3.py
print("\n".join(["FizzBuzz" if n % 15 == 0 else "Fizz" if n % 3 == 0 else "Buzz" if n % 5 == 0 else str(n) for n in range(1,31)]))
Since the length of one line ignores PEP8 as much as possible, line breaks should be made appropriately when the inclusion actually becomes long.
FizzBuzz is also possible with the description in shiracamus's comment. It's very tricky, but it feels like python's unique writing style, so if you can see that as well
Recommended Posts