Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!

Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount

関数


What are Functions?

関数は、コードを便利なブロックに分割する方法であり、コードを整理し、読みやすくし、再利用し、時間を節約することができます。また、関数はプログラマーがコードを共有するための重要な手段です。

How do you write functions in Python?

以前のチュートリアルで見たように、Pythonはブロックを使用します。

ブロックは、以下の形式で書かれたコードの領域です:

ここで、ブロックラインはさらに多くのPythonコード(別のブロックでも可)で構成されており、ブロックヘッドは次の形式です: block_keyword block_name(argument1,argument2, ...) あなたがすでに知っているブロックキーワードは "if"、"for"、および "while" です。

Pythonでの関数は、ブロックキーワード "def" を使用して定義され、そのブロック名として関数の名前が続きます。 例:

関数はまた、引数(呼び出し元から関数への変数)を受け取ることができます。 例:

関数は、キーワード 'return' を使用して呼び出し元に値を返すことができます。 例:

How do you call functions in Python?

単に関数名の後に () を書き、必要な引数を括弧の中に配置します。 例として、上記の例で書かれた関数を呼び出してみましょう:

演習

この演習では、既存の関数を使用しながら、自分の関数を追加して、完全に機能するプログラムを作成します。

  1. "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"という文字列のリストを返すlist_benefits()という名前の関数を追加します。

  2. 文字列を含む単一の引数を受け取り、その文字列で始まり、" is a benefit of functions!"で終わる文を返すbuild_sentence(info)という名前の関数を追加します。

  3. すべての関数が一緒に動作するのを実行して確認してください!

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Previous Tutorial Next Tutorial Take the Test
Copyright © learnpython.org. Read our Terms of Use and Privacy Policy