Python で数値 n の平方を計算

Document 对象参考手册Python3 例

この簡単な Python プログラムは、数値 n の平方を計算します。平方とは、ある数をそれ自身で掛けることです。

例

def calculate_square(n):
    return n * n

# 使用例
number = 4
result = calculate_square(number)
print(f"The square of {number} is {result}")

コードの解説:

  • def calculate_square(n):という名前のcalculate_square関数を定義しました。それは 1 つの引数n。
  • return n * nを受け取ります。関数はnの平方値を返します。
  • number = 4変数numberを定義し、4 を代入しました。
  • result = calculate_square(number)関数calculate_squareを呼び出し、結果を変数resultに格納します。
  • print(f"The square of {number} is {result}")フォーマット文字列を使用して結果を出力します。

出力結果:

The square of 4 is 16

Document 对象参考手册Python3 例

その他の拡張