0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

復習 Python tutorial #4 関数1

Last updated at Posted at 2021-03-04

関数

これまでの関数は元々定義されていた関数である。しかし関数というものは自分で作ることも可能である。関数というものは任意の型、任意の個数の入力引数をとり任意の型や数字を出力する。関数に対しては定義と呼び出しを主に行うことができる。定義の仕方は簡単でdefと入力し、関数名を書き関数に関する入力引数をカッコで囲んでかく。
まず引数を取らない関数を定義すると

def do_nothing():
    pass
do_nothing()
def write_something():
    print('something')
write_something()
# 実行結果
something

このようにして簡単にやることができる。

def agree():
    return True
if agree():
    print("You're good")
else:
    print("You're bad")
# 実行結果
You're good

カッコの中に何か入れてそれを代入していくという形をやってみよう

def anything_tap(anything):
    print("You're ", anything)
anything_tap('good')
anything_tap('cool')
# 実行結果
You're  good
You're  cool

このようなものは簡易的であるから対して関数の意味があるのかと思うかもしれない。関数を考えるにあたってはif文と一緒に用いたりすると利便性がわかると思う。

def you_choose_t_shirt(color):
    if color == 'red':
        print('You choose A-SHIRT')
    elif color == 'blue':
        print('You choose B-SHIRT')
    elif color == 'yellow':
        print('You choose C-SHIRT')
    else:
        print("I don't have shirt which you want")
you_choose_t_shirt('blue')
# 実行結果
You choose B-SHIRT

Noneについて

NoneはPythonの特殊な値で何もいうことがない時に使う。Noneはブール値として評価するとFalseとして返されるが、実際はFalseとは少し違う性質を持っている。

# None
thing = None
if thing:
    print("It's something")
else:
    print("It's no thing")
# False
thing = False
if thing:
    print("It's something")
else:
    print("It's no thing")
# 実行結果
It's no thing
It's no thing

これをみる限り区別はない。ではis演算子というある値がNoneかどうかというものをいろいろチェックできるものである。大まかにいうとNoneは空の値と存在しない値を区別する際に必要なものである。NoneはNoneしか返されない。それ以外は全てFalseという考え方でしばらくはいいであろう。

thing = None
if thing is None:
    print('There is None')
else:
    print('There is a object')
# 実行結果
There is None

位置引数

これはごく簡単で先頭から入れた順に対応する位置の仮引数にコピーされるというものである。

def menu(color, sort, feature):
    return {'color': color, 'sort': sort, 'feature': feature}
print(menu('yellow', 'T-SHIRT', 'SOFT'))
# 実行結果
{'color': 'yellow', 'sort': 'T-SHIRT', 'feature': 'SOFT'}

キーワード引数

位置引数は便利ではあるが、たくさんの情報を打つとなるとどれがどれだか分からなくなる。そのことを止めるためにはキーワード引数というものを用いる。これは位置引数のような順番は関係ないい。ではさっきの位置引数に関してキーワード引数を考えてみよう。

menu(sort='Jacket', color='blue', feature='tough')
# 実行結果
{'color': 'blue', 'sort': 'Jacket', 'feature': 'tough'}

デフォルト引数値の指定。

例えばJacketという枠組みで考えるとした時に、いちいちJacketを代入するのは面倒である。それを防ぐために用いられるのがデフォルト引数値である。

def menu(color, feature, sort='Jacket'):
    return {'color': color, 'sort': sort, 'feature': feature}
print(menu('yellow', 'SOFT'))
# 実行結果
{'color': 'yellow', 'sort': 'Jacket', 'feature': 'SOFT'}

ここで気をつけて欲しいのはsortの位置であるデフォルト引数と位置引数を両方用いる時はデフォルト値の位置は右端でないといけない。
デフォルト引数は他にも空のリストを作って実行するということもできる。これはリストが更新する形で作れるので引数に対してリストを自動的に作ることが可能である。

def list_making(value, list=[]):
    list.append(value)
    print(list)
list_making(1)
# 実行結果
[1]
# 複数の引数を入れたい時は?
# 考えてみよう。答えはすぐ下

このようにして引数は指定の仕方がいろいろある。

複数引数の答え

def list_makings_1(values, list=[]):
    for value in values:
        list.append(value)
    print(list)
def list_makings_2(values, list=[], zero=0):
    while len(values) > zero:
        value = values[zero]
        list.append(value)
        zero+=1
    print(list)
list_makings([1,2,3])

どちらかでできる。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

タプル化

仮引数のものをタプル化したい時は*を用いることによって仮引数をタプル化することができる。

def def become_taple(*ob):
    print('This is converted to taple: ', ob)
become_taple(1, 2, 3)
# 実行結果
This is converted to taple: (1, 2, 3)

これを先ほどのように複数の文字に対してリスト化したものを出したりする時にはlist関数を用いれば良い

def list_making_3(*values):
    print(list(values))
list_making_3(1, 2, 3)
# 実行結果
[1, 2, 3]

こんな感じでもできる。いろいろ試してみることが大切です。

辞書化

先ほどはタプル化について説明してきた。今度は辞書化である。先ほどの*ではなく**を用いることによってできるものである。そして今回の引数はキーワード引数を用いる。

def dic_making(**values):
    print(values)
dic_making(a=1, b=2, c=3)
# 実行結果
{'a': 1, 'b': 2, 'c': 3}

docstring

これはとても便利なもので、他人が作った関数は瞬時にわかるわけではないし、難しい関数になってくると分からない時もあり、作業が効率的に進まなくなることが多いであろう。その時にdocstringを用いることによって説明がつけられる。いわば関数のコメントのようなものである。例を示してみよう。

def dic_making(**values):
    'この関数はキーワード変数から辞書を作ることができる関数である。'
    print(values)

関数のdocstringを表すためにはhelp関数を用いる。もしくはdocstringだけを示したい時は、『.doc』を用いる。

help(dic_making)
print('##############\n')

print(dic_making.__doc__)
# 実行結果
dic_making(**values)
    この関数はキーワード変数から辞書を作ることができる関数である

##############

この関数はキーワード変数から辞書を作ることができる関数である
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?