python3を勉強中の初心者です。
今、”一番優しいpythonの教本”という本で独学しているのですが
その中のpython3の標準ライブラリである
randomモジュールを使ったプログラムを書く部分で躓いています。
どうすればプログラムが動くか
解決したいです。
よろしくお願いします。
前提・実現したいこと
ここに質問の内容を詳しく書いてください。
(例)PHP(CakePHP)で●●なシステムを作っています。
■■な機能を実装中に以下のエラーメッセージが発生しました。
発生している問題・エラーメッセージ
エラーメッセージ 1``` Traceback (most recent call last): File "aisatu_bot.py", line 47, in <module> response = choice_command(command) File "/Users/gorigorinogorira/Desktop/golira/random.py", line 5, in choice_command choiced = choice(data[1:]) NameError: name 'choice' is not defined 2 Traceback (most recent call last): File "aisatu_bot.py", line 49, in <module> response = dice_command(command) File "/Users/gorigorinogorira/Desktop/golira/random.py", line 10, in dice_command num = random.randrange(1, 100) AttributeError: module 'random' has no attribute 'randrange' ### 該当のソースコード ```ここに言語名を入力 ソースコード 1 from import_eto import eto_command from random import choice_command, dice_command def len_command(command): cmd, text = command.split() length = len(text) response = "文字列の長さは{}です".format(length) return response def heisei_command(command): heisei, year_str = command.split() year = int(year_str) if year >= 1989: heisei_year = year - 1988 response = "西暦{}年は、平成{}年です".format(year, heisei_year) else: response = "西暦{}年は、平成ではありません".format(year) return response aisatu_file = open("aisatu.txt", encoding="utf-8") raw_data = aisatu_file.read() aisatu_file.close lines = raw_data.splitlines() bot_dict = {} for line in lines: word_list = line.split(",") key = word_list[0] response = word_list[1] bot_dict[key] = response while True: command = input("なんか言え ") response = "" for key in bot_dict: if key in command: response = bot_dict[key] break if "平成" in command: response = heisei_command(command) if "長さ" in command: response = len_command(command) if "干支" in command: response = eto_command(command) if "選ぶ" in command: response = choice_command(command) if "サイコロ" in command: response = dice_command(command) if not response: response = "日本語喋れや豚野郎" print(response) if "さようなら" in command: print("二度と開くなよまじで") break 2 import random def choice_command(command): data = command.split() choiced = random.choice(data[1:]) response = "「{}」が選ばれました".format(choiced) return response def dice_command(command): num = random.randrange(1, 100) response = "「{}」の目が出ました".format(num) return response ### 試したこと ここに問題に対して試したことを記載してください。 書き直してみましたが、どうにもなりませんでした。 ### 補足情報(FW/ツールのバージョンなど) ここにより詳細な情報を記載してください。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/03/07 07:29