0
1

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のデータ型と変数 - 超初心者向け5分で理解

Posted at

TL;DR

  • 数値: int(整数)、float(浮動小数点)
  • 文字列: '' または "" で囲む
  • ブール: True, False
  • リスト/辞書: [], {} で複数データ管理
  • 変数: 変数名 = 値 の形で代入
  • 型変換: str(), int(), float() を使用

背景

Pythonを学び始めてからデータ型と変数について整理した内容です。
実務でよく使うパターンを中心に簡単にまとめました。

1. 数値型

整数型 (int)

age = 25
count = 100

浮動小数点型 (float)

height = 175.5
rate = 0.1

💡 Tips

# 大きな数字はアンダースコアで可読性向上
big_number = 1_000_000  # 1000000と同じ

2. 文字列型

基本的な使い方

name = "田中太郎"
message = 'こんにちは'

よく使うパターン

# f-string (Python 3.6+)
name = "太郎"
age = 25
print(f"{name}さんは{age}歳です。")  # 太郎さんは25歳です。

# 文字列メソッド
text = "Python Programming"
print(text.upper())    # PYTHON PROGRAMMING
print(text.split())    # ['Python', 'Programming']

3. ブール型

基本的な使い方

is_active = True
is_deleted = False

比較演算子

age = 20
print(age >= 18)  # True
print(age < 15)   # False

論理演算子

# and, or, not
is_adult = age >= 18 and has_id
can_enter = is_member or is_vip
is_available = not is_busy

4. 変数の使い方

変数代入

# 基本代入
user_name = "山田太郎"
user_age = 30

# 複数代入
x, y, z = 1, 2, 3

ネーミング規則

# ✅ 良い例
user_name = "田中花子"
MAX_COUNT = 100
_private_var = "非公開"

# ❌ 避けるべき例
# 1name = "田中花子"    # 数字で始まることはできない
# class = "授業"        # キーワード使用不可

5. 型変換

基本型変換

# 文字列 → 数値
age_str = "25"
age_int = int(age_str)    # 25
age_float = float(age_str)  # 25.0

# 数値 → 文字列
count = 100
count_str = str(count)    # "100"

例外処理付き型変換(推奨)

# 安全な型変換
try:
    age = int(input("年齢を入力してください: "))
    print(f"入力された年齢: {age}")
except ValueError:
    print("数字を入力してください")

実務でよく使うパターン

# ユーザー入力処理
try:
    user_input = input("年齢を入力してください: ")
    age = int(user_input)
except ValueError:
    print("正しい数字を入力してください")
    age = 0

# 小数点処理
price = 1234.567
formatted_price = f"{price:.2f}"  # "1234.57"

6. 実践例

簡単な電卓

def simple_calculator():
    """関数を直接実行するには simple_calculator() を呼び出す"""
    try:
        num1 = float(input("最初の数: "))
        operator = input("演算子 (+, -, *, /): ")
        num2 = float(input("二番目の数: "))
        
        if operator == '+':
            result = num1 + num2
        elif operator == '-':
            result = num1 - num2
        elif operator == '*':
            result = num1 * num2
        elif operator == '/':
            result = num1 / num2 if num2 != 0 else "Error: 0で割ることはできません"
        else:
            result = "無効な演算子です"
        
        print(f"結果: {result}")
    except ValueError:
        print("数字を入力してください")

# 関数を実行
simple_calculator()

データ検証

def validate_user_data(name, age, email):
    """ユーザーデータの検証関数"""
    errors = []
    
    # 名前検証
    if not name or not isinstance(name, str):
        errors.append("名前は必須です")
    
    # 年齢検証
    if not isinstance(age, int) or age < 0:
        errors.append("年齢は0以上の整数である必要があります")
    
    # メール検証
    if not email or '@' not in email:
        errors.append("正しいメール形式ではありません")
    
    return errors

# 使用例
errors = validate_user_data("田中太郎", 25, "tanaka@example.com")
if errors:
    print("検証失敗:", errors)
else:
    print("検証成功")

7. よくある間違いと解決法

型変換エラー

# ❌ 間違った例
# age = int("25.5")  # ValueError発生

# ✅ 正しい例
age = int(float("25.5"))  # 25

# ✅ さらに安全な例
try:
    age = int(float("25.5"))
except ValueError:
    print("数値変換に失敗しました")
    age = 0

文字列連結エラー

# ❌ 間違った例
# print("年齢: " + 25)  # TypeError発生

# ✅ 正しい例
print("年齢: " + str(25))  # "年齢: 25"
print(f"年齢: {25}")       # "年齢: 25"

8. 型チェックユーティリティ

def check_type(value):
    """値の型を確認するユーティリティ関数"""
    type_name = type(value).__name__
    print(f"値: {value}, 型: {type_name}")
    
    # bool は int のサブクラスなので、先にチェック
    if isinstance(value, bool):
        print(f"ブール値: {value}")
    elif isinstance(value, (int, float)):
        print(f"数値です: True")
    elif isinstance(value, str):
        print(f"文字列長: {len(value)}")

# 使用例
check_type("Hello")     # 値: Hello, 型: str, 文字列長: 5
check_type(42)          # 値: 42, 型: int, 数値です: True
check_type(3.14)        # 値: 3.14, 型: float, 数値です: True
check_type(True)        # 値: True, 型: bool, ブール値: True

まとめ

Pythonの基本データ型と変数は、すべてのプログラミングの基礎となります。
特に型変換と文字列処理は実務で毎日使う機能なので、しっかりと身につけておくことをお勧めします。

次のステップ

次の投稿ではリストと辞書について扱います!
条件分岐やループ、関数の使い方も順に学んでいきましょう! 🐍

関連タグ

#Python #初心者 #データ型 #変数 #基礎


読んでいただき、ありがとうございました!

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?