Python 関数の定義と呼び出しの使い方・サンプルコード

#関数定義
>>> def greeting():
...     print('おはようございます。')

#関数呼び出し
>>> greeting()
おはようございます。

#関数定義 with return
def greeting():
    s = 'おはようございます。'
    return s
result = greeting()
print(result)

#引数
def what_is_the_material(material):
    print(material)
what_is_the_material('raffia')

#引数 with if
def what_is_the_material(material):
    if material == 'raffia':
        return 'expensive'
    elif material == 'paper':
        return 'cheap'
    else:
        return 'oh my god'
result = what_is_the_material('paper')
print(result)

#関数の引数と返り値の宣言
def multiple_num(a:int, b:int) -> int:
    return a * b
print(multiple_num(100,2))


#引数2
def products(name, price, origin):
    print(name)
    print(price)
    print(origin)
products('raffia', '1000', 'Madagascar')

#引数3
def products(name, price, origin):
    print('name =',name)
    print('price =',price)
    print('origin =',origin)
products(name='raffia', price='1000', origin='Madagascar')

#デフォルト引数
def products(name='raffia', price='1000', origin='Madagascar'):
    print('name =',name)
    print('price =',price)
    print('origin =',origin)
products()
products(name='paper', price='100', origin='china')

#デフォルト引数に空のリスト(及び辞書型)を入れる場合

def some(x,l=None):
    if l is None:
        l = []
    l.append(x)
    return l

r = some(100)
print(r)
r = some(100)
print(r)

About TIER

TIERは、Global、DX、HRの3軸により 大手企業から中小企業、民間企業から行政まで、海外展開に必要なサービスをワンストップで支援しております。海外マーケティングセールスからデジタルマーケティング、多言語サイトや越境ECサイト制作等の海外向けクリエイティブ制作、グローバル人材採用支援まで幅広く対応しております。お気軽にお問い合わせください。

Check Also

python

Pythonメモ:while文のサンプルコード

繰り返し処理はfor文と今回の …