ここまでで if 文と for / while を使った制御の基礎を学びました。仕上げに、これらを組み合わせた課題に挑戦してみましょう。
チャレンジ 1: 成績判定シミュレーター #
生徒 5 人の氏名と点数を入力し、80 点以上は “Pass”、60 点以上 80 点未満は “Border”、それ未満は “Fail” と表示するプログラムを作ってください。結果は次のような表形式にすると良いでしょう。
Name Score Result
Alice 85 Pass
Bob 74 Border
...
records = []
for _ in range(5):
name = input("名前: ")
score = int(input("点数: "))
if score >= 80:
result = "Pass"
elif score >= 60:
result = "Border"
else:
result = "Fail"
records.append((name, score, result))
print(“Name\tScore\tResult”)
for name, score, result in records:
print(f"{name}\t{score}\t{result}")
チャレンジ 2: 文字列圧縮(初級) #
文字列の各文字が連続して何回出現するかを数え、aabcccccaaa → a2b1c5a3 のように圧縮するプログラムを、for か while を使って書いてみましょう。
text = input("文字列: ")
if not text:
print("空文字です")
else:
result = []
current = text[0]
count = 1
for ch in text[1:]:
if ch == current:
count += 1
else:
result.append(f"{current}{count}")
current = ch
count = 1
result.append(f"{current}{count}")
print("".join(result))チャレンジ 3: モンテカルロ法でπを近似 #
0~1 の乱数を使ってモンテカルロ法で π を近似してみましょう。繰り返し回数を増やすと精度が上がります。
import random
n = int(input("試行回数: "))
inside = 0
for _ in range(n):
x = random.random()
y = random.random()
if x * x + y * y <= 1.0:
inside += 1
pi_estimate = 4 * inside / n
print("推定値:", pi_estimate)