diff --git a/app/[docs_id]/markdown.tsx b/app/[docs_id]/markdown.tsx index 002dd80..efc8d80 100644 --- a/app/[docs_id]/markdown.tsx +++ b/app/[docs_id]/markdown.tsx @@ -51,7 +51,6 @@ const components: Components = { ), }; - export function Heading({ level, children, @@ -133,6 +132,11 @@ function CodeComponent({ } else if (match[2] === "-repl") { // repl付きの言語指定 // 現状はPythonのみ対応 + if (!match[3]) { + console.warn( + `${match[1]}-repl without terminal id! content: ${String(props.children).slice(0, 20)}...` + ); + } switch (match[1]) { case "python": return ( diff --git a/public/docs/python-1.md b/public/docs/python-1.md index ee67ed4..bd00a1b 100644 --- a/public/docs/python-1.md +++ b/public/docs/python-1.md @@ -36,7 +36,7 @@ macOSでは、**Homebrew** というパッケージマネージャを使って このウェブサイトではドキュメント内に Python {process.env.PYODIDE_PYTHON_VERSION} の実行環境を埋め込んでいます。 以下のように青枠で囲われたコード例には自由にPythonコードを書いて試すことができます。気軽に利用してください。 -```python-repl +```python-repl:1 >>> message = "Hello, Python!" >>> print(message) Hello, Python! @@ -60,19 +60,19 @@ Type "help", "copyright", "credits" or "license" for more information. ### REPL の基本的な使い方 * **計算:** 数式を直接入力すると、計算結果が返ってきます。 -```python-repl +```python-repl:2 >>> 10 * 5 + 3 53 ``` * **変数と関数の利用:** 変数を定義したり、`print()`のような組み込み関数を呼び出したりできます。 -```python-repl +```python-repl:3 >>> greeting = "Hi there" >>> print(greeting) Hi there ``` * **ヘルプ機能:** `help()` と入力するとヘルプが表示されます。調べたいモジュールや関数名(例: `str`)を入力するとドキュメントが表示されます。 * PCのターミナルで起動したREPLでは、対話的なヘルプモードが起動します。ヘルプモードを抜けるには `quit` と入力します。 -```python-repl +```python-repl:4 >>> help(str) Help on class str in module builtins: diff --git a/public/docs/python-2.md b/public/docs/python-2.md index 6ff3215..499f0c3 100644 --- a/public/docs/python-2.md +++ b/public/docs/python-2.md @@ -6,7 +6,7 @@ Pythonの最も大きな特徴の一つは、変数の型を宣言する必要がないことです。変数への代入が、変数の作成と型の決定を同時に行います。 -```python-repl +```python-repl:1 >>> # 変数 message を作成し、文字列を代入 >>> message = "Hello, Python!" >>> print(message) @@ -19,7 +19,7 @@ Hello, Python! さらに、Pythonは**動的型付け**言語です。これは、一度作成した変数に、異なる型のデータを再代入できることを意味します。`type()`関数を使うと、変数が現在どの型を参照しているかを確認できます。 -```python-repl +```python-repl:2 >>> x = 10 >>> type(x) @@ -39,7 +39,7 @@ Pythonには多くの組み込みデータ型がありますが、ここでは Pythonは整数 (`int`) と浮動小数点数 (`float`) を区別します。 -```python-repl +```python-repl:3 >>> # 整数 (int) >>> a = 10 >>> type(a) @@ -52,7 +52,7 @@ Pythonは整数 (`int`) と浮動小数点数 (`float`) を区別します。 四則演算は直感的に行えます。注意点として、除算 (`/`) は常に `float` を返します。整数除算を行いたい場合は (`//`) を使います。 -```python-repl +```python-repl:4 >>> 10 / 3 3.3333333333333335 >>> 10 // 3 @@ -69,14 +69,14 @@ Pythonは整数 (`int`) と浮動小数点数 (`float`) を区別します。 文字列はシングルクォート (`'`) またはダブルクォート (`"`) で囲んで作成します。 -```python-repl +```python-repl:5 >>> name = "Guido" >>> greeting = 'Hello' ``` 文字列の連結は `+` 演算子、繰り返しは `*` 演算子を使います。 -```python-repl +```python-repl:6 >>> full_greeting = greeting + ", " + name + "!" >>> print(full_greeting) Hello, Guido! @@ -86,7 +86,7 @@ Hello, Guido! 変数の値を文字列に埋め込む際には、**f-string (フォーマット済み文字列リテラル)** が非常に便利で推奨されています。文字列の前に `f` を付け、埋め込みたい変数を `{}` で囲みます。 -```python-repl +```python-repl:7 >>> name = "Ada" >>> age = 36 >>> message = f"My name is {name} and I am {age} years old." @@ -98,7 +98,7 @@ My name is Ada and I am 36 years old. 真偽値は `True` と `False` の2つの値を持ちます(先頭が大文字であることに注意してください)。論理演算子には `and`, `or`, `not` を使います。 -```python-repl +```python-repl:8 >>> is_active = True >>> has_permission = False >>> type(is_active) @@ -120,7 +120,7 @@ False `変数名: 型` のように記述します。 -```python-repl +```python-repl:9 >>> # 型ヒントを付けた変数宣言 >>> user_name: str = "Alice" >>> user_id: int = 123 @@ -128,7 +128,7 @@ False **重要な注意点:** 型ヒントはあくまで「ヒント」であり、**Pythonの実行エンジンはこれを強制しません**。つまり、型ヒントと異なる型の値を代入してもエラーにはなりません。 -```python-repl +```python-repl:10 >>> user_id: int = 123 >>> type(user_id) diff --git a/public/docs/python-3.md b/public/docs/python-3.md index c3c3eb9..a09126d 100644 --- a/public/docs/python-3.md +++ b/public/docs/python-3.md @@ -12,7 +12,7 @@ Pythonのプログラミングにおいて、データを効率的に扱う能 **基本的な使い方 (REPL実行例)** -```python-repl +```python-repl:1 >>> # リストの作成 >>> fruits = ['apple', 'banana', 'cherry'] >>> fruits @@ -57,7 +57,7 @@ Pythonのプログラミングにおいて、データを効率的に扱う能 **基本的な使い方 (REPL実行例)** -```python-repl +```python-repl:2 >>> # タプルの作成 (丸括弧を使用) >>> coordinates = (10, 20) >>> coordinates @@ -92,7 +92,7 @@ TypeError: 'tuple' object does not support item assignment **基本的な使い方 (REPL実行例)** -```python-repl +```python-repl:3 >>> # 辞書の作成 >>> person = {'name': 'Taro Yamada', 'age': 30, 'city': 'Tokyo'} >>> person @@ -132,7 +132,7 @@ dict_items([('name', 'Taro Yamada'), ('age', 31), ('city', 'Tokyo'), ('job', 'En **基本的な使い方 (REPL実行例)** -```python-repl +```python-repl:4 >>> # セットの作成 (重複した4は自動的に無視される) >>> numbers = {1, 2, 3, 4, 4, 5} >>> numbers @@ -168,7 +168,7 @@ dict_items([('name', 'Taro Yamada'), ('age', 31), ('city', 'Tokyo'), ('job', 'En **REPL実行例** -```python-repl +```python-repl:5 >>> numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> # インデックス1から4の手前まで @@ -200,7 +200,7 @@ dict_items([('name', 'Taro Yamada'), ('age', 31), ('city', 'Tokyo'), ('job', 'En `for`ループで書く場合と、リスト内包表記で書く場合を比較してみましょう。 -```python-repl +```python-repl:6 >>> # forループの場合 >>> squares_loop = [] >>> for i in range(10): @@ -222,7 +222,7 @@ dict_items([('name', 'Taro Yamada'), ('age', 31), ('city', 'Tokyo'), ('job', 'En **辞書内包表記** -```python-repl +```python-repl:7 >>> # 数値をキー、その2乗を値とする辞書を作成 >>> square_dict = {x: x*x for x in range(5)} >>> square_dict @@ -231,7 +231,7 @@ dict_items([('name', 'Taro Yamada'), ('age', 31), ('city', 'Tokyo'), ('job', 'En **セット内包表記** -```python-repl +```python-repl:8 >>> # リスト内のユニークな数値の2乗のセットを作成 >>> numbers = [1, 2, 2, 3, 4, 4, 5] >>> square_set = {x*x for x in numbers} diff --git a/public/docs/python-4.md b/public/docs/python-4.md index 9d2bc39..6994738 100644 --- a/public/docs/python-4.md +++ b/public/docs/python-4.md @@ -6,7 +6,7 @@ Pythonの条件分岐は`if`、`elif`(else ifの略)、`else`を使って記述します。C言語やJavaのような波括弧`{}`は使わず、**コロン`:`とインデント(通常は半角スペース4つ)**でコードブロックを表現するのが最大の特徴です。 -```python-repl +```python-repl:1 >>> score = 85 >>> if score >= 90: ... print('優') @@ -22,7 +22,7 @@ Pythonの条件分岐は`if`、`elif`(else ifの略)、`else`を使って記 条件式に`and`や`or`、`not`といった論理演算子も使用できます。 -```python-repl +```python-repl:2 >>> temp = 25 >>> is_sunny = True >>> if temp > 20 and is_sunny: @@ -35,7 +35,7 @@ Pythonの条件分岐は`if`、`elif`(else ifの略)、`else`を使って記 Pythonの`for`ループは、他の言語の`for (int i = 0; i < 5; i++)`といったカウンタ変数を使うスタイルとは少し異なります。リストやタプル、文字列などの**イテラブル(反復可能)オブジェクト**から要素を1つずつ取り出して処理を実行します。これは、Javaの拡張for文やC\#の`foreach`に似ています。 -```python-repl +```python-repl:3 >>> fruits = ['apple', 'banana', 'cherry'] >>> for fruit in fruits: ... print(f"I like {fruit}") @@ -49,7 +49,7 @@ I like cherry 決まった回数のループを実行したい場合は、`range()`関数が便利です。`range(n)`は0からn-1までの連続した数値を生成します。 -```python-repl +```python-repl:4 >>> for i in range(5): ... print(i) ... @@ -64,7 +64,7 @@ I like cherry ループ処理の中で、要素のインデックス(番号)と値の両方を使いたい場合があります。そのような時は`enumerate()`関数を使うと、コードが非常にスッキリします。これは非常にPythonらしい書き方の一つです。 -```python-repl +```python-repl:5 >>> fruits = ['apple', 'banana', 'cherry'] >>> for i, fruit in enumerate(fruits): ... print(f"Index: {i}, Value: {fruit}") @@ -78,7 +78,7 @@ Index: 2, Value: cherry `while`ループは、指定された条件が`True`である間、処理を繰り返します。ループを途中で抜けたい場合は`break`を、現在の回の処理をスキップして次の回に進みたい場合は`continue`を使用します。 -```python-repl +```python-repl:6 >>> n = 0 >>> while n < 5: ... print(n) @@ -95,7 +95,7 @@ Index: 2, Value: cherry 関数は`def`キーワードを使って定義します。ここでもコードブロックはコロン`:`とインデントで示します。値は`return`キーワードで返します。 -```python-repl +```python-repl:7 >>> def greet(name): ... """指定された名前で挨拶を返す関数""" # これはDocstringと呼ばれるドキュメント文字列です ... return f"Hello, {name}!" @@ -108,7 +108,7 @@ Hello, Alice! 引数と返り値に**型アノテーション(型ヒント)**を付けることもできます。これはコードの可読性を高め、静的解析ツールによるバグの発見を助けますが、実行時の動作に直接影響を与えるものではありません。 型アノテーションは `引数名: 型` のように記述し、返り値の型は `-> 型:` のように記述します。 -```python-repl +```python-repl:8 >>> # typingモジュールからList型をインポート >>> from typing import List >>> def greet(name: str) -> str: @@ -128,7 +128,7 @@ Pythonの関数は、非常に柔軟な引数の渡し方ができます。型 * **キーワード引数 (Keyword Arguments):** `引数名=値`の形式で渡します。順序を問わないため、可読性が向上します。 * **デフォルト引数値 (Default Argument Values):** 関数を定義する際に引数にデフォルト値を設定できます。呼び出し時にその引数が省略されると、デフォルト値が使われます。 -```python-repl +```python-repl:9 >>> def describe_pet(animal_type: str, pet_name: str, owner_name: str = "Taro") -> None: ... # この関数は何も値を返さないため、返り値の型は None となります ... print(f"私には {animal_type} がいます。") @@ -158,7 +158,7 @@ Pythonの関数は、非常に柔軟な引数の渡し方ができます。型 任意の数の**位置引数**をタプルとして受け取ります。型アノテーションでは `*args: 型` のように表現します。 -```python-repl +```python-repl:10 >>> def sum_all(*numbers: int) -> int: ... print(f"受け取ったタプル: {numbers}") ... total = 0 @@ -178,7 +178,7 @@ Pythonの関数は、非常に柔軟な引数の渡し方ができます。型 任意の数の**キーワード引数**を辞書として受け取ります。型アノテーションでは `**kwargs: 型` のように表現します。どのような型の値も受け付ける場合は `Any` を使います。 -```python-repl +```python-repl:11 >>> from typing import Any >>> def print_profile(**user_info: Any) -> None: ... print(f"受け取った辞書: {user_info}") @@ -198,7 +198,7 @@ city: Tokyo 構文: `lambda 引数: 式` -```python-repl +```python-repl:12 >>> # 通常の関数で2つの数を足す >>> def add(x: int, y: int) -> int: ... return x + y diff --git a/public/docs/python-5.md b/public/docs/python-5.md index 0d333ac..d5f8744 100644 --- a/public/docs/python-5.md +++ b/public/docs/python-5.md @@ -10,7 +10,7 @@ Pythonでは、**1つの `.py` ファイルが1つのモジュール**として モジュールを利用するには `import` 文を使います。Pythonには多くの便利なモジュールが標準で用意されています(これらを**標準ライブラリ**と呼びます)。例えば、数学的な計算を行う `math` モジュールを使ってみましょう。 -```python-repl +```python-repl:1 >>> # mathモジュールをインポート >>> import math >>> # mathモジュール内の変数や関数を利用する @@ -31,7 +31,7 @@ Pythonでは、**1つの `.py` ファイルが1つのモジュール**として * **`from ... import ...`**: モジュールから特定の関数や変数だけを取り込む - ```python-repl + ```python-repl:2 >>> from math import pi, sqrt >>> >>> print(pi) # 直接piを参照できる @@ -42,7 +42,7 @@ Pythonでは、**1つの `.py` ファイルが1つのモジュール**として * **`as` (別名)**: モジュールに別名をつけて利用する - ```python-repl + ```python-repl:3 >>> import math as m >>> >>> print(m.pi) @@ -184,7 +184,7 @@ Pythonの大きな魅力の一つは、その「**バッテリー同梱 (Batteri また、REPLの `help()` や `dir()` を使うと、モジュールの内容を簡単に確認できます。 -```python-repl +```python-repl:4 >>> import datetime >>> # datetimeモジュールが持つ属性や関数のリストを表示 >>> dir(datetime) @@ -207,7 +207,7 @@ class date(builtins.object) * **`os`**: オペレーティングシステムと対話するための機能を提供します。ファイルやディレクトリの操作、環境変数の取得などができます。 - ```python-repl + ```python-repl:5 >>> import os >>> # カレントディレクトリのファイル一覧を取得 >>> os.listdir('.') @@ -219,7 +219,7 @@ class date(builtins.object) * **`sys`**: Pythonインタプリタ自体を制御するための機能を提供します。コマンドライン引数の取得や、Pythonの検索パスの確認などができます。 - ```python-repl + ```python-repl:6 >>> import sys >>> # Pythonのバージョンを表示 >>> sys.version # 環境により異なります @@ -228,7 +228,7 @@ class date(builtins.object) * **`datetime`**: 日付や時刻を扱うための機能を提供します。 - ```python-repl + ```python-repl:7 >>> import datetime >>> # 現在の日時を取得 (実行時刻による) >>> now = datetime.datetime.now() @@ -241,7 +241,7 @@ class date(builtins.object) * **`json`**: Web APIなどで広く使われているデータ形式であるJSONを扱うための機能を提供します。 - ```python-repl + ```python-repl:8 >>> import json >>> # Pythonの辞書型データ >>> user = {"id": 1, "name": "Ken", "email": "ken@example.com"} diff --git a/public/docs/python-7.md b/public/docs/python-7.md index 5636bbe..ed69636 100644 --- a/public/docs/python-7.md +++ b/public/docs/python-7.md @@ -15,7 +15,7 @@ Pythonでファイルを操作するには、まず組み込み関数の **`open * `'+'` を付けると読み書き両用になります(例: `'r+'`, `'w+'`)。 * `'b'` を付けるとバイナリモードになります(例: `'rb'`, `'wb'`)。 -```python-repl +```python-repl:1 >>> # 'w' モードでファイルを開く(または新規作成する) >>> f = open('spam.txt', 'w', encoding='utf-8') >>> f @@ -35,7 +35,7 @@ Pythonでファイルを操作するには、まず組み込み関数の **`open **`write()`** メソッドは、文字列をファイルに書き込みます。このメソッドは書き込んだ文字数を返します。 -```python-repl +```python-repl:2 >>> f = open('test.txt', 'w', encoding='utf-8') >>> f.write('こんにちは、世界!\n') 9 @@ -59,7 +59,7 @@ Pythonでファイルを操作するには、まず組み込み関数の **`open * **`readline()`**: ファイルから1行だけを読み込み、文字列として返します。 * **`readlines()`**: ファイルのすべての行を読み込み、各行を要素とするリストで返します。 -```python-repl +```python-repl:3 >>> # 先ほど書き込んだファイルを読み込む >>> f = open('test.txt', 'r', encoding='utf-8') >>> content = f.read() @@ -87,7 +87,7 @@ Pythonでファイルを操作するには、まず組み込み関数の **`open **`with`** 文のブロックを抜けると、ファイルオブジェクトは自動的に `close()` されます。エラーが発生した場合でも同様です。これは「コンテキストマネージャ」という仕組みによって実現されており、ファイル操作の標準的な方法です。 -```python-repl +```python-repl:4 >>> # with文を使った書き込み >>> with open('spam.txt', 'w', encoding='utf-8') as f: ... f.write('withブロックを使っています。\n') @@ -123,7 +123,7 @@ withブロックを使っています。 -```python-repl +```python-repl:5 >>> import json >>> # 書き込むデータ(Pythonの辞書) @@ -172,7 +172,7 @@ withブロックを使っています。 **`csv.writer()`** を使ってライターオブジェクトを作成し、**`writerow()`** (1行) や **`writerows()`** (複数行) メソッドでデータを書き込みます。 -```python-repl +```python-repl:6 >>> import csv >>> # 書き込むデータ(リストのリスト) @@ -201,7 +201,7 @@ ID,Name,Score **`csv.reader()`** を使ってリーダーオブジェクトを作成します。このオブジェクトをループで回すことで、1行ずつリストとしてデータを取得できます。 -```python-repl +```python-repl:7 >>> import csv >>> with open('scores.csv', 'r', newline='', encoding='-utf-8') as f: diff --git a/public/docs/python-8.md b/public/docs/python-8.md index e1bfba4..91618b5 100644 --- a/public/docs/python-8.md +++ b/public/docs/python-8.md @@ -8,7 +8,7 @@ 例えば、`0` で割り算をすると `ZeroDivisionError` という例外が発生します。 -```python-repl +```python-repl:1 >>> 10 / 0 Traceback (most recent call last): File "", line 1, in @@ -17,7 +17,7 @@ ZeroDivisionError: division by zero このエラーを `try...except` で捕捉してみましょう。 -```python-repl +```python-repl:2 >>> try: ... result = 10 / 0 ... except ZeroDivisionError: @@ -38,7 +38,7 @@ ZeroDivisionError: division by zero エラーの種類ごとに異なる処理を行いたい場合に適しています。 -```python-repl +```python-repl:3 >>> def calculate(a, b): ... try: ... a = int(a) @@ -62,7 +62,7 @@ ZeroDivisionError: division by zero 複数の例外に対して同じ処理を行いたい場合に便利です。 -```python-repl +```python-repl:4 >>> def calculate_v2(a, b): ... try: ... a = int(a) @@ -86,7 +86,7 @@ ZeroDivisionError: division by zero 例えば、負の値を受け付けない関数を考えてみましょう。 -```python-repl +```python-repl:5 >>> def process_positive_number(num): ... if num < 0: ... raise ValueError("負の値は処理できません。") @@ -112,7 +112,7 @@ ValueError: 負の値は処理できません。 すべての節を使った例を見てみましょう。 -```python-repl +```python-repl:6 >>> def divider(a, b): ... print(f"--- {a} / {b} の計算を開始します ---") ... try: diff --git a/public/docs/python-9.md b/public/docs/python-9.md index a31652c..11e00cc 100644 --- a/public/docs/python-9.md +++ b/public/docs/python-9.md @@ -13,7 +13,7 @@ Pythonの`for`ループは非常にシンプルで強力ですが、その裏側 REPLで動きを見てみましょう。`iter()`関数でイテレータを取得し、`next()`関数で要素を取り出します。 -```python-repl +```python-repl:1 >>> my_list = [1, 2, 3] >>> my_iterator = iter(my_list) >>> type(my_iterator) @@ -45,7 +45,7 @@ StopIteration フィボナッチ数列を生成するジェネレータの例を見てみましょう。 -```python-repl +```python-repl:2 >>> def fib_generator(n): ... a, b = 0, 1 ... count = 0 @@ -86,7 +86,7 @@ StopIteration リスト内包表記はリストオブジェクトを生成するため、要素数が多いとメモリを大量に消費します。一方、ジェネレータ式はジェネレータオブジェクトを返すため、遅延評価(必要になるまで計算しない)が行われ、メモリ使用量を抑えられます。 -```python-repl +```python-repl:3 # リスト内包表記 >>> list_comp = [i * 2 for i in range(5)] >>> list_comp @@ -127,7 +127,7 @@ StopIteration 関数の実行前後にメッセージを表示する簡単なデコレータを見てみましょう。 -```python-repl +```python-repl:4 >>> def my_decorator(func): ... def wrapper(): ... print("--- 処理を開始します ---") @@ -150,7 +150,7 @@ StopIteration この書き方をより簡単にするための構文が `@`(アットマーク)、シンタックスシュガーです。 -```python-repl +```python-repl:5 >>> @my_decorator ... def say_goodbye(): ... print("さようなら!")