Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Conditionals aren't working.

+2 votes
asked Mar 2 by JuSt HoTMaiL CurSeS (330 points)

So... I'm doing a chatbot for fun and every sentence i write it returns the first conditional. I've tried:

 - Convert conditionals to variables.

 - Use text.find(text)

 - Use different compilers:

      · Python.org: the same

      · w3schools: no EOL allowed

Thank you in advance! (Code below)

import math
import random
import time

while True:
    text = input().lower().split()
    if "hello" or "hi" or "greetings" in text:
        print('Hello! I\'m PyChat, an artificial intelligence. How may I help you? ')
    elif "enjoy" or "like" or "fun" or "enjoys" or "likes" in text:
        print('I also enjoy that, what a coincidence!')

3 Answers

+1 vote
answered Mar 2 by Peter Minarik (79,780 points)

The problem is that your expression is evaluated like this:

if ("hello") or ("hi") or ("greetings" in text")

A string literal is always true, hence your program always prints "Hello..."

Instead, you could create a set of the keywords from the input and compare it to a set that contains the greetings. If these sets have an intersection (i.e. they are not disjoint), only then you print your message.

The code would be something like this:

greetings =  { "hi", "hello", "greetings" }
interests = { "enjoy", "enjoys", "like", "likes", "fun" }

while True:
    keywords = set(input().lower().split())
    if not keywords.isdisjoint(greetings):
        print('Hello! I\'m PyChat, an artificial intelligence. How may I help you?')
    elif not keywords.isdisjoint(interests):
        print('I also enjoy that, what a coincidence!')
commented Mar 2 by JuSt HoTMaiL CurSeS (330 points)
Thank you! SOLVED
0 votes
answered Mar 2 by Eidnoxon (4,370 points)
Hi! I tried to fix your problem. Here you go:

https://onlinegdb.com/iDPwY_Op3
0 votes
answered Mar 2 by Mike Finch (300 points)

The short answer is that order of operations is killing you.

6. Expressions — Python 3.11.2 documentation

 If you are not sure what order python is acting on your conditional specify.

Let me know if you need a sample..

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...