python_beginner
python_beginner

Reputation: 23

Can't break out of the loop where i want

I tried to program a chatbot. Everything works great for the most part, but if I want to break out of my loop with the word 'bye', the program generates an answer from the 'randomanswers' list. What can I do to only have my print command as output? Thanks in advance!

Here is my code:

import random

print("Welcome to Chatbot! Have fun.")
print("")
randomanswer = ['Thats not good', 'me too', 'how about you?']
reactionanswer = {'hello': 'hello, whats up?',
                  'sad': 'speak to me',
                  'entertainment': 'how can i entertain you?'}
userinput = ''
while True:
    if userinput == 'bye':
        print("See you soon!")
        break
    else:
        userinput = input("Question/Answer: ")
        userinput = userinput.lower()
        usersplit = userinput.split()
    
        for i in usersplit:
            if i in reactionanswer:
                print(reactionanswer[i])
            else:
                print(random.choice(randomanswer))



Upvotes: 1

Views: 51

Answers (2)

agenel
agenel

Reputation: 155

if you follow the flow of the while loop, you can see it goes directly into 'else:' section. It is better to ask input just after while loop started!

Upvotes: 0

Henry Harutyunyan
Henry Harutyunyan

Reputation: 2425

This is because you are checking for 'bye' after the next loop iteration, which is after checking it in the list reactionanswer, this it executes this print(random.choice(randomanswer))

Try doing

import random

print("Welcome to Chatbot! Have fun.")
print("")
randomanswer = ['Thats not good', 'me too', 'how about you?']
reactionanswer = {'hello': 'hello, whats up?',
                  'sad': 'speak to me',
                  'entertainment': 'how can i entertain you?'}
userinput = ''
while True:
    userinput = input("Question/Answer: ")
    userinput = userinput.lower()

    if userinput == 'bye':
        print("See you soon!")
        break

    usersplit = userinput.split()

    for i in usersplit:
        if i in reactionanswer:
            print(reactionanswer[i])
        else:
            print(random.choice(randomanswer))

Upvotes: 1

Related Questions