Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

Python入門

Posted at

Python 入門

目次

  1. 環境構築
  2. 基本構文
  3. データ型と変数
  4. 演算子
  5. 制御構造
  6. 関数
  7. データ構造
  8. オブジェクト指向プログラミング
  9. 例外処理
  10. テスト(unittest)
  11. Web フレームワーク(Flask)

環境構築

主要な環境構築方法

方法 説明 利点 用途
Anaconda データサイエンス向け Python ディストリビューション パッケージ管理が簡単、GUI 付き データサイエンス・機械学習
pyenv Python バージョン管理ツール 複数バージョンの切り替えが容易 開発環境でのバージョン管理
venv Python 標準の仮想環境ツール 軽量、標準搭載 プロジェクト別環境分離

基本的なセットアップ手順

# pyenv + venv の基本的な流れ
# 1. pyenvでPythonをインストール
pyenv install 3.9.0
pyenv global 3.9.0

# 2. venvで仮想環境を作成
python -m venv myenv

# 3. 仮想環境をアクティベート
source myenv/bin/activate  # macOS/Linux
# myenv\Scripts\activate   # Windows

# 4. 仮想環境を無効化
deactivate

基本構文

基本的な記述規則

項目 説明
文字コード UTF-8 が標準 # -*- coding: utf-8 -*-
コメント #で単行、"""で複数行 # これはコメント
インデント 4 スペースが標準 ブロック構造を表現
行継続 \または括弧で改行 長い文の分割

出力とコメント

# 基本的な出力
print("Hello, World!")
print('Hello, Python!')

# 複数の値を出力
print("名前:", "田中", "年齢:", 25)

# 改行なしで出力
print("Hello", end="")
print("World")  # HelloWorld

# 複数行コメント
"""
これは複数行の
コメントです
"""

データ型と変数

基本データ型

データ型 説明 特徴
int 整数 age = 25 任意精度
float 浮動小数点数 height = 170.5 64 ビット精度
str 文字列 name = "田中" イミュータブル
bool 論理値 is_student = True True/False
NoneType 空の値 data = None null 値

変数の宣言と型変換

# 基本的な変数宣言
name = "田中太郎"
age = 25
height = 170.5
is_student = True

# 型の確認
print(type(name))        # <class 'str'>
print(type(age))         # <class 'int'>
print(type(height))      # <class 'float'>
print(type(is_student))  # <class 'bool'>

# 型変換
num_str = "123"
num_int = int(num_str)      # 文字列 → 整数
num_float = float(num_str)  # 文字列 → 浮動小数点数
str_num = str(123)          # 数値 → 文字列
bool_num = bool(1)          # 数値 → 論理値

文字列操作

# 文字列の基本操作
text = "Hello, World!"

# 主要なメソッド
print(text.upper())          # 大文字に変換
print(text.lower())          # 小文字に変換
print(text.replace("World", "Python"))  # 置換
print(text.split(","))       # 分割

# 文字列フォーマット
name = "田中"
age = 25

# f-string(推奨)
message = f"名前: {name}, 年齢: {age}"

# format()メソッド
message = "名前: {}, 年齢: {}".format(name, age)

演算子

算術演算子

演算子 説明 結果
+ 加算 5 + 3 8
- 減算 5 - 3 2
* 乗算 5 * 3 15
/ 除算(浮動小数点) 10 / 3 3.333...
// 除算(整数) 10 // 3 3
% 余り 10 % 3 1
** べき乗 2 ** 3 8

比較演算子

演算子 説明
== 等しい 5 == 5True
!= 等しくない 5 != 3True
> より大きい 5 > 3True
>= 以上 5 >= 5True
< より小さい 3 < 5True
<= 以下 3 <= 3True

論理演算子

演算子 説明
and かつ True and FalseFalse
or または True or FalseTrue
not 否定 not TrueFalse

制御構造

条件分岐(if 文)

# 基本的なif文
age = 20

if age >= 20:
    print("成人です")
elif age >= 18:
    print("高校生以上です")
else:
    print("未成年です")

# 三項演算子
status = "成人" if age >= 20 else "未成年"

# Pythonで偽と判定される値
falsy_values = [False, None, 0, 0.0, "", [], {}, ()]

ループ処理

for 文

# range()を使った繰り返し
for i in range(5):
    print(f"{i + 1}回目のループ")

# リストの要素を繰り返し
fruits = ["りんご", "バナナ", "オレンジ"]
for fruit in fruits:
    print(fruit)

# enumerate()でインデックスと値を取得
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

# zip()で複数のリストを同時に処理
names = ["田中", "佐藤", "鈴木"]
ages = [25, 30, 28]
for name, age in zip(names, ages):
    print(f"{name}さんは{age}歳です")

while 文

# 基本的なwhile文
count = 0
while count < 5:
    print(f"カウント: {count}")
    count += 1

ループ制御

キーワード 説明 使用例
break ループを完全に抜ける if i == 3: break
continue 次の繰り返しにスキップ if i == 2: continue
pass 何もしない if condition: pass

関数

関数の定義

# 基本的な関数
def greet(name):
    return f"こんにちは、{name}さん!"

# デフォルト引数
def greet_default(name, greeting="こんにちは"):
    return f"{greeting}{name}さん!"

# 可変長引数
def sum_all(*numbers):
    return sum(numbers)

# キーワード可変長引数
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

lambda 関数

# 基本的なlambda関数
square = lambda x: x ** 2
add = lambda x, y: x + y

# map()との組み合わせ
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # [1, 4, 9, 16, 25]

データ構造

リスト(List)

# リストの作成と基本操作
fruits = ["りんご", "バナナ", "オレンジ"]

# 要素へのアクセス
print(fruits[0])      # りんご
print(fruits[-1])     # オレンジ(最後の要素)
print(fruits[0:2])    # ['りんご', 'バナナ'](スライス)

主要なリストメソッド

メソッド 説明
append() 末尾に要素を追加 fruits.append("ぶどう")
insert() 指定位置に挿入 fruits.insert(1, "メロン")
remove() 指定要素を削除 fruits.remove("バナナ")
pop() 指定位置の要素を削除して返す last = fruits.pop()
index() 要素の位置を取得 fruits.index("りんご")
count() 要素の出現回数 fruits.count("りんご")
sort() ソート fruits.sort()
reverse() 逆順 fruits.reverse()

リスト内包表記

# 基本的な内包表記
squares = [x ** 2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

# 条件付き内包表記
even_squares = [x ** 2 for x in range(1, 11) if x % 2 == 0]
print(even_squares)  # [4, 16, 36, 64, 100]

辞書(Dictionary)

# 辞書の作成
person = {
    "name": "田中太郎",
    "age": 30,
    "city": "東京"
}

# 要素へのアクセス
print(person["name"])           # 田中太郎
print(person.get("age"))        # 30
print(person.get("job", "未設定"))  # デフォルト値

# 要素の追加・変更・削除
person["job"] = "エンジニア"
person["age"] = 31
del person["city"]

主要な辞書メソッド

メソッド 説明
keys() 全てのキーを取得 person.keys()
values() 全ての値を取得 person.values()
items() キーと値のペアを取得 person.items()
pop() 指定キーの値を削除して返す person.pop("age")
update() 辞書を更新 person.update({"age": 32})

その他のデータ構造

タプル(Tuple)

# タプルの作成(変更不可)
coordinates = (10, 20)
colors = ("red", "green", "blue")

# タプルのアンパック
x, y = coordinates
print(f"x: {x}, y: {y}")

セット(Set)

# セットの作成(重複要素なし)
numbers = {1, 2, 3, 4, 5}

# セット演算
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

print(set1 | set2)  # 和集合: {1, 2, 3, 4, 5, 6}
print(set1 & set2)  # 積集合: {3, 4}
print(set1 - set2)  # 差集合: {1, 2}

オブジェクト指向プログラミング

クラスの基本

class User:
    """ユーザークラス"""

    def __init__(self, name, age):
        """初期化メソッド"""
        self.name = name
        self.age = age

    def greet(self):
        """挨拶メソッド"""
        return f"こんにちは、{self.name}です。{self.age}歳です。"

    def __str__(self):
        """文字列表現"""
        return f"User: {self.name}"

# オブジェクトの生成と使用
user1 = User("田中", 25)
print(user1.greet())
print(user1)

継承

class Employee(User):
    """社員クラス(Userを継承)"""

    def __init__(self, name, age, department):
        super().__init__(name, age)  # 親クラスの初期化
        self.department = department

    def greet(self):
        """オーバーライドされた挨拶メソッド"""
        return f"こんにちは、{self.name}です。{self.department}に所属しています。"

employee = Employee("佐藤", 30, "営業部")
print(employee.greet())

クラス変数とインスタンス変数

変数の種類 説明 アクセス方法 共有範囲
クラス変数 クラスに属する変数 Class.variable 全インスタンスで共有
インスタンス変数 インスタンスに属する変数 instance.variable インスタンス毎に独立
class Counter:
    total_count = 0  # クラス変数

    def __init__(self, name):
        self.name = name  # インスタンス変数
        Counter.total_count += 1

    @classmethod
    def get_total(cls):
        return cls.total_count

    @staticmethod
    def reset_total():
        Counter.total_count = 0

特殊メソッド

メソッド 説明 用途
__init__ 初期化 オブジェクト生成時
__str__ 文字列表現 print()で呼ばれる
__repr__ オブジェクト表現 デバッグ用
__len__ 長さ len()で呼ばれる
__add__ 加算演算 +演算子で呼ばれる

例外処理

基本的な例外処理

try:
    x = 10 / 0
except ZeroDivisionError as e:
    print(f"ゼロ除算エラー: {e}")
except Exception as e:
    print(f"その他のエラー: {e}")
else:
    print("エラーが発生しませんでした")
finally:
    print("必ず実行される処理")

主要な組み込み例外

例外 説明 発生例
ValueError 不正な値 int("abc")
TypeError 型エラー "text" + 1
KeyError 存在しないキー dict["nonkey"]
IndexError 範囲外インデックス list[100]
FileNotFoundError ファイルが見つからない open("nonfile.txt")

カスタム例外

class CustomError(Exception):
    """カスタム例外クラス"""
    pass

def validate_age(age):
    if age < 0:
        raise CustomError("年齢は0以上である必要があります")
    return age

try:
    validate_age(-5)
except CustomError as e:
    print(f"カスタムエラー: {e}")

テスト(unittest)

基本的なテストの書き方

# test_sample.py
import unittest

class TestMathOperations(unittest.TestCase):

    def setUp(self):
        """各テストの前に実行"""
        self.numbers = [1, 2, 3, 4, 5]

    def tearDown(self):
        """各テストの後に実行"""
        pass

    def test_addition(self):
        """足し算のテスト"""
        result = 2 + 3
        self.assertEqual(result, 5)

    def test_division(self):
        """割り算のテスト"""
        result = 10 / 2
        self.assertEqual(result, 5.0)

    def test_list_length(self):
        """リストの長さのテスト"""
        self.assertEqual(len(self.numbers), 5)

    @unittest.skip("一時的にスキップ")
    def test_skipped(self):
        """スキップされるテスト"""
        pass

if __name__ == '__main__':
    unittest.main()

主要なアサーションメソッド

メソッド 説明 使用例
assertEqual(a, b) a == b self.assertEqual(result, 5)
assertNotEqual(a, b) a != b self.assertNotEqual(x, y)
assertTrue(x) x is True self.assertTrue(condition)
assertFalse(x) x is False self.assertFalse(condition)
assertIn(a, b) a in b self.assertIn(item, list)
assertIsNone(x) x is None self.assertIsNone(result)

テストの実行

# 単一ファイルの実行
python -m unittest test_sample.py

# すべてのテストを実行
python -m unittest

# 詳細出力
python -m unittest -v

Web フレームワーク(Flask)

Flask の基本

Flask は軽量な Python Web フレームワークで、マイクロフレームワークと呼ばれます。

特徴

特徴 説明
軽量 最小限の機能で構成
柔軟 必要な機能を後から追加可能
学習コスト低 シンプルで理解しやすい
REST API API 開発に適している

基本的な使用例

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello, Flask!"

@app.route('/user/<name>')
def show_user(name):
    return f"Hello, {name}!"

@app.route('/api/data', methods=['GET', 'POST'])
def api_data():
    if request.method == 'POST':
        data = request.json
        return jsonify({"received": data})
    else:
        return jsonify({"message": "GET request"})

if __name__ == '__main__':
    app.run(debug=True)

実践的なサンプルコード

ファイル操作

# ファイルの読み書き
def read_file(filename):
    try:
        with open(filename, 'r', encoding='utf-8') as file:
            return file.read()
    except FileNotFoundError:
        return None

def write_file(filename, content):
    with open(filename, 'w', encoding='utf-8') as file:
        file.write(content)

# JSON操作
import json

def save_to_json(data, filename):
    with open(filename, 'w', encoding='utf-8') as file:
        json.dump(data, file, ensure_ascii=False, indent=2)

def load_from_json(filename):
    try:
        with open(filename, 'r', encoding='utf-8') as file:
            return json.load(file)
    except FileNotFoundError:
        return None

日付・時刻操作

from datetime import datetime, timedelta

# 現在の日時
now = datetime.now()
print(f"現在時刻: {now}")

# 日付の計算
tomorrow = now + timedelta(days=1)
week_ago = now - timedelta(weeks=1)

# 文字列との変換
date_str = now.strftime('%Y-%m-%d %H:%M:%S')
parsed_date = datetime.strptime('2023-12-25', '%Y-%m-%d')
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?