質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.49%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

1回答

2278閲覧

Python3 実行後KeyErrorが出てしまいます。

gaijin

総合スコア30

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2018/10/30 23:46

昨日回答いただきこちらでcodeを変更いたしました。
ターミナルで実行しているのですがこのように

File "05_file.py", line 44, in <module> evaluation = evaluation_dict[student_name] KeyError: 'Takanori Suzuki'

とエラーが出ます。

下記のように定義しております。

open_file = open('point.txt') raw_data = open_file.read() open_file.close() point_data = raw_data.splitlines() point_dict = {} for line in point_data: student_name, points_str = line.split(':') point_dict[student_name] = points_str score_dict = {} for student_name in point_dict: point_list = point_dict[student_name].split(',') subject_number = len(point_list) total = 0 for point in point_list: total = total + int(point) average = total / subject_number score_dict[student_name] = (total, average, subject_number) evaluation_dict = {} for student_name in score_dict: score_data = score_dict[student_name] total = score_data[0] average = score_data[1] subject_number = score_data[2] excellent = subject_number * 100 * 0.8 good = subject_number * 100 * 0.65 if total >= excellent: evaluation = 'Excellent' elif total >= good: evaluation = 'Good' else: evaluation = 'Bad' evaluation_dict[student_name] = evaluation file_name = 'evaluation.txt' output_file = open(file_name, 'w') for student_name in score_dict: score_data = score_dict[student_name] total = score_data[0] evaluation = evaluation_dict[student_name] text = '[{}] total: {}, evaluation: {}\n'.format(student_name, total, evaluation) output_file.write(text) output_file.close() print('評価結果を{}に出力しました'.format(file_name))

保存ファイルには下記のように
入力しております。

Takanori Suzuki:100,88,81 Takayuki Shimizukawa:77,94,85 Mitsuki Sugiya:80,52,99

独学にて学んでおります。
どうぞご教授いただければと思います。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

以下の部分のインデントがおかしいです。totalがbadの場合しか辞書に登録されていません。
なお、さらにもう一か所、終了処理付近にもインデントがおかしい部分があります。
ソースコードを良く確認ください。

Python

1# 略 2for student_name in score_dict: 3 # 略 4 good = subject_number * 100 * 0.65 5 if total >= excellent: 6 evaluation = 'Excellent' 7 elif total >= good: 8 evaluation = 'Good' 9 else: 10 evaluation = 'Bad' 11 #evaluation_dict[student_name] = evaluation # NG 12 evaluation_dict[student_name] = evaluation # OK 13# 略

投稿2018/10/31 00:58

can110

総合スコア38256

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

gaijin

2018/10/31 13:39

帰宅が遅くなり返信遅くなってしまい申し訳ございません。 can110様がおっしゃる様にインデントを直しただけで実行されました。 インデントがどれだけ重要なのか身をもってわかりました。 本当に実行された時の喜びはなんとも言えないです。 感謝いたします。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.49%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問