1

我正在搞乱这个基本的 Magic 8 Ball 程序,我试图让它只允许是或否的问题我认为它只会除了第一个单词“will”或“do”的问题只允许那些话?

这是脚本:

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)
4

3 回答 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()在空格上分割句子,str.lower应该处理大写。

于 2013-04-19T21:21:18.823 回答
2

您可以使用str.startswith并传递一组接受的单词。

if a.lower().startswith(("will ", "do ")):
   # Do your magic.
于 2013-04-19T21:22:52.810 回答
1

也许如果你有小词,你可以使用 elif 或 or

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

或者你可以这样做

if a=="exit" or a=="notAllowedWord":
    exit()
于 2013-04-19T21:51:33.193 回答