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 の変数定義とデータ型の基本【Day 4】

0
Last updated at Posted at 2025-12-03

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

変数ってなに?Python の変数定義とデータ型の基本

Python でプログラミングを始めるうえで、最初に理解しておきたいのが 変数データ型 です。
変数は「値を入れる箱」、データ型は「その箱の中に何が入っているか」を表します。

この記事では、初心者向けに変数の基本と、Pythonでよく使うデータ型について解説します。

1. 変数とは

変数とは「値を入れて名前をつける箱」のようなものです。

  • 名前をつける
  • 値を入れる
  • あとでその名前を使って値を取り出す

message = "Hello, Python"
number = 42
pi = 3.14

ここで、

  • message には文字列 "Hello, Python"
  • number には整数 42
  • pi には小数 3.14

が入っています。

2. 変数の書き方とルール

基本の書き方

変数名 = 値

name = "Alice"
age = 20
height = 165.5

変数名のルール

  • 英字、数字、アンダースコア(_)が使える
  • 数字で始めてはいけない
  • 空白は使えない
  • 大文字小文字は区別される(Namename は別)

3. Pythonの主なデータ型

Python の変数にはさまざまな型があります。よく使うものを紹介します。

3-1. 数値型(int, float)

x = 10      # 整数
y = 3.14    # 小数

3-2. 文字列型(str)

name = "Alice"
greeting = 'Hello'

3-3. ブール型(bool)

is_active = True
is_admin = False

4. 型を確認する方法

Python では type() 関数で変数の型を確認できます。

x = 10
y = 3.14
name = "Alice"

print(type(x))    # <class 'int'>
print(type(y))    # <class 'float'>
print(type(name)) # <class 'str'>

5. 変数の値を更新する

変数にはあとから別の値を代入できます。

score = 0
print(score)  # 0

score = 10
print(score)  # 10

型も自由に変えることができます(ただし注意が必要です)。

value = 5
value = "five"

6. 実際に動かしてみよう

VS Code または任意の .py ファイルに次のコードを書いて実行してください。

message = "Hello, Python"
number = 42
pi = 3.14
is_active = True

print(message)
print("number:", number)
print("pi:", pi)
print("is_active:", is_active)

出力例:

Hello, Python
number: 42
pi: 3.14
is_active: True

7. まとめ

  • 変数は「値を入れる箱」
  • 変数名にはルールがある
  • Python でよく使うデータ型は int, float, str, bool
  • type() で型を確認できる
  • 値はあとから自由に変更できる

次回 Day5 では、数値・文字列・ブール値の扱い方とよくあるエラー について解説します。

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?