1

I am messing around with this basic Magic 8 Ball program and im trying to make it only allow yes or no questions I am thinking that it will only except questions that have the first word "will" or "do" how can I make a that only allows those to words?

Here is the Script:

import random
import time
print "Welcome to Magic Eight Ball !"
while True:
    def Magic8(a):
        foo = ['Yes', 'No', 'Maybe', 'Doubtful', 'Try Again']
        from random import choice
        print choice(foo)


    a = raw_input("Question: ")
    if a == "exit":
        exit()
    #If Stament here
    print "Determining Your Future..."
    time.sleep(2)
    Magic8(a)

3 Answers 3

4
if a.split(None, 1)[0].lower() in {'will', 'do'}:
    print "Determining Your Future..."
    time.sleep(2)
    magic8(a) # function names are usually not capitalized

str.split() splits the sentence on whitespace, str.lower should handle the uppercase.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use str.startswith and pass a tuple of accepted words.

if a.lower().startswith(("will ", "do ")):
   # Do your magic.

1 Comment

Nice, and simpler than my answer, but you probably have to add a space there: 'will ', 'do ', otherwise there can be false positives: 'William is a unicorn'. Also you need to account for the capitalization.
1

maybe if you have little words you can use elif or or

if a=="exit":
    exit()
elif a=="optionOne":
     doSomething
else:
    print "word not alowed"

Or you can do like this

if a=="exit" or a=="notAllowedWord":
    exit()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.