2025.02.28(更新日: 2025.02.28)
FizzBuzzについて解説
はじめに
みなさんは「FizzBuzz」をご存知だろうか?
3の倍数の時は「Fizz」、5の倍数の時は「Buzz」、15の倍数の時は「FizzBuzz」と出力するやつだ。
前提として、1~100まで出力する。
今回はそんな「FizzBuzz」をPythonで作成してみたので、ソースコードの解説をしていきたい。
まずは単純出力
for文とrangeの知識を試すコードを書いた。
for i in range(0, 100):
print(i)
こちらを実行すると、0~99まで単純出力される。


1~100にする
range関数は、終了値 – 1の数値までの連続した数値を持つ「イテラブル」なので、range(1, 101)とすることで、1~100までの数値を持つ「イテラブル」にすることができる。
for i in range(1, 101):
print(i)


3の倍数のとき「fizz」を出力する
3の倍数ということは3で割った時の余りが0ということ。
if文の条件にそれを持ってくる。
elseには3の倍数以外がくることになる。
for i in range(1, 101):
if i % 3 == 0:
print('fizz')
else:
print(i)

5の倍数のとき「buzz」を出力する
ここで登場するのが「elif」。
elifで条件を追加することができる。分岐を追加といった方が適切かもしれない。
for i in range(1, 101):
if i % 3 == 0:
print('fizz')
elif i % 5 == 0:
print('buzz')
else:
print(i)

15の倍数のとき、「fizzbuzz」を出力する
15の倍数というのは、3の倍数と5の倍数の両方の条件を満たすということ。
最小公倍数である。
for i in range(1, 101):
if i % 15 == 0:
print('fizzbuzz')
elif i % 3 == 0:
print('fizz')
elif i % 5 == 0:
print('buzz')
else:
print(i)

git登録
私が以前書いた以下の記事を参考にgithubのリポジトリで管理できるようにした。
(venv) Mac:python shibatahiroshitaka$ cd fizzbuzz
(venv) Mac:fizzbuzz shibatahiroshitaka$ git init
hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint:
hint: git config --global init.defaultBranch <name>
hint:
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint:
hint: git branch -m <name>
Initialized empty Git repository in /Users/shibatahiroshitaka/Downloads/python/fizzbuzz/.git/
(venv) Mac:fizzbuzz shibatahiroshitaka$ git remote add origin https://github.com/ki-hi-ro/fizzbuzz.git
(venv) Mac:fizzbuzz shibatahiroshitaka$ git remote -v
origin https://github.com/ki-hi-ro/fizzbuzz.git (fetch)
origin https://github.com/ki-hi-ro/fizzbuzz.git (push)
(venv) Mac:fizzbuzz shibatahiroshitaka$ git add .
(venv) Mac:fizzbuzz shibatahiroshitaka$ git commit -m "fizzbuzz initial"
[master (root-commit) 0347ca0] fizzbuzz initial
1 file changed, 9 insertions(+)
create mode 100644 fizzbuzz.py
(venv) Mac:fizzbuzz shibatahiroshitaka$ git push origin master
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Delta compression using up to 8 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 299 bytes | 299.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
To https://github.com/ki-hi-ro/fizzbuzz.git
* [new branch] master -> master

ソースコード
for i in range(1, 101):
if i % 15 == 0:
print('fizzbuzz')
elif i % 3 == 0:
print('fizz')
elif i % 5 == 0:
print('buzz')
else:
print(i)
投稿ID : 28752
コメントを残す