こんにちは、鯨井貴博@opensourcetechです。
Python の関数定義とlambda(ラムダ)式に関するメモです。
以下はいずれも同じことを実施しています。
関数の定義の仕方
bash-3.2$ python
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def tashizan(a,b):・・・関数tashizanの定義
... c = a+b
... return c
...
>>> tashizan(1,2)・・・関数tashizanの実施
3
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def tashizan(a,b):・・・関数tashizanの定義
... c = a+b
... return c
...
>>> tashizan(1,2)・・・関数tashizanの実施
3
入れ子になった関数の定義の仕方
bash-3.2$ python
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def testranger():
... def range():・・・入れ子の関数定義
... x = 7
... print(x)
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def testranger():
... def range():・・・入れ子の関数定義
... x = 7
... print(x)
lambda(ラムダ)式による関数定義
bash-3.2$ python
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> tashizan = lambda a,b : a+b・・・関数tashizanの定義
>>> tashizan(2,3)・・・関数tashizanの実施
5
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> tashizan = lambda a,b : a+b・・・関数tashizanの定義
>>> tashizan(2,3)・・・関数tashizanの実施
5