目次
プログラミング教育者。ScratchやPythonを教えています。
工作HardwareHubからのお知らせ
defステートメントを用いて定義します。
sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
def rec(x):
return 1 if x==0 else x*rec(x-1)
for (i,x) in enumerate(range(7)):
print "%d!=%d" % (i,rec(x))
出力例
$ python sample.py
0!=1
1!=1
2!=2
3!=6
4!=24
5!=120
6!=720
デフォルト引数の指定
sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
def func(x='default'):
print x
func(123)
func()
出力例
$ python sample.py
123
default
複数の値を引数として渡す (Rubyの多値相当)
関数定義でアスタリスクを使用
sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
def printTuple(*arg): # タプル化
print arg
def printDict(**arg): # ディクショナリ化
print arg
printTuple(1,2,3,4)
printDict(a=1, b=2, c=3)
実行例
$ python sample.py
(1, 2, 3, 4)
{'a': 1, 'c': 3, 'b': 2}
関数呼び出しでアスタリスクを使用
sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
def func(a,b,c):
print a,b,c
T = tuple("str")
D = dict(zip(['a','b','c'],[1,2,3]))
func(*T)
func(**D)
出力例
$ python sample.py
s t r
1 2 3
動的な関数定義
sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
if False:
def func(x): return x*2
else:
def func(x): return x+2
print func(10)
出力例
$ python sample.py
12
変数への代入
sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
def func(x,y): return x+y
ref = func
print ref(7,8)
出力例
$ python sample.py
15
グローバル変数の利用
sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
x = 128
def func():
global x
x = 256
func()
print x
出力例
$ python sample.py
256
クロージャ
sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
def getFact(base):
def fact(x):
return base**x
return fact
ref = getFact(1)
print ref(10)
ref = getFact(2)
print ref(10)
出力例
$ python sample.py
1
1024
ラムダ式を用いたクロージャ
いわゆるラムダ式です。Perlでは無名関数と呼ばれていたものです。
なお、ラムダ式内には一つのステートメントしか記述できません。
sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
def getFact(base):
return (lambda x: base**x)
ref = getFact(1)
print ref(10)
ref = getFact(2)
print ref(10)
出力例
$ python sample.py
1
1024
0
記事の執筆者にステッカーを贈る
有益な情報に対するお礼として、またはコメント欄における質問への返答に対するお礼として、 記事の読者は、執筆者に有料のステッカーを贈ることができます。
さらに詳しく →Feedbacks
ログインするとコメントを投稿できます。
関連記事
- Python コードスニペット (条件分岐)if-elif-else sample.py #!/usr/bin/python # -*- coding: utf-8 -*- # コメント内であっても、ASCII外の文字が含まれる場合はエンコーディング情報が必須 x = 1 # 一行スタイル if x==0: print 'a' # 参考: and,or,notが使用可能 (&&,||はエラー) elif x==1: p...
- Python コードスニペット (リスト、タプル、ディクショナリ)リスト range 「0から10まで」といった範囲をリスト形式で生成します。 sample.py print range(10) # for(int i=0; i<10; ++i) ← C言語などのfor文と比較 print range(5,10) # for(int i=5; i<10; ++i) print range(5,10,2) # for(int i=5; i<10;...
- ZeroMQ (zmq) の Python サンプルコードZeroMQ を Python から利用する場合のサンプルコードを記載します。 Fixing the World To fix the world, we needed to do two things. One, to solve the general problem of "how to connect any code to any code, anywhere". Two, to wra...
- Matplotlib/SciPy/pandas/NumPy サンプルコードPython で数学的なことを試すときに利用される Matplotlib/SciPy/pandas/NumPy についてサンプルコードを記載します。 Matplotlib SciPy pandas [NumPy](https://www.numpy
- pytest の基本的な使い方pytest の基本的な使い方を記載します。 適宜参照するための公式ドキュメントページ Full pytest documentation API Reference インストール 適当なパッケージ