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.

プロンプトエンジニアリング【新規コーディング編】例:Zero-shot

0
Last updated at Posted at 2026-10-30

本記事は、プロンプトエンジニアリングについて【新規コーディング編】の記事で比較した「Zero-shot」による、説明用のサンプル記事です。
以下はAIの回答結果です。構成案の妥当性を保証するものではありません。

入力プロンプト

以下の要件を満たすPythonプログラムを作成してください。

【作業依頼】
売上CSVファイルを読み込み、商品別の売上金額と全体の合計金額を表示するPythonプログラムを新規作成したい。

【機能要件】
・CSVにはdate、product、quantity、priceの列がある
・売上金額はquantity × priceで計算する
・商品別の売上金額を集計する
・全商品の売上合計を表示する
・商品はCSVに最初に登場した順番で表示する

【制約条件】
・Pythonの標準ライブラリのみを使用する
・CSVファイル名はsales.csvとする
・結果はコンソールに表示する

【回答形式】
・完成したPythonコードを提示してください
・コードの実行方法を簡潔に説明してください
・使用した標準ライブラリを説明してください

AIの回答(実行方法の説明を省略)

1. 完成したPythonコード

以下のプログラムでは、sales.csv を読み込み、商品別の売上金額と全商品の売上合計をコンソールに表示します。

ファイル名:sales_summary.py

import csv

# 商品別の売上金額を保存する辞書
product_sales = {}

# 全商品の売上合計
total_sales = 0

# CSVファイルを読み込む
with open("sales.csv", mode="r", encoding="utf-8-sig", newline="") as file:
    reader = csv.DictReader(file)

    for row in reader:
        product = row["product"]
        quantity = int(row["quantity"])
        price = int(row["price"])

        # 売上金額を計算
        amount = quantity * price

        # 商品別に売上金額を集計
        if product not in product_sales:
            product_sales[product] = 0

        product_sales[product] += amount

        # 全商品の売上合計を加算
        total_sales += amount

# 集計結果を表示
print("商品別売上金額")

for product, amount in product_sales.items():
    print(f"{product}: {amount}円")

print("--------------------")
print(f"全商品の売上合計: {total_sales}円")

Python 3.7以降では辞書の挿入順序が保証されるため、商品はCSVに最初に登場した順番で表示されます。

2. 入出力例

入力ファイル:sales.csv

date,product,quantity,price
2026-10-01,りんご,3,150
2026-10-01,みかん,5,100
2026-10-02,りんご,2,150
2026-10-02,バナナ,4,120
2026-10-03,みかん,3,100

実行結果:

商品別売上金額
りんご: 750円
みかん: 800円
バナナ: 480円
--------------------
全商品の売上合計: 2030円

3. 使用した標準ライブラリ・機能

ライブラリ・機能 用途
csv CSVファイルの読み込み
csv.DictReader 列名をキーとして各行のデータを取得
open() CSVファイルを開く
dict(組み込み型) 商品別の売上金額を保持
int()(組み込み関数) 数量と単価を整数に変換
print() 集計結果をコンソールに表示

外部ライブラリのインストールは不要です。

4. 要件への対応状況

要件 対応状況 実装方法
CSVの読み込み 対応 csv.DictReader
売上金額の計算 対応 quantity * price
商品別の集計 対応 辞書による加算
全商品の売上合計 対応 total_sales += amount
商品の登場順を維持 対応 辞書の挿入順序を利用
標準ライブラリのみ 対応 csv のみ使用
コンソール出力 対応 print()

補足: このプログラムは、CSVの数量と単価が整数であり、必須列が存在することを前提としています。小数の単価、不正なデータ、ファイルが存在しない場合などの例外処理は、今回の要件に含まれていないため実装していません。

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?