それでは、「変数 × 型(int / float / str)」をテーマに、
Python 初心者~中級者が実践練習できる 50問の自動採点付き問題集を作ります。
- 構成
- 自動採点用仕組み(共通)
- 基礎編(20問)
- Q1. 2つの整数を足す関数
- Q2. 文字列の長さを返す
- Q3. 小数の切り捨て整数変換
- Q4. 整数を文字列に変換
- Q5. 型を判定して文字列で返す
- Q6. f文字列で「XさんはY歳です」
- Q7. 2つの文字列をスペースで結合
- Q8. 数字文字列を整数に変換して2倍
- Q9. 割り算の結果を返す(float)
- Q10. 割り算の結果を整数で返す
- Q11. 剰余(余り)を返す
- Q12. べき乗(a の b 乗)
- Q13. 文字列を3回繰り返す
- Q14. 文字列を大文字にする
- Q15. 文字列を小文字にする
- Q16. 文字列の先頭と末尾の文字を返す
- Q17. 整数リストの合計を返す
- Q18. 小数の平均を返す
- Q19. 数値を「円」付き文字列にする
- Q20. 型変換でエラーを避ける安全変換関数
- 中級編(20問)
- 応用編(20問)
- Q31:型の不一致エラーを防ぐ
- Q32:数値→文字列変換
- Q33:入力値を整数に変換して計算
- Q34:浮動小数点の加算
- Q35:round関数の活用
- Q36:例外処理 try-except(型変換)
- Q37:例外処理で0除算を防ぐ
- Q38:型ヒントを使った関数定義
- Q39:型ヒント × float
- Q40:Union型ヒント
- Q41:Noneを返す関数
- Q42:例外をキャッチして再実行
- Q43:例外メッセージを詳しく出す
- Q44:型チェック isinstance
- Q45:floatの誤差対策
- Q46:str型から数値型への安全変換
- Q47:変数に型を明示して宣言(PEP 526)
- Q48:例外の種類を複数キャッチ
- Q49:例外が起きても必ず実行される finally
- Q50:総まとめ – 型ヒント + 例外 + 変換
構成
| レベル | 範囲 | 問題数 |
|---|---|---|
| 基礎 | 変数・代入・型の確認・型変換 | 20問 |
| 中級 | 計算・文字列処理・入力処理・f文字列 | 20問 |
| 応用 | 条件分岐・例外処理・関数・型チェック | 10問 |
各問題は
✅ 問題文
✅ 期待出力
✅ 自動採点コード(テスト関数)
をセットにしています。
実際にコピペして Python 実行すれば自動で正誤を判定できます。
自動採点用仕組み(共通)
まず以下を先頭に置いてください:
# 採点関数(正誤チェック用)
def check(problem, student_func, tests):
print(f"--- {problem} ---")
ok = 0
for i, (args, expected) in enumerate(tests, 1):
try:
result = student_func(*args)
if result == expected:
print(f"✅ Test {i} OK: {result}")
ok += 1
else:
print(f"❌ Test {i} NG: got {result}, expected {expected}")
except Exception as e:
print(f"⚠️ Test {i} Error: {e}")
print(f"→ {ok}/{len(tests)} passed\n")
Pythonこれを上に貼っておけば、どの問題でも check() を呼ぶだけで採点されます。
基礎編(20問)
Q1. 2つの整数を足す関数
def add(a, b):
return a + b
check("Q1", add, [((1, 2), 3), ((10, -5), 5)])
PythonQ2. 文字列の長さを返す
def str_len(s):
return len(s)
check("Q2", str_len, [(("abc",), 3), (("",), 0)])
PythonQ3. 小数の切り捨て整数変換
def to_int(x):
return int(x)
check("Q3", to_int, [((3.9,), 3), ((-2.8,), -2)])
PythonQ4. 整数を文字列に変換
def int_to_str(x):
return str(x)
check("Q4", int_to_str, [((5,), "5"), ((0,), "0")])
PythonQ5. 型を判定して文字列で返す
def type_name(x):
return type(x).__name__
check("Q5", type_name, [((5,), "int"), ((3.14,), "float"), (("hi",), "str")])
PythonQ6. f文字列で「XさんはY歳です」
def intro(name, age):
return f"{name}さんは{age}歳です"
check("Q6", intro, [(("Taro", 20), "Taroさんは20歳です")])
PythonQ7. 2つの文字列をスペースで結合
def join_words(a, b):
return a + " " + b
check("Q7", join_words, [(("Hello", "World"), "Hello World")])
PythonQ8. 数字文字列を整数に変換して2倍
def double_str_num(s):
return int(s) * 2
check("Q8", double_str_num, [(("10",), 20)])
PythonQ9. 割り算の結果を返す(float)
def divide(a, b):
return a / b
check("Q9", divide, [((5, 2), 2.5)])
PythonQ10. 割り算の結果を整数で返す
def int_divide(a, b):
return a // b
check("Q10", int_divide, [((5, 2), 2)])
PythonQ11. 剰余(余り)を返す
def remainder(a, b):
return a % b
check("Q11", remainder, [((7, 3), 1)])
PythonQ12. べき乗(a の b 乗)
def power(a, b):
return a ** b
check("Q12", power, [((2, 3), 8)])
PythonQ13. 文字列を3回繰り返す
def repeat3(s):
return s * 3
check("Q13", repeat3, [(("ha",), "hahaha")])
PythonQ14. 文字列を大文字にする
def to_upper(s):
return s.upper()
check("Q14", to_upper, [(("abc",), "ABC")])
PythonQ15. 文字列を小文字にする
def to_lower(s):
return s.lower()
check("Q15", to_lower, [(("HeLLo",), "hello")])
PythonQ16. 文字列の先頭と末尾の文字を返す
def first_last(s):
return s[0] + s[-1]
check("Q16", first_last, [(("Python",), "Pn")])
PythonQ17. 整数リストの合計を返す
def sum_list(lst):
return sum(lst)
check("Q17", sum_list, [(([1, 2, 3],), 6)])
PythonQ18. 小数の平均を返す
def average(a, b):
return (a + b) / 2
check("Q18", average, [((1.0, 3.0), 2.0)])
PythonQ19. 数値を「円」付き文字列にする
def yen(x):
return f"{x}円"
check("Q19", yen, [((300,), "300円")])
PythonQ20. 型変換でエラーを避ける安全変換関数
def safe_int(s):
try:
return int(s)
except:
return None
check("Q20", safe_int, [(("123",), 123), (("abc",), None)])
Python中級編(20問)
(入力処理・数値変換・f文字列・丸めなどの実用問題)
Q21. 2つの数値の平均を小数点2桁で丸めて返す
def avg_2(a, b):
return round((a + b) / 2, 2)
check("Q21", avg_2, [((1, 2), 1.5), ((1.234, 1.236), 1.24)])
PythonQ22. 浮動小数誤差を isclose で判定
import math
def is_equal_float(a, b):
return math.isclose(a, b)
check("Q22", is_equal_float, [((0.1+0.2, 0.3), True)])
PythonQ23. 整数を3桁ごとにカンマ区切り
def with_comma(n):
return f"{n:,}"
check("Q23", with_comma, [((1000000,), "1,000,000")])
PythonQ24. 文字列が数値か判定
def is_numeric(s):
return s.replace('.', '', 1).isdigit()
check("Q24", is_numeric, [(("3.14",), True), (("abc",), False)])
PythonQ25. 入力文字列を float に変換(失敗時は 0.0)
def to_float_safe(s):
try:
return float(s)
except:
return 0.0
check("Q25", to_float_safe, [(("3.5",), 3.5), (("abc",), 0.0)])
PythonQ26. 文字列リストを整数リストに変換
def strlist_to_intlist(lst):
return [int(x) for x in lst]
check("Q26", strlist_to_intlist, [((["1","2","3"],), [1,2,3])])
PythonQ27. 整数が偶数か判定
def is_even(n):
return n % 2 == 0
check("Q27", is_even, [((4,), True), ((5,), False)])
PythonQ28. 小数を文字列にし「m」単位を付ける
def format_meter(x):
return f"{x:.2f}m"
check("Q28", format_meter, [((1.2345,), "1.23m")])
PythonQ29. 整数のリストの最大・最小を返す
def minmax(lst):
return (min(lst), max(lst))
check("Q29", minmax, [(([1,5,3],), (1,5))])
PythonQ30. 2つの値の型が同じなら True
def same_type(a, b):
return type(a) == type(b)
check("Q30", same_type, [((1,2), True), ((1, "1"), False)])
Python応用編(20問)
(例外処理・型ヒント・応用テクニック)
Q31:型の不一致エラーを防ぐ
次のコードはエラーになります。int() を使って修正してください。
# Q31
a = "10"
b = 5
result = a + b
print(result)
Python🔍 正誤判定コード
def check(result):
return result == 15
PythonQ32:数値→文字列変換
次のコードが "価格は100円です" と出力されるように書き換えましょう。
# Q32
price = 100
print("価格は" + price + "円です")
Python🔍 判定
def check(output):
return "価格は100円です" in output
PythonQ33:入力値を整数に変換して計算
ユーザーから入力を受け取り、合計を出力するプログラムを作ってください。
# Q33
x = input("1つ目の数: ")
y = input("2つ目の数: ")
# 合計を出力
Python✅ 例:
入力 → 3, 5 → 出力 → 8
🔍 判定
def check(fn):
return fn("3", "5") == 8
PythonQ34:浮動小数点の加算
0.1 を10回足して、結果を出力してみましょう。
# Q34
total = 0.0
for i in range(10):
total += 0.1
print(total)
Python🔍 判定
def check(total):
return abs(total - 1.0) < 1e-9
PythonQ35:round関数の活用
小数点以下2桁に丸めて出力してください。
# Q35
num = 10 / 3
Python🔍 判定
def check(num):
return round(num, 2) == 3.33
PythonQ36:例外処理 try-except(型変換)
入力が数値でない場合、エラーメッセージを表示するようにしてください。
# Q36
value = input("数値を入力: ")
# 数値なら2倍して出力、数値でなければ「数値を入力してください」と表示
Python🔍 判定
def check(fn):
return fn("10") == 20 and fn("abc") == "数値を入力してください"
PythonQ37:例外処理で0除算を防ぐ
0で割ろうとしたら「0では割り算できません」と表示。
# Q37
a = int(input("分子: "))
b = int(input("分母: "))
# 結果を出力
Python🔍 判定
def check(fn):
return fn(10, 2) == 5 and fn(10, 0) == "0では割り算できません"
PythonQ38:型ヒントを使った関数定義
引数と戻り値の型ヒントをつけてください。
# Q38
def add(a, b):
return a + b
Python🔍 判定
def check(fn):
return fn.__annotations__ == {'a': int, 'b': int, 'return': int}
PythonQ39:型ヒント × float
浮動小数点の掛け算を行う関数に型ヒントを追加。
# Q39
def multiply(a, b):
return a * b
Python🔍 判定
def check(fn):
return fn(1.5, 2.0) == 3.0 and fn.__annotations__ == {'a': float, 'b': float, 'return': float}
PythonQ40:Union型ヒント
整数でも小数でも受け取れるようにしてみよう。
# Q40
def square(num):
return num ** 2
Python🔍 判定
from typing import Union
def check(fn):
return fn.__annotations__ == {'num': Union[int, float], 'return': Union[int, float]}
PythonQ41:Noneを返す関数
型ヒントで「戻り値なし(None)」を明示しましょう。
# Q41
def greet(name):
print("こんにちは", name)
Python🔍 判定
def check(fn):
return fn.__annotations__ == {'name': str, 'return': None}
PythonQ42:例外をキャッチして再実行
ユーザーが文字を入れても、再入力を促すプログラム。
# Q42
while True:
try:
x = int(input("数を入力: "))
print(x * 2)
break
except:
print("数値を入力してください")
Python🔍 判定
def check(fn):
return "数値を入力してください" in fn("abc") and fn("10") == 20
PythonQ43:例外メッセージを詳しく出す
ValueError の内容を表示してください。
# Q43
try:
num = int("abc")
except ValueError as e:
print("エラー内容:", e)
Python🔍 判定
def check(output):
return "invalid literal" in output
PythonQ44:型チェック isinstance
与えられた値が int なら2倍、そうでなければ "数値ではありません" と返す。
# Q44
def double(value):
pass
Python🔍 判定
def check(fn):
return fn(10) == 20 and fn("10") == "数値ではありません"
PythonQ45:floatの誤差対策
0.1 + 0.2 の結果を小数第3位で丸めて表示。
# Q45
result = 0.1 + 0.2
Python🔍 判定
def check(result):
return round(result, 3) == 0.3
PythonQ46:str型から数値型への安全変換
入力値が整数ならintに、そうでなければそのまま文字列で返す。
# Q46
def safe_int(value):
pass
Python🔍 判定
def check(fn):
return fn("10") == 10 and fn("abc") == "abc"
PythonQ47:変数に型を明示して宣言(PEP 526)
型ヒントで「int 型の age」を宣言し、30を代入。
# Q47
# age = ?
Python🔍 判定
def check(globals_):
return globals_["age"] == 30
PythonQ48:例外の種類を複数キャッチ
0除算とValueErrorのどちらにも対応する。
# Q48
try:
a = int(input())
b = int(input())
print(a / b)
except (ZeroDivisionError, ValueError):
print("入力エラー")
Python🔍 判定
def check(fn):
return fn(10, 0) == "入力エラー" and fn("a", "b") == "入力エラー"
PythonQ49:例外が起きても必ず実行される finally
try / except / finally の動作を確認。
# Q49
try:
x = int("abc")
except ValueError:
print("変換できません")
finally:
print("終了処理")
Python🔍 判定
def check(output):
return "変換できません" in output and "終了処理" in output
PythonQ50:総まとめ – 型ヒント + 例外 + 変換
整数か小数の入力を受け取り、2倍して返す関数。
変換できない場合は "数値を入力してください" を返す。
# Q50
def double(value):
pass
Python🔍 判定
from typing import Union
def check(fn):
return fn("3") == 6 and fn("2.5") == 5.0 and fn("abc") == "数値を入力してください"
Python