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入門

Last updated at Posted at 2025-04-16
# プログラム名: python_fundamentals_summary.py
# Program Name: python_fundamentals_summary.py
# Python入門:文法、データ型、構造、関数、クラス、例外、アルゴリズム、ファイル操作など、基礎から応用まで一貫した学習が可能なスクリプト。

# --- Pythonとは? / What is Python? ---
# Pythonは汎用的な高水準のプログラミング言語であり、可読性が高く、教育・研究・実務など幅広く使われています。
# インタプリタ型で動的型付けを採用し、簡潔な構文が特徴です。

# Pythonの用途:
# - データ分析(pandas, numpy, matplotlib)
# - Web開発(Django, Flask)
# - 機械学習(scikit-learn, TensorFlow, PyTorch)
# - 自動化(スクリプト、バッチ処理、Webスクレイピング)

# --- Pythonの実行方法 ---
# - インタプリタ起動: python
# - スクリプト実行: python ファイル名.py
# - Jupyter NotebookやGoogle Colabも学習に便利です

# --- print関数 ---
# Pythonではprint()を使って画面に出力できます。
print("Hello, Python!")  # コメントは # で記述 / Comments start with '#'

# --- 変数の宣言と代入 / Variables ---
# 変数は値を格納する名前付きのラベルです。型を指定せずに代入できます。
name = "Alice"
age = 25
height = 1.68
is_student = False

# --- 型の確認と変換 / Type Check & Cast ---
print(type(age))        # <class 'int'>
print(str(age))         # 型変換: int -> str
print(int("10"))        # str -> int
print(float(3))         # int -> float

# --- 入力 / User Input ---
# ユーザーからの入力を受け取るには input() を使います。
# user_input = input("Enter your name: ")
# print(f"Hello, {user_input}")

# --- コメント / Comments ---
# 単一行: # を使う
"""
複数行コメントやドキュメントには triple quotes を使う
複数行説明や関数の説明(docstring)に便利です
"""

# --- スタイルガイド / Style Guide ---
# PythonではPEP8というスタイルガイドに従うことが推奨されています。
# ・インデントはスペース4つ(タブではなく)
# ・関数・変数名はスネークケース(lower_case_with_underscores)
# ・定数は全て大文字(ALL_CAPS)

# 以降は章番号順に構成されたスクリプトとなります:
# - 1. 基本文法とインデント
# - 2. 変数
# - 3. データ型
# - 4. 数値演算
# - 5. 文字列操作
# - 6. リスト
# - 7. 辞書
# - 8. 集合とタプル
# - 9. 条件分岐
# - 10. ループ
# - 11. ネスト
# - 12. 関数
# - 13. クラスとオブジェクト指向
# - 14. モジュール
# - 15. 外部ライブラリ
# - 16. 例外処理
# - 17. ファイル操作
# - 18. 内包表記
# - 19. 無名関数と高階関数
# - 20. テストとデバッグ
# - 21. アルゴリズム(再帰)
# - 22. 日付と時間

# プログラム名: python_basics_summary.py
# 概要: Pythonの基本構文と機能を網羅的に学習・確認するための統合スクリプト


# --- 1. 基本文法とインデント / Basic Syntax and Indentation ---
# Pythonのコードはインデントで構造を示す / Indentation defines structure
# 通常はスペース4つを使う(PEP8)
print("Hello, Python!")  # コメントは # で記述

# --- 2. 変数 / Variables ---
# 型宣言なしで代入できる / No need for type declaration
name = "Alice"  # 文字列型 / string
age = 25        # 整数型 / integer
height = 1.65   # 浮動小数点型 / float
is_student = True  # 真偽値型 / boolean

# --- 3. データ型 / Data Types ---
integer = 42            # int型
floating = 3.14         # float型
string = "Python"       # str型
boolean = False         # bool型
lst = [1, 2, 3]          # list型
print(type(lst))
dct = {"key": "value"}  # dict型
st = {1, 2, 3}           # set型
tpl = (4, 5, 6)          # tuple型(不変)

# --- 4. 数値演算 / Arithmetic Operations ---
a = 10
b = 3
print("加算:", a + b)     # Addition
print("減算:", a - b)     # Subtraction
print("乗算:", a * b)     # Multiplication
print("除算:", a / b)     # Division (float)
print("整数除算:", a // b) # Floor division
print("剰余:", a % b)      # Modulo
print("べき乗:", a ** b)    # Exponentiation

import math
print("平方根:", math.sqrt(16))

# --- 5. 文字列操作 / String Operations ---
text = "Hello"
print(text + " World")      # 結合 / concatenation
print(text.upper())         # 大文字化 / uppercase
print(text.lower())         # 小文字化 / lowercase
print(text.replace("H", "J"))  # 部分置換 / replace
print(f"Length: {len(text)}")  # 長さ / length

# --- 6. リスト / List ---
numbers = [1, 2, 3]
numbers.append(4)            # 要素追加 / append
numbers.insert(1, 10)        # 指定位置に挿入 / insert
numbers.remove(2)            # 指定要素削除 / remove
print("リスト:", numbers)
for num in numbers:
    print(num)

# --- 7. 辞書 / Dictionary ---
data = {"name": "Bob", "age": 30}
data["city"] = "Tokyo"         # 要素追加
for key, value in data.items():
    print(f"{key}: {value}")
print("名前:", data.get("name"))  # get()で取得

# --- 8. 集合とタプル / Set and Tuple ---
unique = set([1, 1, 2, 3])   # 重複排除
print("集合:", unique)
print(2 in unique)           # 要素の存在確認

fixed = (1, 2, 3)            # 不変のリスト
print("タプル:", fixed)

# --- 9. 条件分岐 / Conditional Statements ---
x = 10
if x > 0:
    print("Positive")
elif x == 0:
    print("Zero")
else:
    print("Negative")

# --- 10. ループ / Loops ---
# forループ / for loop
for i in range(3):
    print(f"For loop: {i}")

# whileループ / while loop
j = 0
while j < 3:
    print(f"While loop: {j}")
    j += 1

# --- 11. ネスト / Nesting ---
for i in range(2):
    if i % 2 == 0:
        print(f"{i} is even")
    else:
        print(f"{i} is odd")

# --- 12. 関数 / Functions ---
def greet(name):
    return f"Hello, {name}"

message = greet("Charlie")
print(message)

# --- 13. クラスとオブジェクト指向 / Classes and OOP ---
class Person:
    def __init__(self, name):
        self.name = name

    def say_hello(self):
        print(f"Hi, I'm {self.name}")

p = Person("Dave")
p.say_hello()

# --- 14. モジュール / Modules ---
import os  # OS操作用モジュール
print("OS name:", os.name)

import random  # 乱数生成
print("Random number:", random.randint(1, 10))

# --- 15. 外部ライブラリ / External Libraries ---
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

arr = np.array([1, 2, 3])
print("NumPy array:", arr)

df = pd.DataFrame({'col1': arr})
print("DataFrame:\n", df)

df.plot(title="Sample Plot")
plt.xlabel("Index")
plt.ylabel("Value")
plt.grid(True)
plt.show()

# --- 16. 例外処理 / Exception Handling ---
try:
    num = int("abc")  # 文字列を整数に変換(失敗)
except ValueError as e:
    print("変換エラー:", e)  # ValueErrorをキャッチ
finally:
    print("例外処理完了 / Exception handling done.")

# --- 17. ファイル操作 / File I/O ---
# 書き込み / Writing
with open("sample.txt", "w", encoding="utf-8") as f:
    f.write("これはファイルへの書き込みです。\nThis is a file write.")

# 読み込み / Reading
with open("sample.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print("ファイル内容:\n", content)

# --- 18. 内包表記 / List & Dict Comprehension ---
squares = [x**2 for x in range(5)]  # リスト内包表記 / List comprehension
print("Squares:", squares)

square_dict = {x: x**2 for x in range(5)}  # 辞書内包表記 / Dict comprehension
print("Square Dictionary:", square_dict)

# --- 19. 無名関数と高階関数 / Lambda & Higher-order Functions ---
from functools import reduce

double = lambda x: x * 2
print("Lambda x2:", double(4))

mapped = list(map(lambda x: x + 1, range(5)))   # 各要素に+1
filtered = list(filter(lambda x: x % 2 == 0, range(5)))  # 偶数だけ
total = reduce(lambda x, y: x + y, range(5))    # 合計値

print("Mapped:", mapped)
print("Filtered (even):", filtered)
print("Reduced sum:", total)

# --- 20. テストとデバッグ / Testing and Debugging ---
def square(x):
    return x * x

assert square(3) == 9, "Test failed"  # 簡易テスト / simple test
print("関数squareは正しく動作しています。")

# --- 21. アルゴリズム(再帰)/ Algorithms (Recursion) ---
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)  # 再帰呼び出し / recursive call

print("5の階乗:", factorial(5))  # 5! = 120

# --- 22. 日付と時間 / Date and Time ---
import datetime
import time
import calendar
import zoneinfo

# 現在時刻 / Current time
now = datetime.datetime.now()
print("現在時刻 / Now:", now)

# 書式付き表示 / Formatted output
print("Formatted:", now.strftime("%Y-%m-%d %H:%M:%S"))

# 時差付き時刻 / Timezone-aware datetime
tokyo_time = datetime.datetime.now(zoneinfo.ZoneInfo("Asia/Tokyo"))
utc_time = datetime.datetime.now(zoneinfo.ZoneInfo("UTC"))
print("Tokyo:", tokyo_time)
print("UTC:", utc_time)

# 日付演算 / Date arithmetic
tomorrow = now + datetime.timedelta(days=1)
yesterday = now - datetime.timedelta(days=1)
print("Tomorrow:", tomorrow)
print("Yesterday:", yesterday)

# UNIX時刻との変換 / UNIX timestamp conversion
timestamp = now.timestamp()
dt_from_ts = datetime.datetime.fromtimestamp(timestamp)
print("UNIX Timestamp:", timestamp)
print("From timestamp:", dt_from_ts)

# カレンダー表示 / Calendar
print("2025年4月のカレンダー:")
print(calendar.month(2025, 4))

# 処理時間計測 / Performance timing
start = time.perf_counter()
for _ in range(1000000): pass
end = time.perf_counter()
print("処理時間:", end - start, "")

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?