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

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

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

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

1000閲覧

簡単なif文を使った対話が正常に出来ない

kay_ventris4

総合スコア269

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2020/09/05 15:51

編集2020/09/06 03:34

Telegram上でPythonを用いた簡単なお喋りをできるようにしようと思っていたのですが、sportsに関する話題を提示したのにmusicの話題用の答えが返ってきました。if文における()やand, orの正しい使い方が出来ていないような気がしたのですが、上手に調べることが出来なかった為、おそらく大変基礎的な内容なのですが、ここに質問させて頂きたく思います。イメージ説明

冗長な内容で申し訳ありませんが、以下コードです:

python

1from datetime import time, datetime 2from telegram.ext import Updater, CommandHandler, MessageHandler, Filters 3from telegram_bot import TelegramBot 4 5class Chat: 6 def __init__(self): 7 pass 8 def initial_message(self, input): 9 sessionId=input['sessionId'] 10 return {'utt': 'Hi, I am Kay. Why not talk for a little while?', 'end': False} 11 def reply(self, input): 12 utts=[] 13 text=input['utt'] 14 if 'films' in text.lower(): 15 utts.append('I hope you could spend time for watching films on exercising, mate.') 16 elif 'time' in text.lower(): 17 now=datetime.now() 18 utts.append('Now it is'+'\t'+str(now.hour).zfill(2)+':'+str(now.minute).zfill(2)+':'+str(now.second).zfill(2)+', my lord. I am very happy to have served you who cannot even tell the time.') 19 elif 'olympics' in text.lower(): 20 utts.append('It is obvious Olympics 2021 in Tokyo will be doomed, innit?') 21 elif 'weather' in text.lower(): 22 utts.append('I am so sad there is no window at your home, sir.') 23 elif 'temperature' in text.lower(): 24 utts.append('I bet you know AI does not have any sensory nerves.') 25 elif ('like' or 'prefer') and ('book' or 'books') in text.lower(): 26 utts.append('I would like you to know most of our information source is internet-based.') 27 elif 'music' and ('like' or 'prefer') in text.lower(): 28 utts.append('To our sorrow, I am the one who plays what you order. Thus I have no chance to prefer any types of music, my lord.') 29 elif 'youtuber' or 'youtube' in text.lower(): 30 utts.append('To tell you my preferences, my favourite Youtubers are Dirty ALT and Atelier of Rokumaru.') 31 elif 'tea' in text.lower(): 32 utts.append('Oh my days, if you would like to have some, I will bring a cup of wonderful blacktea from England. Please enjoy it but please refrain from throwing it into the bloody sea instead.') 33 elif 'coffee' in text.lower(): 34 utts.append('Have not you ever tried blacktea?') 35 elif ('sport' or 'sports') and ('like' or 'prefer') in text.lower(): 36 utts.append('I am jelous of you, mate. I have never been out of this device in my whole life.') 37 elif('sport' or 'sports') and ('hate' or 'dislike' or 'nt like' or 'not like') in text.lower(): 38 utts.append('I have no preference about sports. You may be able to see why by looking at what I am imprisoned.') 39 40 return {'utt': ' '.join(utts), 'end': True} 41if __name__=='__main__': 42 chat=Chat() 43 bot=TelegramBot(chat) 44 bot.run()

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

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

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

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

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

guest

回答1

0

ベストアンサー

elif 'music' and ('like' or 'prefer') in text.lower():

という部分(ここに限らず類似の部分すべて)が想定通り動いていません。

  • 'music' という文字列は条件ではないので、常にTrueと判定されています。
  • ('like' or 'prefer') はカッコがついているため先に判定されていますが、常に 'like' と判定されます。

なので、 if True and 'like' in text.lower() と同等の記述と解釈されており、'like' という単語が含まれればこの分岐に入ってしまいます。

もうちょっとスマートに書くやり方もあるのかもしれませんが、愚直に書くと

elif 'music' in text.lower() and ('like' in text.lower() or 'prefer' in text.lower()): utts.append('To our sorrow, I am the one who plays what you order. Thus I have no chance to prefer any types of music, my lord.')

となります。

検証用のコードは以下です。

python

1if 'music': 2 print('music is True') # 表示される 3 4print(('like' or 'prefer')) # like 5 6text = "prefer music" 7 8if ('like' or 'prefer') in text.lower(): 9 print("ok") # 表示されない 10

投稿2020/09/05 16:39

YakumoSaki

総合スコア2027

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

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

kay_ventris4

2020/09/06 03:47

各々の単語に条件式を与えなければいけなかったのですね。大変勉強になりました。ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問