Python & AI Tutorials Logo
Python プログラミング

3. 変数と基本データ型

第 2 章では、テキストを出力したり、入力を受け取ったり、基本的な演算を行うシンプルなプログラムの書き方を学びました。ですが、そこには大きな制限がありました。そのプログラムは、後で使うために情報を保存したり、さまざまな種類のデータを洗練された方法で扱ったりすることができませんでした。この章では、Python が 変数 (variable)データ型 (data type) を使って情報を保存・管理する方法を学びます。

変数は、情報を入れておくラベル付きの容器だと考えてください。家の中の物を整理するためにラベル付きの箱を使うのと同じように、Python はプログラム内のデータを整理・管理するために変数を使います。ただし、すべてのデータが同じというわけではありません。数値はテキストとは根本的に異なり、Python は「どんな種類のデータを扱っているのか」を知る必要があります。そこで データ型 (data type) の出番です。

この章の終わりまでに、次のことが理解できるようになります。

  • 変数を正しく作成し、命名する方法
  • データ型とは何か、そしてなぜ重要なのか
  • 数値、テキスト、論理値を扱う方法
  • 異なるデータ型の間で変換する方法
  • Python が内部的にデータをどのように表現しているか

これらの概念は、Python で行うあらゆることの土台になります。そのため、この章では実践的な例をたくさん使いながら、じっくりと学んでいきます。

3.1) 変数の命名と作成

3.1.1) 変数とは何か、なぜ重要なのか

変数 (variable) は、コンピュータのメモリに保存された値を参照する名前です。変数を作成するということは、あるデータ片を指し示すラベルを作ることだと言えます。これにより、次のことが可能になります。

  1. プログラム内で後から使うために 情報を保存 する
  2. 同じ値を何度も 参照 でき、毎回書き直す必要がない
  3. プログラムの実行中に 値を更新 できる
  4. 生の値の代わりに意味のある名前を使うことで、コードを読みやすく できる

具体的な例を見てみましょう。変数を使わない場合、長方形の面積を計算したいときには次のように書くかもしれません。

python
# without_variables.py
print("Rectangle area:", 15 * 8)

これは動作しますが、これらの寸法を何度も使う必要がある場合はどうでしょうか。また、15 と 8 は何を表しているのでしょうか。変数を使うと、コードはよりわかりやすく、柔軟になります。

python
# with_variables.py
length = 15
width = 8
area = length * width
print("Rectangle area:", area)  # Output: Rectangle area: 120

これでコード自体が説明書きの役割を果たします。これを読めば、特定の寸法の長方形の面積を計算していることがすぐにわかります。寸法を変更したくなった場合も、先頭の変数への代入だけを更新すればよくなります。

3.1.2) 代入による変数の作成

Python では、代入演算子 (=) を使って変数を作成します。基本的な構文は次のとおりです。

python
variable_name = value

= 記号は数学的な意味での「等しい」ではありません。代わりに「右辺の値を左辺の名前に代入する」という意味になります。これは非常に重要な違いです。Python がこの文を見たときには、次のように処理します。

  1. = の右側の式を評価する
  2. 左側の変数名を新しく作成するか、更新する
  3. その名前が評価結果の値を参照するようにする

変数の作成例をいくつか見てみましょう。

python
# creating_variables.py
age = 25
temperature = 72.5
name = "Alice"
is_student = True
 
print(age)          # Output: 25
print(temperature)  # Output: 72.5
print(name)         # Output: Alice
print(is_student)   # Output: True

各変数がどの種類のデータを格納するのかを宣言する必要がないことに注目してください。Python は、代入された値から自動的に型を判断します。これは 動的型付け (dynamic typing) と呼ばれ、Python をとても柔軟で使いやすくしています。

また、複数代入 (multiple assignment) を使って、1 行で複数の変数を作成することもできます。

python
# multiple_assignment.py
x, y, z = 10, 20, 30
print(x)  # Output: 10
print(y)  # Output: 20
print(z)  # Output: 30
 
# You can even assign the same value to multiple variables
a = b = c = 100
print(a, b, c)  # Output: 100 100 100

最初の形式(タプルのアンパック (tuple unpacking) と呼ばれます—タプルについては第 14 章で学びます)は、各値を順番に対応する変数へ代入します。2 つ目の形式は、同じ値を 3 つの変数すべてに代入します。

3.1.3) 変数名のルールと慣習

Python には、有効な変数名の条件に関する明確なルールがあります。中には 必須のルール(必ず守らなければならないもの)もあれば、慣習(コードを読みやすくし、他の Python コードと一貫性を保つためのガイドライン)もあります。

必須ルール(必ず守る必要があるもの):

  1. 先頭は英字 (a-z, A-Z) かアンダースコア (_) で始まること: 変数名は数字で始めることはできません。
  2. 英字、数字、アンダースコアを含められること: 先頭以降には、英字・数字・アンダースコアを任意に組み合わせて使えます。
  3. スペースや特殊文字を含めないこと: スペース、ハイフン、大半の記号は使えません。
  4. Python のキーワードではないこと: if, for, while, def など、一部の単語は Python が自分自身のために予約しています。
  5. 大文字と小文字を区別すること: age, Age, AGE は 3 つの別々の変数です。

有効な変数名と無効な変数名の例を見てみましょう。

python
# valid_names.py
# Valid variable names
user_age = 30
firstName = "John"
total_2024 = 1000
_private = "hidden"
x = 5
MAX_SIZE = 100
 
# Invalid variable names (these will cause errors)
# 2nd_place = "silver"      # Error: starts with digit
# user-name = "alice"       # Error: contains hyphen
# total amount = 500        # Error: contains space
# class = "Python 101"      # Error: 'class' is a keyword

慣習(可読性のために従うべきもの):

  1. 通常の変数には小文字とアンダースコアを使う: このスタイルは snake_case と呼ばれ、Python で標準的な書き方です。

    python
    user_age = 25
    total_price = 99.99
    is_valid = True
  2. 定数には大文字 (UPPERCASE) を使う: 実行中に変わらないことが前提の値に使います。

    python
    MAX_ATTEMPTS = 3
    PI = 3.14159
    DEFAULT_COLOR = "blue"
  3. 意味のある名前を使う: 変数名から、その変数が何を表しているのかが明確にわかるようにします。

    python
    # Good: clear and descriptive
    student_count = 30
    average_temperature = 72.5
     
    # Poor: unclear abbreviations
    sc = 30
    avg_tmp = 72.5
     
    # Poor: too generic
    x = 30
    data = 72.5
  4. 特別な場合を除き、一文字の名前は避ける: i, j, k のような一文字の名前は、ループ (loop) のカウンタ(第 11 章で学びます)や、x, y, z のような座標として使う場合は許容されますが、それ以外では意味のある名前を使いましょう。

  5. 組み込み関数と同じ名前を使わない: Python はそれを許してはいますが、list, str, int, print など、組み込み関数の名前を変数名に使うのは避けてください。

よい命名規則を実際に示した例を見てみましょう。

python
# good_naming.py
# Constants at the top
SALES_TAX_RATE = 0.08
DISCOUNT_THRESHOLD = 100
 
# Descriptive variable names
item_price = 75.00
quantity = 3
subtotal = item_price * quantity
 
# Clear boolean variable
qualifies_for_discount = subtotal >= DISCOUNT_THRESHOLD
 
if qualifies_for_discount:
    discount = subtotal * 0.10
    subtotal = subtotal - discount
    print("Discount applied: $", discount)
 
tax = subtotal * SALES_TAX_RATE
total = subtotal + tax
 
print("Subtotal: $", subtotal)
print("Tax: $", tax)
print("Total: $", total)
# Output:
# Subtotal: $ 202.5
# Tax: $ 16.2
# Total: $ 218.7

変数名のおかげで、コメントがなくてもコードの意味がわかることに注目してください。プログラムが何を計算しているのかが読み取れます。

3.1.4) 式の中で変数を使う

一度変数を作成すれば、その変数が表す値を使う場面ならどこでも利用できます。Python は式を評価するときに、自動的に変数の現在の値を代入してくれます。

python
# using_variables.py
# Create some variables
hours_worked = 40
hourly_rate = 25.50
 
# Use variables in calculations
gross_pay = hours_worked * hourly_rate
print("Gross pay:", gross_pay)  # Output: Gross pay: 1020.0
 
# Use variables in other expressions
bonus = gross_pay * 0.10
total_pay = gross_pay + bonus
print("Total with bonus:", total_pay)  # Output: Total with bonus: 1122.0
 
# Use variables in strings (we'll learn more about this in Chapter 5)
message = "You worked " + str(hours_worked) + " hours"
print(message)  # Output: You worked 40 hours

変数は、第 2 章で学んだ関数とも組み合わせて使えます。

python
# variables_with_functions.py
name = input("What is your name? ")
age = input("What is your age? ")
 
greeting = "Hello, " + name + "!"
print(greeting)
 
age_next_year = int(age) + 1
print("Next year you will be", age_next_year, "years old.")
# If user enters "Alice" and "25":
# Output: Hello, Alice!
# Output: Next year you will be 26 years old.

この例は、重要な概念も示しています。input() 関数は常にテキスト(文字列 (string))を返すので、数値として扱いたい場合は、まず数値に変換する必要があります。この変換プロセスについては、この章の後半(3.7 節)で詳しく説明します。

3.2) 変数の代入と再代入

3.2.1) 代入の理解

値を変数に代入すると、Python は変数名とメモリ上の値との関連付けを作ります。ここで重要なのは、変数が物理的な意味で値を「中に含んでいる」わけではない、という点です。むしろ、メモリのどこかに保存された値を 参照 (refer) したり、指し示したり (point) している名前だと考えるべきです。

これは、値が入った箱に貼り付けられた「ラベル付きの付箋」のようなものだと思ってください。変数(付箋)は値そのものではなく、「どの箱に値が入っているか」を指し示しているだけです。変数を再代入するというのは、付箋を別の箱に貼り替えて別の値を指し示すようにすることであり、元の箱の中身を書き換えることではありません。

この区別は、再代入の話をするときに重要になります。代入・再代入時に何が起きているか見てみましょう。

python
# assignment_basics.py
x = 10
print(x)  # Output: 10
 
# Reassign x to a new value
x = 20
print(x)  # Output: 20
 
# The old value (10) is gone; x now refers to 20

ここで起きていることをステップごとに見てみます。

  1. x = 10: Python はメモリに整数 10 を作成し、その値を x という名前が参照するようにします。
  2. print(x): Python は x が参照しているもの(10)を調べ、それを出力します。
  3. x = 20: Python はメモリに整数 20 を作成し、今度は x がこの新しい値を参照するようにします。
  4. print(x): Python は x が参照しているもの(今は 20)を調べ、それを出力します。

元の値 10 はメモリ上にはしばらく残っていますが、どの変数からも参照されなくなったので、Python の自動メモリ管理機構(ガーベジコレクション (garbage collection) と呼ばれます)が、いずれそれを回収します。

3.2.2) 再代入と変数の更新

プログラミングで最もよく使うパターンのひとつが、「現在の値に基づいて変数を更新する」ことです。たとえば、カウンタを増やしたり、合計値を更新したり、ある計算に基づいて値を変更したりするときです。

python
# updating_variables.py
score = 0
print("Initial score:", score)  # Output: Initial score: 0
 
# Add 10 points
score = score + 10
print("After first update:", score)  # Output: After first update: 10
 
# Add 5 more points
score = score + 5
print("After second update:", score)  # Output: After second update: 15
 
# Double the score
score = score * 2
print("After doubling:", score)  # Output: After doubling: 30

score = score + 10 の中で何が起きているのかを分解してみます。

  1. Python は右辺 score + 10 を評価します。
  2. 現在の score の値(0)を調べます。
  3. 0 + 10 を計算し、10 を得ます。
  4. この新しい値(10)を score に代入します。
  5. これで score は 0 ではなく 10 を参照するようになります。

このパターンは非常によく使われるため、Python ではこれを短く書ける「複合代入演算子」が用意されています(これについては第 4 章 3 節で学びます)。ただし、今の段階では、この完全な形を理解することが重要です。なぜなら、ここには「まず右辺を完全に評価し、それから左辺に代入する」という処理の順序がはっきりと現れているからです。

3.2.3) 変数同士は独立している

ある変数を別の変数に代入するとき、Python は(数値や文字列のような単純な型に関しては)値そのものではなく「参照」をコピーします。ただし、この章で扱う基本的な型については、代入後は変数同士が独立して振る舞います。

python
# independent_variables.py
a = 10
b = a  # b now refers to the same value as a (10)
print("a:", a)  # Output: a: 10
print("b:", b)  # Output: b: 10
 
# Change a
a = 20
print("After changing a:")
print("a:", a)  # Output: a: 20
print("b:", b)  # Output: b: 10 (unchanged!)

b = a と書いたとき、b はその瞬間に a が参照していた値(10)を参照するようになります。その後で a を 20 を参照するように変更しても、b は影響を受けません。b は依然として 10 を参照し続けます。

この挙動は数値や文字列では直感的ですが、リスト (list) や辞書のようなコレクション型では、より複雑になります。Python のオブジェクトモデルと参照セマンティクスについては、第 17 章で詳しく解説します。

3.2.4) 代入前の変数を使う

初心者がよくやってしまう間違いのひとつが、値を代入する前の変数を使おうとすることです。このような場合、Python は NameError を発生させます。

python
# undefined_variable.py
print(total)  # Error: NameError: name 'total' is not defined

このエラーは、Python が total が何を指しているのか分からないために起こります。まだその変数を作成していないからです。解決策はシンプルで、使う前に変数へ値を代入しておけばよいのです。

python
# defined_variable.py
total = 0  # Initialize the variable first
print(total)  # Output: 0
 
# Now we can update it
total = total + 10
print(total)  # Output: 10

このように、変数を使う前に初期値を与えることを 初期化 (initialization) と呼びます。これはプログラミングにおいて基本となるパターンで、とくにループ (loop) の中でカウンタや合計値(アキュムレータ)を扱うときに頻繁に登場します(第 10 章で詳しく見ていきます)。

3.2.5) 変数の値を入れ替える

よく行われる操作のひとつに、2 つの変数の値を入れ替える、というものがあります。多くのプログラミング言語では、これには一時的な変数が必要です。

python
# swap_with_temp.py
x = 10
y = 20
print("Before swap: x =", x, ", y =", y)  # Output: Before swap: x = 10 , y = 20
 
# Swap using a temporary variable
temp = x    # Save x's value
x = y       # Put y's value in x
y = temp    # Put saved value in y
 
print("After swap: x =", x, ", y =", y)  # Output: After swap: x = 20 , y = 10

しかし、Python では 同時代入 (simultaneous assignment) を使った、よりエレガントな方法が用意されています。

python
# swap_pythonic.py
x = 10
y = 20
print("Before swap: x =", x, ", y =", y)  # Output: Before swap: x = 10 , y = 20
 
# Swap in one line
x, y = y, x
 
print("After swap: x =", x, ", y =", y)  # Output: After swap: x = 20 , y = 10

これは、Python が右辺全体(y, x)をどの代入よりも先に評価するから動作します。Python は、yx の値を含む一時的な構造を作り、その後でその値を順番に xy にアンパックして代入します。これは、「よく行う操作を簡潔かつ読みやすく書けるようにする」という Python の思想をよく表している例でもあります。

3.3) データ型の概念と type()

3.3.1) データ型とは何か

データ型 (data type)、あるいは単に 型 (type) とは、値がどのような種類のデータを表しているか、そしてその値に対してどのような操作が可能かを定義するものです。データ型は、Python がさまざまな種類の情報をどのように解釈し、扱うべきかを伝える「カテゴリ」と考えるとよいでしょう。

例えば次のようなものがあります。

  • 数値 42整数 (integer)(整数値)です。
  • 数値 3.14浮動小数点数 (floating-point number)(小数点を含む数値)です。
  • テキスト "Hello"文字列 (string)(文字の並び)です。
  • Trueブール値 (boolean)(真偽値)です。

データ型が重要なのは、型が異なればサポートされる操作も異なるからです。

python
# type_operations.py
# You can add numbers
result1 = 10 + 5
print(result1)  # Output: 15
 
# You can also "add" strings (concatenation)
result2 = "Hello" + " " + "World"
print(result2)  # Output: Hello World
 
# But you can't add a number and a string directly
# result3 = 10 + "5"  # Error: TypeError: unsupported operand type(s)

最後の例でエラーが起きるのは、Python が数値と文字列をどのように「足せばよいか」わからないためです。数値をテキストに変換して連結すべきなのか、それともテキストを数値に変換して数学的に足すべきなのか判断がつきません。Python は、どちらの解釈をすべきかをプログラマが明示的に指定することを求めます(片方の値をもう片方と同じ型に変換する必要があります。この方法は 3.7 節で学びます)。

3.3.2) type() を使ったデータ型の確認

Python には、値や変数がどの型に属しているかを教えてくれる組み込み関数 type() があります。これは、自分が扱っているデータを理解したり、問題をデバッグしたりするのに非常に便利です。

python
# checking_types.py
# Check types of literal values
print(type(42))        # Output: <class 'int'>
print(type(3.14))      # Output: <class 'float'>
print(type("Hello"))   # Output: <class 'str'>
print(type(True))      # Output: <class 'bool'>
 
# Check types of variables
age = 25
name = "Alice"
temperature = 98.6
is_valid = False
 
print(type(age))         # Output: <class 'int'>
print(type(name))        # Output: <class 'str'>
print(type(temperature)) # Output: <class 'float'>
print(type(is_valid))    # Output: <class 'bool'>

<class 'int'> という出力は、「この値は int というクラス(型)に属しています」という意味です。Python では、型は実際には「クラス」であり(クラスについては第 VIII 部で詳しく学びます)、今のところは「型」と「クラス」は同じものだと考えて構いません。

3.3.3) Python の動的型付け

Python は 動的型付け (dynamic typing) の言語です。これは次のような意味を持ちます。

  1. 変数には固定の型がない: ひとつの変数が、プログラムの実行中に異なる型の値を参照することができます。
  2. 型は実行時に決まる: Python は、コードを書いた時点ではなく、プログラムを実行したときに型を判断します。
  3. 型を明示的に宣言する必要がない: 他の言語とは異なり、「この変数は整数を格納します」と宣言する必要はありません。

動的型付けがどのように働くのか、例を見てみましょう。

python
# dynamic_typing.py
x = 42
print(x, "is of type", type(x))  # Output: 42 is of type <class 'int'>
 
x = "Hello"
print(x, "is of type", type(x))  # Output: Hello is of type <class 'str'>
 
x = 3.14
print(x, "is of type", type(x))  # Output: 3.14 is of type <class 'float'>

x が、プログラムのある時点では整数を参照し、次の時点では文字列を参照し、その次には浮動小数点数を参照していることがわかります。Python は何も文句を言わず、その都度 x が参照している値の型を更新します。

この柔軟性はとても便利ですが、注意も必要です。数値が入っていると思っていた変数に実は文字列が入っていた場合、思わぬエラーが起きてしまうかもしれません。

python
# type_confusion.py
value = "100"  # This is a string, not a number!
 
# Trying to do math with it will fail
# result = value + 50  # Error: TypeError: can only concatenate str to str
 
# You need to convert it first
result = int(value) + 50
print(result)  # Output: 150

だからこそ、データ型を理解することが非常に重要です。どの操作がうまくいくか、どんなときにエラーが発生するかを予測できるようになるからです。

3.3.4) Python の組み込み型の概要

Python にはいくつかの組み込みデータ型があります。この章では、その中でも最も基本的なものに焦点を当てます。

Python Built-in Types

Numeric Types

Text Type

Boolean Type

None Type

Collection Types

int: Integers

float: Decimal Numbers

complex: Complex Numbers

str: Text/Strings

bool: True/False

NoneType: None

list, tuple, dict, set...

この章では次の型を扱います。

  • int: 整数(小数点を含まない数値)
  • float: 浮動小数点数(小数点を含む数値)
  • str: 文字列(テキスト)
  • bool: ブール値(True と False)
  • NoneType: 特殊な値 None

complex(虚数成分を持つ数値)についても簡単に触れますが、日常的なプログラミングで使うことはあまりありません。コレクション型(リスト (list), タプル (tuple), 辞書, セットなど)は非常に重要なので、第 IV 部でそれぞれ一章ずつ割いて詳しく扱います。

3.3.5) 実践での型チェック

型の理解は、ユーザー入力や外部ソースから得たデータを扱うときにとくに重要になります。input() が、ユーザーが数値を入力しても常に文字列を返すことを思い出してください。

python
# input_types.py
user_input = input("Enter a number: ")
print("You entered:", user_input)
print("Type:", type(user_input))  # Output: Type: <class 'str'>
 
# Even if user types "42", it's still a string!
# To use it as a number, convert it:
number = int(user_input)
print("As a number:", number)
print("Type:", type(number))  # Output: Type: <class 'int'>
 
# Now we can do math with it
doubled = number * 2
print("Doubled:", doubled)

このプログラムを実行して 42 と入力すると、次のような出力になります。

Enter a number: 42
You entered: 42
Type: <class 'str'>
As a number: 42
Type: <class 'int'>
Doubled: 84

ここからわかる重要なポイントは、見た目が似ていても "42"(文字列)と 42(整数)は Python にとっては別物だということです。文字列は 2 つの文字('4' と '2')の並びであり、整数は数学的な演算に使える数値です。

3.4) 整数と浮動小数点数

3.4.1) 整数 (int)

整数 (integer)(型 int)は、小数点を持たない整数値です。整数は正の数、負の数、ゼロを含み、Python 3 では理論上どれだけ大きくても扱えるようになっています(実際にはコンピュータのメモリ量によって制限されます)。

python
# integers.py
# Positive integers
age = 25
year = 2024
population = 8000000000
 
# Negative integers
temperature = -15
debt = -5000
 
# Zero
balance = 0
 
# Very large integers (Python handles these easily)
huge_number = 123456789012345678901234567890
print(huge_number)  # Output: 123456789012345678901234567890
print(type(huge_number))  # Output: <class 'int'>

Python では、大きな数値を読みやすくするためにアンダースコア _ を使って区切りを入れることができます。アンダースコアは Python によって無視されますが、人間にとっては数字の読み取りがずっと簡単になります。

python
# readable_numbers.py
# These are all the same number
million = 1000000
million = 1_000_000  # Much easier to read!
 
# Works with any size
population = 8_000_000_000
national_debt = 31_000_000_000_000
 
print(million)      # Output: 1000000 (underscores not shown in output)
print(population)   # Output: 8000000000

また、特別なプレフィックスを使って、異なる基数(基数表現)の整数を書くこともできます。

python
# number_bases.py
# Binary (base 2) - prefix 0b
binary = 0b1010  # This is 10 in decimal
print(binary)  # Output: 10
 
# Octal (base 8) - prefix 0o
octal = 0o12  # This is 10 in decimal
print(octal)  # Output: 10
 
# Hexadecimal (base 16) - prefix 0x
hexadecimal = 0xFF  # This is 255 in decimal
print(hexadecimal)  # Output: 255

これらの別の基数表現は、Web デザインで色を扱うときや、低レベルのプログラミングなど特定の場面で役に立ちますが、日常的なプログラミングでは通常の 10 進整数を使うことがほとんどです。

3.4.2) 浮動小数点数 (float)

浮動小数点数 (floating-point number)(型 float)は、小数点を含む数値です。float は「実数」を表すために使われます。つまり、必ずしも整数でない値を扱うための型です。

python
# floats.py
# Numbers with decimal points
price = 19.99
temperature = 98.6
pi = 3.14159
 
# Very small numbers
electron_mass = 0.00000000000000000000000000000091093837
 
# Very large numbers
speed_of_light = 299792458.0
 
print(price)           # Output: 19.99
print(temperature)     # Output: 98.6
print(electron_mass)   # Output: 9.1093837e-31 (scientific notation)
print(speed_of_light)  # Output: 299792458.0

非常に小さい値や非常に大きい浮動小数点数は、科学技術表記 (scientific notation)(指数表記)で表示されることに注目してください。9.1093837e-31 という表記は、「9.1093837 × 10⁻³¹」、すなわち「9.1093837 を 10 の 31 乗で割った値」を意味します。

浮動小数点数は、科学技術表記を使って直接書くこともできます。

python
# scientific_notation.py
# These are equivalent
avogadro = 602214076000000000000000.0
avogadro = 6.02214076e23  # Much more readable!
 
# Small numbers
planck = 0.000000000000000000000000000000000662607015
planck = 6.62607015e-34  # Much more readable!
 
print(avogadro)  # Output: 6.02214076e+23
print(planck)    # Output: 6.62607015e-34

ここでの e(または E)は「指数 (exponent)」を表します。e の後の数値は、小数点を何桁動かすかを示します(正なら右へ、負なら左へ動かします)。

3.4.3) 整数と float の違い

整数も浮動小数点数も数値を表しますが、いくつか重要な違いがあります。

1. 精度と表現

整数は 厳密 (exact) です。値 42 は、誤差なく完全に 42 です。それに対して、浮動小数点数はコンピュータが 2 進数で小数を表現する仕組み上、近似値 (approximation) になります。

python
# float_precision.py
# This might surprise you!
result = 0.1 + 0.2
print(result)  # Output: 0.30000000000000004
 
# The result isn't exactly 0.3 due to floating-point representation
print(result == 0.3)  # Output: False

これはバグではなく、コンピュータが小数を表現する方式による根本的な制約です。この点については、第 4 章 10 節でより詳しく説明しますが、今は「float の計算結果は完全に正確でないことがある」と知っておけば十分です。

2. 演算と結果の型

整数と浮動小数点数の演算では、Python は特定のルールに従います。

python
# int_float_operations.py
# Integer operations
int_result = 10 + 5
print(int_result, type(int_result))  # Output: 15 <class 'int'>
 
# Float operations
float_result = 10.0 + 5.0
print(float_result, type(float_result))  # Output: 15.0 <class 'float'>
 
# Mixed operations: result is always float
mixed_result = 10 + 5.0
print(mixed_result, type(mixed_result))  # Output: 15.0 <class 'float'>
 
# Division always returns float, even with integers
division_result = 10 / 5
print(division_result, type(division_result))  # Output: 2.0 <class 'float'>

重要なルールは、「少なくとも一方が float の演算の結果は必ず float になる」というものです。float のほうがより広い範囲(小数も含む)を表現できるため、Python は結果をより一般的な型に「昇格」させます。

3. メモリとパフォーマンス

整数は float に比べてメモリ使用量が少なく、計算も速いです。ほとんどのプログラムではこの差は気になりませんが、大規模なデータや性能がシビアなアプリケーションでは重要になることがあります。

3.4.4) int と float の使い分け

整数と浮動小数点数をどのように使い分ければよいか、実践的な指針を挙げます。

整数を使うべき場面:

  • 個数を数えるとき(人、物、繰り返し回数など)
  • 分割できない量を表すとき(学生数、クリック数など)
  • シーケンスのインデックスや位置を扱うとき
  • 厳密な計算が必要なとき
python
# use_integers.py
student_count = 30  # Can't have 30.5 students
page_number = 42    # Can't be on page 42.7
loop_counter = 0    # Counting iterations

浮動小数点数を使うべき場面:

  • 測定値を表すとき(温度、距離、重さなど)
  • 金額を扱うとき(ただし精度には注意が必要です—第 4 章で扱います)
  • 比率、パーセンテージ、平均値を計算するとき
  • ある程度の近似で問題ないとき
python
# use_floats.py
temperature = 72.5     # Temperature can be fractional
price = 19.99          # Money amounts have cents
average_score = 87.3   # Averages are often fractional
percentage = 0.15      # 15% as a decimal

3.5) 文字列リテラルとブールリテラル(簡単なプレビュー)

この節では、もう 2 つの基本的なデータ型である文字列とブール値を簡単に紹介します。文字列については第 5 章と第 6 章で、ブール値については第 7 章で詳しく扱いますが、簡単なプログラムを書くためにも今の段階で基本を押さえておく必要があります。

3.5.1) 文字列の基本

文字列 (string)(型 str)は文字の並び、つまりテキストを表します。文字列はテキストを引用符で囲むことで作成します。Python では、シングルクォート (') とダブルクォート (") のどちらも使えます。

python
# string_basics.py
# Single quotes
name = 'Alice'
message = 'Hello, World!'
 
# Double quotes (exactly equivalent)
name = "Alice"
message = "Hello, World!"
 
# Print them
print(name)     # Output: Alice
print(message)  # Output: Hello, World!
print(type(name))  # Output: <class 'str'>

シングルクォートとダブルクォートは機能的にはまったく同じです。どちらを使うかは好みで構いませんが、コード内では一貫させるのがよいでしょう。多くの Python プログラマは、他の言語で一般的なこともありダブルクォートを好みますが、シングルクォートでも同様に問題ありません。

両方ある理由は? 主な理由は、文字列の中に引用符を含めたいときに便利だからです。

python
# quotes_in_strings.py
# Use double quotes when string contains single quotes
sentence = "It's a beautiful day!"
print(sentence)  # Output: It's a beautiful day!
 
# Use single quotes when string contains double quotes
speech = 'She said, "Hello!"'
print(speech)  # Output: She said, "Hello!"
 
# Or use escape sequences (we'll learn more in Chapter 5)
sentence = 'It\'s a beautiful day!'  # \' means a literal single quote
speech = "She said, \"Hello!\""     # \" means a literal double quote

文字列は、何も文字を含まない 空文字列 である場合もあります。

python
# empty_string.py
empty = ""
also_empty = ''
 
print(empty)            # Output: (nothing—it's empty!)
print(len(empty))       # Output: 0 (we'll learn about len() later)
print(type(empty))      # Output: <class 'str'>

+ 演算子を使って文字列同士を結合する(連結 (concatenation) する)ことができます。

python
# string_concatenation.py
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)  # Output: John Doe
 
# Be careful: you can't concatenate strings and numbers directly
age = 25
# message = "I am " + age + " years old"  # Error: TypeError
 
# Convert the number to a string first
message = "I am " + str(age) + " years old"
print(message)  # Output: I am 25 years old

文字列については、第 5 章と第 6 章で、エスケープシーケンス、文字列メソッド、フォーマット、テキスト処理などを詳しく学びます。今のところは、「文字列はテキストを表し、引用符で作成する」という点を覚えておいてください。

3.5.2) ブール値の基本

ブール値 (boolean)(型 bool)は、論理値を表す型で、TrueFalse のどちらか一方だけを取ります。これらが Python における唯一のブール値であり、論理演算において真か偽かを表すために使われます。

python
# boolean_basics.py
# Boolean literals
is_sunny = True
is_raining = False
 
print(is_sunny)         # Output: True
print(is_raining)       # Output: False
print(type(is_sunny))   # Output: <class 'bool'>

重要: ブール値 TrueFalse は、ここに書かれているとおりの大文字・小文字で書く必要があります。Python は大文字・小文字を区別するので、true, TRUE, false, FALSE といった書き方は使えません。

python
# boolean_case.py
correct = True    # Correct
# wrong = true    # Error: NameError: name 'true' is not defined
# wrong = TRUE    # Error: NameError: name 'TRUE' is not defined

ブール値は通常、比較論理演算 の結果として得られます。

python
# boolean_from_comparisons.py
age = 25
 
# Comparison operators produce boolean results
is_adult = age >= 18
print(is_adult)  # Output: True
 
is_senior = age >= 65
print(is_senior)  # Output: False
 
# You can use booleans in conditions (we'll learn more in Chapter 8)
if is_adult:
    print("You can vote!")  # Output: You can vote!
 
if is_senior:
    print("You get a senior discount!")  # (no output—condition is False)

ブール値を返す代表的な比較演算子は次のとおりです。

  • == : 等しい
  • != : 等しくない
  • < : より小さい
  • > : より大きい
  • <= : 以下
  • >= : 以上
python
# comparison_operators.py
x = 10
y = 20
 
print(x == y)   # Output: False (10 is not equal to 20)
print(x != y)   # Output: True (10 is not equal to 20)
print(x < y)    # Output: True (10 is less than 20)
print(x > y)    # Output: False (10 is not greater than 20)
print(x <= 10)  # Output: True (10 is less than or equal to 10)
print(y >= 20)  # Output: True (20 is greater than or equal to 20)

重要な注意: =(代入)と ==(比較)を混同しないでください。

  • x = 10 は「x に 10 を代入する」という意味です。
  • x == 10 は「x が 10 と等しいかどうかを調べる」という意味で、True か False を返します。
python
# assignment_vs_comparison.py
x = 10        # Assignment: x now refers to 10
result = (x == 10)  # Comparison: is x equal to 10?
print(result)  # Output: True
 
# This is a common mistake for beginners:
# if x = 10:  # Error: SyntaxError (can't use assignment in if condition)
if x == 10:   # Correct: comparison
    print("x is 10")  # Output: x is 10

ブール値については、第 7 章で and, or, not といった論理演算子や、真値性・偽値性、条件式におけるブール値の使われ方などを詳しく学びます。今のところは、「ブール値は True/False を表し、多くの場合比較の結果として得られる」という点を覚えておきましょう。

3.5.3) 実際の場面での文字列とブール値

文字列とブール値がどのように一緒に使われるか、簡単な例で見てみましょう。

python
# strings_booleans_example.py
# Get user input
name = input("What is your name? ")
age_input = input("What is your age? ")
 
# Convert age to integer
age = int(age_input)
 
# Create boolean conditions
is_adult = age >= 18
is_child = age < 13
 
# Build messages using strings
if is_adult:
    status = "adult"
else:
    status = "minor"
 
# Combine everything in output
print("Hello, " + name + "!")
print("You are an " + status + ".")
 
if is_child:
    print("You are a child.")
 
# When user enters "Alice" and "16":
# Output: Hello, Alice!
# Output: You are a minor.

この例では、さまざまなデータ型が一緒に使われています。テキストには文字列、年齢には整数、論理的な判定にはブール値が使われています。異なる型が互いに関係しながら動作するこの仕組みは、あらゆるプログラミングの基本です。

3.6) None 値とその用途

3.6.1) None とは何か

Python には None という特別な値があります(型は NoneType)。これは値が存在しないことを表します。Python における「ここには何もない」「まだ値がない」を表現する方法です。

python
# none_basics.py
result = None
print(result)        # Output: None
print(type(result))  # Output: <class 'NoneType'>

None は、ゼロや空文字列、False とは異なります。これらとは別の「特別な値」であり、「値がない」という意味を持ちます。

python
# none_vs_others.py
x = None
y = 0
z = ""
w = False
 
print(x)  # Output: None
print(y)  # Output: 0
print(z)  # Output: (empty—nothing prints)
print(w)  # Output: False
 
# They're all different types
print(type(x))  # Output: <class 'NoneType'>
print(type(y))  # Output: <class 'int'>
print(type(z))  # Output: <class 'str'>
print(type(w))  # Output: <class 'bool'>

3.6.2) None が使われる場面

None は、よくあるいくつかの場面で登場します。

1. 後で値を代入するためのプレースホルダとして

python
# none_placeholder.py
# Initialize variables that will be assigned later
user_name = None
user_age = None
 
# Later in the program, after getting user input:
user_name = input("Enter your name: ")
user_age = int(input("Enter your age: "))
 
print("Name:", user_name)
print("Age:", user_age)

2. 値を明示的に返さない関数のデフォルト戻り値として

第 19 章で学ぶ「関数 (function)」は、値を返すことができます。関数が明示的に何も返さない場合、Python は自動的に None を返します。

python
# none_from_function.py
# The print() function returns None
result = print("Hello!")  # Output: Hello!
print(result)             # Output: None
print(type(result))       # Output: <class 'NoneType'>

一見変に思えるかもしれませんが、これは便利です。「意味のある値がない」ときにも、必ず何かを返すようになるからです。

3. 任意の情報や欠損したデータを表すために

python
# none_optional.py
# Representing optional middle name
first_name = "John"
middle_name = None  # No middle name
last_name = "Doe"
 
if middle_name is None:
    full_name = first_name + " " + last_name
else:
    full_name = first_name + " " + middle_name + " " + last_name
 
print(full_name)  # Output: John Doe

3.6.3) None を調べる

ある値が None かどうかを調べるには、== ではなく is 演算子を使います。

python
# checking_none.py
value = None
 
# Correct way: use 'is'
if value is None:
    print("Value is None")  # Output: Value is None
 
# Also correct: use 'is not'
if value is not None:
    print("Value has a value")
else:
    print("Value is None")  # Output: Value is None
 
# While == works, 'is' is preferred for None
if value == None:  # This works but is not idiomatic Python
    print("Value is None")  # Output: Value is None

なぜ == ではなく is を使うのでしょうか。is 演算子は、2 つの名前がメモリ上のまったく同じオブジェクトを参照しているかどうかを調べます(これについては第 17 章で詳しく学びます)。None は Python 全体でただひとつだけ存在する特別なオブジェクトなので、is を使うほうが効率的かつ正確です。is None という書き方は、Python で標準的なイディオムです。

3.6.4) 実用場面での None

実際のプログラムで None がどのように役立つか、もう少し現実的な例を見てみましょう。

python
# none_practical.py
# Simulate looking up a user's age
# (In real programs, we'd use functions and dictionaries from later chapters)
 
user_name = input("Enter a name (Alice, Bob, or Charlie): ")
 
# Check each name and assign age or None
if user_name == "Alice":
    user_age = 25
elif user_name == "Bob":
    user_age = 30
elif user_name == "Charlie":
    user_age = 35
else:
    user_age = None  # User not found
 
# Check if we found the user
if user_age is not None:
    print(user_name, "is", user_age, "years old")
else:
    print(user_name, "not found")
 
# When user enters "Alice":
# Output: Alice is 25 years old
# When user enters "David":
# Output: David not found

この例では、None が「ユーザーが見つからなかった」という意味を明確に表しています。これは、「年齢が 0 のユーザーが見つかった」という意味とはまったく違います(0 歳は新生児として妥当な年齢です)。

3.6.5) None と空の値の違い

None と「空の値」を区別することは大切です。

python
# none_vs_empty.py
# These are all different
nothing = None
zero = 0
empty_string = ""
# Note: We'll learn about lists in Chapter 13
# empty_list = []
 
print(nothing is None)       # Output: True
print(zero is None)          # Output: False
print(empty_string is None)  # Output: False
 
# None means "no value"
# 0 means "the number zero"
# "" means "text with no characters"

それぞれが違う意味を持ちます。

  • None: 値が存在しないことを表す
  • 0: 数値としてのゼロという特定の値
  • "": 存在するが、中身の文字数が 0 の文字列

この違いを理解しておくことで、より明確で正しいプログラムを書けるようになります。

3.7) int(), float(), str() による基本的な型変換

3.7.1) なぜ型変換が必要なのか

これまで見てきたとおり、Python には「どの型同士ならどの操作ができるか」という厳格なルールがあります。数値と文字列を足したり、文字列に float を掛けたり、テキストに対して直接数値演算を行ったりすることはできません。ある値を別の型として使いたいときには、明示的に変換 (conversion) する必要があります。

型変換(型キャスト (type casting) とも呼ばれます)は、ある型の値を別の型に変える処理です。Python には、よく使う変換のための組み込み関数が用意されています。

  • int(): 整数に変換する
  • float(): 浮動小数点数に変換する
  • str(): 文字列に変換する

それぞれについて、詳しく見ていきましょう。

3.7.2) int() による整数への変換

int() 関数は、値を整数に変換します。主な使い方は次のとおりです。

float から整数への変換:

python
# float_to_int.py
# int() truncates (cuts off) the decimal part
x = int(3.14)
y = int(3.99)
z = int(-2.7)
 
print(x)  # Output: 3 (not 4—it doesn't round!)
print(y)  # Output: 3 (not 4—it truncates!)
print(z)  # Output: -2 (truncates toward zero)

重要: int() は四捨五入をしません。小数部分を単に切り捨て(0 に向かって切り詰め)ます。このため、int(3.9) が 4 を返すと思っていると、初心者は戸惑うことが多いです。

文字列から整数への変換:

これはユーザー入力を扱うときに非常によく使われます。

python
# string_to_int.py
# Convert string containing a number
age_str = "25"
age_int = int(age_str)
 
print(age_str, type(age_str))  # Output: 25 <class 'str'>
print(age_int, type(age_int))  # Output: 25 <class 'int'>
 
# Now we can do math with it
next_year = age_int + 1
print("Next year:", next_year)  # Output: Next year: 26
 
# Practical example with input()
user_age = int(input("Enter your age: "))
print("In 10 years, you'll be", user_age + 10)

変換できない場合はどうなるか?

整数として解釈できない文字列を変換しようとすると、Python は ValueError を発生させます。

python
# invalid_int_conversion.py
# These work
print(int("123"))    # Output: 123
print(int("-456"))   # Output: -456
print(int("  789 ")) # Output: 789 (whitespace is ignored)
 
# These don't work
# print(int("12.5"))   # Error: ValueError: invalid literal for int()
# print(int("hello"))  # Error: ValueError: invalid literal for int()
# print(int("12 34"))  # Error: ValueError: invalid literal for int()

こうしたエラーを安全に扱う方法については、第 27 章の例外処理で学びます。今は、「文字列を整数に変換する前に、その文字列が整数として妥当か確認する必要がある」と理解しておけば十分です。

ブール値から整数への変換:

ブール値も整数に変換できます。True1 に、False0 になります。

python
# bool_to_int.py
print(int(True))   # Output: 1
print(int(False))  # Output: 0
 
# This is sometimes useful in calculations
is_premium = True
is_student = False
 
# Calculate discount (10% for premium, 5% for students)
discount = int(is_premium) * 0.10 + int(is_student) * 0.05
print("Discount:", discount)  # Output: Discount: 0.1

ただし、ブール値を直接数値計算に利用するとコードの読みやすさが下がるため、一般的には推奨されません。この点については第 7 章でさらに説明します。

3.7.3) float() による浮動小数点数への変換

float() 関数は、値を浮動小数点数に変換します。

整数から float への変換:

python
# int_to_float.py
x = float(42)
y = float(-17)
z = float(0)
 
print(x, type(x))  # Output: 42.0 <class 'float'>
print(y, type(y))  # Output: -17.0 <class 'float'>
print(z, type(z))  # Output: 0.0 <class 'float'>

文字列から float への変換:

python
# string_to_float.py
# Convert string containing decimal number
price_str = "19.99"
price_float = float(price_str)
 
print(price_str, type(price_str))    # Output: 19.99 <class 'str'>
print(price_float, type(price_float))  # Output: 19.99 <class 'float'>
 
# Strings without decimal points work too
x = float("42")
print(x, type(x))  # Output: 42.0 <class 'float'>
 
# Scientific notation strings work
big = float("1.5e10")
print(big)  # Output: 15000000000.0

無効な変換:

int() と同様に、float() も不適切な文字列に対しては ValueError を発生させます。

python
# invalid_float_conversion.py
# These work
print(float("3.14"))      # Output: 3.14
print(float("  2.5  "))   # Output: 2.5 (whitespace ignored)
print(float("-0.5"))      # Output: -0.5
print(float("inf"))       # Output: inf (infinity)
 
# These don't work
# print(float("hello"))   # Error: ValueError
# print(float("1.2.3"))   # Error: ValueError

ブール値から float への変換:

python
# bool_to_float.py
print(float(True))   # Output: 1.0
print(float(False))  # Output: 0.0

3.7.4) str() による文字列への変換

str() 関数は、どんな値でもその文字列表現に変換します。

数値から文字列への変換:

python
# number_to_string.py
# Convert integer
age = 25
age_str = str(age)
print(age_str, type(age_str))  # Output: 25 <class 'str'>
 
# Convert float
price = 19.99
price_str = str(price)
print(price_str, type(price_str))  # Output: 19.99 <class 'str'>
 
# Now we can concatenate with other strings
message = "The price is $" + price_str
print(message)  # Output: The price is $19.99

これはメッセージを組み立てるときにとくに便利です。

python
# building_messages.py
name = "Alice"
age = 25
height = 5.6
 
# Without str(), this would cause an error
# message = "Name: " + name + ", Age: " + age  # Error!
 
# With str(), it works
message = "Name: " + name + ", Age: " + str(age) + ", Height: " + str(height)
print(message)  # Output: Name: Alice, Age: 25, Height: 5.6

ブール値から文字列への変換:

python
# bool_to_string.py
is_valid = True
is_error = False
 
print(str(is_valid))  # Output: True
print(str(is_error))  # Output: False
 
# Useful in messages
status = "Status: " + str(is_valid)
print(status)  # Output: Status: True

None から文字列への変換:

python
# none_to_string.py
value = None
value_str = str(value)
print(value_str)        # Output: None
print(type(value_str))  # Output: <class 'str'>
 
# The string "None" is different from the value None
print(value is None)      # Output: True
print(value_str is None)  # Output: False
print(value_str == "None")  # Output: True

3.7.5) 実践的な変換パターン

よくある変換パターンをまとめて示した例を見てみましょう。

python
# conversion_patterns.py
# Get user input (always strings)
name = input("Enter your name: ")
age_str = input("Enter your age: ")
height_str = input("Enter your height in feet: ")
 
# Convert to appropriate types
age = int(age_str)
height = float(height_str)
 
# Perform calculations
age_in_months = age * 12
height_in_inches = height * 12
 
# Convert back to strings for output
print("Hello, " + name + "!")
print("You are " + str(age_in_months) + " months old.")
print("Your height is " + str(height_in_inches) + " inches.")
 
# Alternative: use multiple arguments to print() (no conversion needed)
print("Hello,", name + "!")
print("You are", age_in_months, "months old.")
print("Your height is", height_in_inches, "inches.")
 
# When user enters "Alice", "25", and "5.5":
# Output: Hello, Alice!
# Output: You are 300 months old.
# Output: Your height is 66.0 inches.
# Output: Hello, Alice!
# Output: You are 300 months old.
# Output: Your height is 66.0 inches.

複数の引数を print() に渡す(カンマで区切る)と、print() が自動的に各値を文字列に変換し、間にスペースを挟んで表示してくれることに注目してください。これは、手動で str() を呼び出して文字列連結するよりも便利なことが多いです。

3.7.6) 型変換フローダイアグラム

よく行われる型変換を図で表すと、次のようになります。

float

int truncates

str

str

int

float

str

int

float

int

float

str

bool

型変換の要点:

  • int → float: 常に安全で、末尾に .0 が付きます。
  • float → int: 小数部分を切り捨てます(四捨五入ではありません)。
  • 任意の型 → str: 常に安全で、その値の文字列表現になります。
  • str → int/float: 文字列が有効な数値表現である場合にのみ成功します。
  • bool → int/float: True は 1/1.0、False は 0/0.0 になります。

3.7.7) よくある型変換のミス

初心者がやりがちな型変換のミスをいくつか挙げます。

ミス 1: ユーザー入力を変換し忘れる

python
# conversion_mistake1.py
# Wrong: trying to do math with string
age = input("Enter your age: ")
# next_year = age + 1  # Error: TypeError
 
# Right: convert first
age = int(input("Enter your age: "))
next_year = age + 1
print("Next year:", next_year)

ミス 2: 不要な変換をしてしまう

python
# conversion_mistake2.py
# Unnecessary: print() handles conversion automatically
age = 25
print("Age:", age)  # This works fine
 
# No need for:
print("Age:", str(age))  # Unnecessary str() conversion

ミス 3: 不正な文字列を変換しようとする

python
# conversion_mistake3.py
# This will crash if user enters non-numeric input
# age = int(input("Enter your age: "))  # Crashes on "twenty"
 
# We'll learn to handle this safely in Chapter 27

ミス 4: int() が四捨五入すると誤解する

python
# conversion_mistake4.py
# Wrong expectation: int() truncates, doesn't round
x = int(3.7)
print(x)  # Output: 3 (not 4!)
 
# If you want rounding, use round()
x = round(3.7)
print(x)  # Output: 4

3.8) str() と repr() による文字列表現の取得

3.8.1) str() と repr() の違い

Python には、オブジェクトの文字列表現を得るための 2 つの方法 str()repr() があります。一見似ていますが、目的が異なります。

  • str(): 人間が読みやすい「きれいな」文字列表現を作るためのもの
  • repr(): 開発者向けの、あいまいさのない「正式な」文字列表現を作るためのもの

数値のような単純な型では両者はたいてい同じですが、それ以外の型では大きく異なることがあります。

python
# str_vs_repr.py
# For numbers, they're usually the same
x = 42
print(str(x))   # Output: 42
print(repr(x))  # Output: 42
 
# For strings, they differ
text = "Hello"
print(str(text))   # Output: Hello
print(repr(text))  # Output: 'Hello' (includes quotes!)
 
# For strings with special characters, repr() shows escape sequences
message = "Hello\nWorld"
print(str(message))   # Output: Hello
                      #         World (newline is interpreted)
print(repr(message))  # Output: 'Hello\nWorld' (shows the \n literally)

3.8.2) str() を使う場面

str() は、最終的なユーザーに見せる読みやすい文字列がほしいときに使います。

python
# using_str.py
price = 19.99
quantity = 3
 
# Create user-friendly messages
message = "Total: $" + str(price * quantity)
print(message)  # Output: Total: $59.97
 
# str() is what print() uses automatically
print("Total: $", price * quantity)  # Output: Total: $ 59.97

str() は、人間にとって意味がわかりやすい出力を目指して設計されています。多少技術的な情報が失われる場合もありますが、可読性を優先します。print() を呼び出すと、Python は内部的に渡された値に str() を適用します。

3.8.3) repr() を使う場面

repr() は、あいまいさのない文字列表現が必要なとき、主にデバッグ用途で使います。

python
# using_repr.py
# Debugging: see exactly what's in a variable
text = "Hello\nWorld"
print("Debug info:", repr(text))  # Output: Debug info: 'Hello\nWorld'
 
# Compare two similar-looking strings
str1 = "42"
str2 = "42 "  # Has trailing space
 
print(str1)       # Output: 42
print(str2)       # Output: 42  (space not obvious)
print(repr(str1)) # Output: '42'
print(repr(str2)) # Output: '42 ' (space is visible!)

repr() は、通常の出力では見えない細かい違い(改行や空白など)も含めて、「Python がその値をどう見ているか」をそのまま表現してくれます。そのため、デバッグに非常に役立ちます。

3.8.4) repr() の目的: 再生成可能な表現

理想的には、repr() が返す文字列は、その文字列を Python のインタプリタに渡すことで元のオブジェクトを再生成できるものであるべきだとされています。基本的な型では、これはうまく機能します。

python
# repr_recreate.py
# For numbers
x = 42
x_repr = repr(x)
print(x_repr)  # Output: 42
 
# You could use this to recreate x
x_recreated = eval(x_repr)  # eval() evaluates a string as Python code
print(x_recreated)  # Output: 42
 
# For strings
text = "Hello"
text_repr = repr(text)
print(text_repr)  # Output: 'Hello'
 
# This could recreate the string
text_recreated = eval(text_repr)
print(text_recreated)  # Output: Hello

重要な注意: eval() 関数は、文字列を Python コードとして評価します。ここでは repr() の目的を説明するために取り上げましたが、信頼できない入力に対して eval() を使ってはいけません。セキュリティ上の重大なリスクがあります。より安全な代替手段については、後の章で扱います。

3.8.5) str() と repr() の実用例

例 1: 文字列の問題のデバッグ

python
# debugging_strings.py
# User input might have unexpected whitespace
user_input = "  Alice  "
 
print("User entered:", user_input)         # Output: User entered:   Alice  
print("Debug view:", repr(user_input))     # Output: Debug view: '  Alice  '
 
# Now the extra spaces are obvious!
cleaned = user_input.strip()  # Remove leading/trailing whitespace
print("Cleaned:", repr(cleaned))  # Output: Cleaned: 'Alice'

例 2: 型の違いを見分ける

python
# comparing_types.py
# These look similar but are different
num = 42
text = "42"
 
print("Number:", num)       # Output: Number: 42
print("Text:", text)        # Output: Text: 42
 
print("Number repr:", repr(num))   # Output: Number repr: 42
print("Text repr:", repr(text))    # Output: Text repr: '42'
 
# repr() makes the difference clear
print("Are they equal?", num == text)  # Output: Are they equal? False

3.8.6) 他の型に対する str() と repr()

ここまで学んだ型に対して str()repr() がどう動作するかをまとめて見てみましょう。

python
# str_repr_types.py
# Integers
x = 42
print("int str:", str(x))    # Output: int str: 42
print("int repr:", repr(x))  # Output: int repr: 42
 
# Floats
y = 3.14159
print("float str:", str(y))   # Output: float str: 3.14159
print("float repr:", repr(y)) # Output: float repr: 3.14159
 
# Booleans
b = True
print("bool str:", str(b))   # Output: bool str: True
print("bool repr:", repr(b)) # Output: bool repr: True
 
# None
n = None
print("None str:", str(n))   # Output: None str: None
print("None repr:", repr(n)) # Output: None repr: None
 
# Strings (where they differ most)
s = "Hello\nWorld"
print("string str:", str(s))   # Output: string str: Hello
                                #                     World
print("string repr:", repr(s)) # Output: string repr: 'Hello\nWorld'

3.8.7) まとめ: str() と repr() の使い分け

str() を使うべき場面:

  • エンドユーザーに見せる出力を作るとき
  • メッセージやログを読みやすく整えるとき
  • データを表示用にフォーマットするとき
  • とにかく「人にとって読みやすい」出力が欲しいとき

repr() を使うべき場面:

  • コードのデバッグをするとき
  • 技術的な情報をログに残すとき
  • 変数の中身を正確に確認したいとき
  • あいまいさのない表現が必要なとき

覚えておきたいポイント:

  • print() は、渡された引数に自動的に str() を適用します。
  • 基本的な型では、str()repr() の結果が同じことも多いです。
  • 文字列の場合、repr() は引用符を含み、改行などのエスケープシーケンスもそのまま表示します。
  • repr() は、理想的には「評価すれば元のオブジェクトを再生成できる」文字列を返すよう設計されています。

章のまとめ

この章では、Python における変数とデータ型の基本概念を学びました。ここまでの重要なポイントを振り返りましょう。

変数:

  • 変数はメモリ上の値を参照する「名前」です。
  • variable_name = value のように、代入で作成します。
  • いつでも新しい値を再代入できます。
  • 命名ルールに従う必要があり、慣習に従うことで可読性が上がります。
  • 意味のある名前を使うことで、コード自体が説明書きのようになり、理解しやすくなります。

データ型:

  • Python のすべての値には型があります。
  • type() を使って値の型を確認できます。
  • Python は動的型付けであり、変数は実行中に異なる型の値を参照することができます。
  • 型が異なれば、サポートされる操作や振る舞いも異なります。

基本的な型:

  • int: 整数(正・負・ゼロを含む)、Python 3 では理論上のサイズ制限なし
  • float: 小数点を含む数値。表現の仕組みにより、厳密さに限界があることがあります。
  • str: 引用符で囲まれたテキスト(シングルクォートまたはダブルクォート)
  • bool: 論理値 TrueFalse
  • None: 値がないことを表す特別な値

型変換:

  • int(): 整数に変換(float の小数部分は切り捨て、文字列は数値表現である必要がある)
  • float(): 浮動小数点数に変換
  • str(): 文字列に変換(どんな値にも使える)
  • 不適切な入力に対する変換は ValueError を発生させます。

文字列表現:

  • str(): エンドユーザー向けの、読みやすい文字列表現
  • repr(): 開発者向けの、あいまいさのない文字列表現(デバッグ用)
  • print() は引数に対して自動的に str() を使います。

これらの概念は、Python でこれから行うすべての作業の土台となります。どんなプログラムでも、データを保存するために変数を使いますし、データ型を理解することは、「どの操作が有効か」「どのタイミングでエラーが出る可能性があるか」を予測する助けになります。

次の章では、この土台の上に立って、数値の扱い方をさらに詳しく見ていきます。算術演算、演算子の優先順位、よくある数値パターンなどを学びます。また、計算の実行方法、数学関数の使い方、浮動小数点数特有の注意点への対処法なども扱っていきます。

© 2025. Primesoft Co., Ltd.
support@primesoft.ai