0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

関数 def の基本:引数と戻り値【Day 18】

0
Last updated at Posted at 2025-12-17

Qiita Advent Calendar 2025 のパイソニスタの一人アドカレ Day18 の記事です。

関数 def の基本:引数と戻り値

コードが長くなると「同じ処理を何度も書く」ことが増えます。
そこで使うのが 関数(function) です。
Python では def を使って関数を定義します。

1. 関数を定義してみよう

■ 基本の形

def 関数名():
    実行したい処理

■ 最もシンプルな例

def hello():
    print("Hello!")

呼び出し:

hello()

2. 引数(ひきすう)を使う

引数とは「関数に渡す値」のことです。

def greet(name):
    print("Hello,", name)

greet("Alice")

出力:

Hello, Alice

複数の引数もOK:

def add(a, b):
    print(a + b)

add(3, 5)

3. 戻り値(return)を使う

関数の結果を呼び出し元に返したいときは return を使います。

def add(a, b):
    return a + b

result = add(3, 5)
print(result)
8

print と return の違い:

書き方 役割
print 画面に出すだけ
return 呼び出し元に結果を返す

4. 引数も戻り値もある関数の例

def full_name(first, last):
    return f"{first} {last}"

name = full_name("Taro", "Yamada")
print(name)

5. 今日のまとめ

  • def で関数を定義する
  • 引数:関数に渡す値
  • return:処理結果を返す(print とは役割が違う)
  • 関数を使うとコードが整理され、再利用しやすくなる

6. ミニ問題

Q1.
引数 x を受け取り、2 倍にして返す関数 double(x) を作ってください。

Q2.
firstlast を受け取り、"last first" 形式で返す関数を作ってみてください。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?