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?

【Python初心者】print()関数の基本と活用まとめ

Posted at

Pythonの標準出力に使われる print() 関数について、自分の学習内容を整理するためにまとめました。基本的な構文からよく使うオプション、応用的な使い方まで記載しています。

✅ 基本構文

print(値1, 値2, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
引数 説明
値1, 値2, ... 出力したい値。複数指定可能。
sep 値と値の間に挟む文字列。デフォルトは半角スペース ' '
end 出力の最後に追加される文字列。デフォルトは改行文字 '\n'
file 出力先。デフォルトは標準出力 sys.stdout
flush Trueにすると出力バッファをすぐにフラッシュする。デフォルトは False。

🧪 基本の使い方とオプション

① 単純な出力

print("Hello, world!")
# 出力: Hello, world!

② 複数の値を出力(スペース区切り)

print("Python", 3, "rocks")
# 出力: Python 3 rocks

③ sep オプション(区切り文字の変更)

print("2025", "05", "11", sep="-")
# 出力: 2025-05-11

④ end オプション(出力の末尾変更)

print("Hello", end="")
print("World")
# 出力: HelloWorld

⑤ file オプション(ファイルに出力)

with open("log.txt", "w") as f:
    print("ファイルに書き込みます", file=f)

⑥ flush オプション(即時出力)

import time
for i in range(3):
    print(i, end=" ", flush=True)
    time.sleep(1)

💡 その他のポイント

print() は戻り値として None を返します。つまり、何も返しません。

例えば次のようになります:

result = print("Hello")
print(result)
# 出力:
# Hello
# None

print("Hello") の出力は画面に表示されますが、関数としての戻り値は None なので、result に代入されるのは None です。

そのため、print() の結果を変数に入れてさらに処理をしようとするとエラーになります:

# ❌ エラーになる例
result = print("Hi").upper()

このように、print() はあくまで「表示」だけを行う関数であり、値を返さないことを覚えておくと、エラーを防げます。

・引数で渡されたオブジェクトは、内部的に str() によって文字列に変換されて表示されます。

f文字列 を使うと、変数を埋め込んだ分かりやすい出力ができます。

name = "Alice"
age = 30
print(f"{name} is {age} years old.")
# 出力: Alice is 30 years old.

おわりに

print() 関数はデバッグやログ出力にも頻繁に使われるため、各オプションの使い方を知っておくと便利だと思いました。自分の理解を深めるために今後もよく使いながら慣れていきたいと思います。

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?