Pythonで「calculator()」の関数は、どうやって使うのですか?


ブログ読者からの質問:Pythonで「calculator()」の関数は、どうやって使うのですか?


回答

Pythonで「calculator()」という関数を使う場合は、以下のような手順で使用することができます。

  1. calculator()関数の定義
def calculator(operation, a, b):
    if operation == "+":
        return a + b
    elif operation == "-":
        return a - b
    elif operation == "*":
        return a * b
    elif operation == "/":
        return a / b
    else:
        return "Invalid operation"
  1. 関数の呼び出し
result = calculator("+", 5, 3)
print(result)  # Output: 8

result = calculator("-", 10, 4)
print(result)  # Output: 6

result = calculator("*", 2, 7)
print(result)  # Output: 14

result = calculator("/", 15, 3)
print(result)  # Output: 5.0

result = calculator("**", 2, 3)
print(result)  # Output: Invalid operation

このcalculator()関数は、3つの引数を受け取ります:

  • operation: 数学演算の種類を表す文字列 (“+”, “-“, “*”, “/”)
  • a: 演算の左側の数値
  • b: 演算の右側の数値

関数は、与えられた演算子に応じて、2つの数値の計算結果を返します。無効な演算子が渡された場合は、エラーメッセージを返します。

呼び出し時は、関数名と引数を指定して実行します。上記の例のように、関数の戻り値を変数に代入したり、直接出力することができます。

error: Alert: Content selection is disabled!!
タイトルとURLをコピーしました