LoginSignup
0
0

More than 3 years have passed since last update.

【Udemy Python3入門+応用】 48. 関数定義

Posted at

※この記事はUdemyの
現役シリコンバレーエンジニアが教えるPython3入門+応用+アメリカのシリコンバレー流コードスタイル
の講座を受講した上での、自分用の授業ノートです。
講師の酒井潤さんから許可をいただいた上で公開しています。

■関数を定義して呼び出す

◆基本
function
def say_something():
    print('hi')

# 定義したsay_something()を呼び出す
say_something()
result
hi

このとき、say_somethingの後ろに()をつけないといけない。

function
def say_something():
    print('hi')

f = say_something
f()
result
hi

このように別の変数に代入してから呼び出すことももちろん可能。

◆typeはどうなる?
function
def say_something():
    print('hi')

print(type(say_something))
result
<class 'function'>

typeは 'function' になっている。

◆返り値
function
def say_something():
    s = 'hi'
    return s

result = say_something()
print(result)
result
hi

ここでのsay_something()の中身は、
'hi'に代入し、
そのsを返す
というものになっている。

◆引数
result
def what_is_this(color):
    print(color)

what_is_this('red')
result
red
◆応用
function
# 引数に応じたオブジェクトをprintする
def what_is_this(color):
    if color == 'red':
        return 'tomato'
    elif color == 'green':
        return 'green pepper'
    else:
        return "I don't know."

result = what_is_this('red')
print(result)

result = what_is_this('green')
print(result)

result = what_is_this('blue')
print(result)
result
tomato
green pepper
I don't know.

このように、なんども同じ処理をする場合は、共通の部分を関数として定義し、
その関数を呼び出すようにするとよい。

0
0
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
0