Python | レベル別練習問題:変数 × 型(int / float / str)2

Python
スポンサーリンク

それでは、「変数 × 型(int / float / str)」をテーマに、
Python 初心者~中級者が実践練習できる 50問の自動採点付き問題集を作ります。


  1. 構成
  2. 自動採点用仕組み(共通)
  3. 基礎編(20問)
    1. Q1. 2つの整数を足す関数
    2. Q2. 文字列の長さを返す
    3. Q3. 小数の切り捨て整数変換
    4. Q4. 整数を文字列に変換
    5. Q5. 型を判定して文字列で返す
    6. Q6. f文字列で「XさんはY歳です」
    7. Q7. 2つの文字列をスペースで結合
    8. Q8. 数字文字列を整数に変換して2倍
    9. Q9. 割り算の結果を返す(float)
    10. Q10. 割り算の結果を整数で返す
    11. Q11. 剰余(余り)を返す
    12. Q12. べき乗(a の b 乗)
    13. Q13. 文字列を3回繰り返す
    14. Q14. 文字列を大文字にする
    15. Q15. 文字列を小文字にする
    16. Q16. 文字列の先頭と末尾の文字を返す
    17. Q17. 整数リストの合計を返す
    18. Q18. 小数の平均を返す
    19. Q19. 数値を「円」付き文字列にする
    20. Q20. 型変換でエラーを避ける安全変換関数
  4. 中級編(20問)
    1. Q21. 2つの数値の平均を小数点2桁で丸めて返す
    2. Q22. 浮動小数誤差を isclose で判定
    3. Q23. 整数を3桁ごとにカンマ区切り
    4. Q24. 文字列が数値か判定
    5. Q25. 入力文字列を float に変換(失敗時は 0.0)
    6. Q26. 文字列リストを整数リストに変換
    7. Q27. 整数が偶数か判定
    8. Q28. 小数を文字列にし「m」単位を付ける
    9. Q29. 整数のリストの最大・最小を返す
    10. Q30. 2つの値の型が同じなら True
  5. 応用編(20問)
  6. Q31:型の不一致エラーを防ぐ
  7. Q32:数値→文字列変換
  8. Q33:入力値を整数に変換して計算
  9. Q34:浮動小数点の加算
  10. Q35:round関数の活用
  11. Q36:例外処理 try-except(型変換)
  12. Q37:例外処理で0除算を防ぐ
  13. Q38:型ヒントを使った関数定義
  14. Q39:型ヒント × float
  15. Q40:Union型ヒント
  16. Q41:Noneを返す関数
  17. Q42:例外をキャッチして再実行
  18. Q43:例外メッセージを詳しく出す
  19. Q44:型チェック isinstance
  20. Q45:floatの誤差対策
  21. Q46:str型から数値型への安全変換
  22. Q47:変数に型を明示して宣言(PEP 526)
  23. Q48:例外の種類を複数キャッチ
  24. Q49:例外が起きても必ず実行される finally
  25. 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)])
Python

Q2. 文字列の長さを返す

def str_len(s):
    return len(s)

check("Q2", str_len, [(("abc",), 3), (("",), 0)])
Python

Q3. 小数の切り捨て整数変換

def to_int(x):
    return int(x)

check("Q3", to_int, [((3.9,), 3), ((-2.8,), -2)])
Python

Q4. 整数を文字列に変換

def int_to_str(x):
    return str(x)

check("Q4", int_to_str, [((5,), "5"), ((0,), "0")])
Python

Q5. 型を判定して文字列で返す

def type_name(x):
    return type(x).__name__

check("Q5", type_name, [((5,), "int"), ((3.14,), "float"), (("hi",), "str")])
Python

Q6. f文字列で「XさんはY歳です」

def intro(name, age):
    return f"{name}さんは{age}歳です"

check("Q6", intro, [(("Taro", 20), "Taroさんは20歳です")])
Python

Q7. 2つの文字列をスペースで結合

def join_words(a, b):
    return a + " " + b

check("Q7", join_words, [(("Hello", "World"), "Hello World")])
Python

Q8. 数字文字列を整数に変換して2倍

def double_str_num(s):
    return int(s) * 2

check("Q8", double_str_num, [(("10",), 20)])
Python

Q9. 割り算の結果を返す(float)

def divide(a, b):
    return a / b

check("Q9", divide, [((5, 2), 2.5)])
Python

Q10. 割り算の結果を整数で返す

def int_divide(a, b):
    return a // b

check("Q10", int_divide, [((5, 2), 2)])
Python

Q11. 剰余(余り)を返す

def remainder(a, b):
    return a % b

check("Q11", remainder, [((7, 3), 1)])
Python

Q12. べき乗(a の b 乗)

def power(a, b):
    return a ** b

check("Q12", power, [((2, 3), 8)])
Python

Q13. 文字列を3回繰り返す

def repeat3(s):
    return s * 3

check("Q13", repeat3, [(("ha",), "hahaha")])
Python

Q14. 文字列を大文字にする

def to_upper(s):
    return s.upper()

check("Q14", to_upper, [(("abc",), "ABC")])
Python

Q15. 文字列を小文字にする

def to_lower(s):
    return s.lower()

check("Q15", to_lower, [(("HeLLo",), "hello")])
Python

Q16. 文字列の先頭と末尾の文字を返す

def first_last(s):
    return s[0] + s[-1]

check("Q16", first_last, [(("Python",), "Pn")])
Python

Q17. 整数リストの合計を返す

def sum_list(lst):
    return sum(lst)

check("Q17", sum_list, [(([1, 2, 3],), 6)])
Python

Q18. 小数の平均を返す

def average(a, b):
    return (a + b) / 2

check("Q18", average, [((1.0, 3.0), 2.0)])
Python

Q19. 数値を「円」付き文字列にする

def yen(x):
    return f"{x}円"

check("Q19", yen, [((300,), "300円")])
Python

Q20. 型変換でエラーを避ける安全変換関数

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)])
Python

Q22. 浮動小数誤差を 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)])
Python

Q23. 整数を3桁ごとにカンマ区切り

def with_comma(n):
    return f"{n:,}"

check("Q23", with_comma, [((1000000,), "1,000,000")])
Python

Q24. 文字列が数値か判定

def is_numeric(s):
    return s.replace('.', '', 1).isdigit()

check("Q24", is_numeric, [(("3.14",), True), (("abc",), False)])
Python

Q25. 入力文字列を 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)])
Python

Q26. 文字列リストを整数リストに変換

def strlist_to_intlist(lst):
    return [int(x) for x in lst]

check("Q26", strlist_to_intlist, [((["1","2","3"],), [1,2,3])])
Python

Q27. 整数が偶数か判定

def is_even(n):
    return n % 2 == 0

check("Q27", is_even, [((4,), True), ((5,), False)])
Python

Q28. 小数を文字列にし「m」単位を付ける

def format_meter(x):
    return f"{x:.2f}m"

check("Q28", format_meter, [((1.2345,), "1.23m")])
Python

Q29. 整数のリストの最大・最小を返す

def minmax(lst):
    return (min(lst), max(lst))

check("Q29", minmax, [(([1,5,3],), (1,5))])
Python

Q30. 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
Python

Q32:数値→文字列変換

次のコードが "価格は100円です" と出力されるように書き換えましょう。

# Q32
price = 100
print("価格は" + price + "円です")
Python

🔍 判定

def check(output):
    return "価格は100円です" in output
Python

Q33:入力値を整数に変換して計算

ユーザーから入力を受け取り、合計を出力するプログラムを作ってください。

# Q33
x = input("1つ目の数: ")
y = input("2つ目の数: ")
# 合計を出力
Python

✅ 例:
入力 → 3, 5 → 出力 → 8

🔍 判定

def check(fn):
    return fn("3", "5") == 8
Python

Q34:浮動小数点の加算

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
Python

Q35:round関数の活用

小数点以下2桁に丸めて出力してください。

# Q35
num = 10 / 3
Python

🔍 判定

def check(num):
    return round(num, 2) == 3.33
Python

Q36:例外処理 try-except(型変換)

入力が数値でない場合、エラーメッセージを表示するようにしてください。

# Q36
value = input("数値を入力: ")
# 数値なら2倍して出力、数値でなければ「数値を入力してください」と表示
Python

🔍 判定

def check(fn):
    return fn("10") == 20 and fn("abc") == "数値を入力してください"
Python

Q37:例外処理で0除算を防ぐ

0で割ろうとしたら「0では割り算できません」と表示。

# Q37
a = int(input("分子: "))
b = int(input("分母: "))
# 結果を出力
Python

🔍 判定

def check(fn):
    return fn(10, 2) == 5 and fn(10, 0) == "0では割り算できません"
Python

Q38:型ヒントを使った関数定義

引数と戻り値の型ヒントをつけてください。

# Q38
def add(a, b):
    return a + b
Python

🔍 判定

def check(fn):
    return fn.__annotations__ == {'a': int, 'b': int, 'return': int}
Python

Q39:型ヒント × 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}
Python

Q40: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]}
Python

Q41:Noneを返す関数

型ヒントで「戻り値なし(None)」を明示しましょう。

# Q41
def greet(name):
    print("こんにちは", name)
Python

🔍 判定

def check(fn):
    return fn.__annotations__ == {'name': str, 'return': None}
Python

Q42:例外をキャッチして再実行

ユーザーが文字を入れても、再入力を促すプログラム。

# 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
Python

Q43:例外メッセージを詳しく出す

ValueError の内容を表示してください。

# Q43
try:
    num = int("abc")
except ValueError as e:
    print("エラー内容:", e)
Python

🔍 判定

def check(output):
    return "invalid literal" in output
Python

Q44:型チェック isinstance

与えられた値が int なら2倍、そうでなければ "数値ではありません" と返す。

# Q44
def double(value):
    pass
Python

🔍 判定

def check(fn):
    return fn(10) == 20 and fn("10") == "数値ではありません"
Python

Q45:floatの誤差対策

0.1 + 0.2 の結果を小数第3位で丸めて表示。

# Q45
result = 0.1 + 0.2
Python

🔍 判定

def check(result):
    return round(result, 3) == 0.3
Python

Q46:str型から数値型への安全変換

入力値が整数ならintに、そうでなければそのまま文字列で返す。

# Q46
def safe_int(value):
    pass
Python

🔍 判定

def check(fn):
    return fn("10") == 10 and fn("abc") == "abc"
Python

Q47:変数に型を明示して宣言(PEP 526)

型ヒントで「int 型の age」を宣言し、30を代入。

# Q47
# age = ?
Python

🔍 判定

def check(globals_):
    return globals_["age"] == 30
Python

Q48:例外の種類を複数キャッチ

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") == "入力エラー"
Python

Q49:例外が起きても必ず実行される finally

try / except / finally の動作を確認。

# Q49
try:
    x = int("abc")
except ValueError:
    print("変換できません")
finally:
    print("終了処理")
Python

🔍 判定

def check(output):
    return "変換できません" in output and "終了処理" in output
Python

Q50:総まとめ – 型ヒント + 例外 + 変換

整数か小数の入力を受け取り、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
Python
スポンサーリンク
シェアする
@lifehackerをフォローする
スポンサーリンク
タイトルとURLをコピーしました