我几天前问过这个Q,如果你帮助我,我会很感激。然而,一位绅士pepr已经插手了。我似乎跑到了一堵砖墙。我的代码是供儿童玩的游戏。它如下:
import re
import sys
name = input
name = input('Please Enter your question: ').lower()
name2 - name[:]
for item in name2:
if len(name2) >= 3:
MODULE1
elif len(name2) >= 3:
MODULE2
elif len(name2) >=3:
MODULE3............# CONTINUES LIKE THIS FOR THESE MODULES
示例模块 MODULE1
import re
import sys
name = input
name = input(Please Enter your question: ').lower
name2 = name[:]
colorLists = ['what is my color', 'color', ...]# this list have about 5mb of sample lists.Other lists have items for foods, cars, toys etc
for item in name2:
if item in name2 and in colorLists:
print('you found the color here')
name3 = input('What is your favorite color?')
if name3 == red:
print('You are hot!')
elif name3 == pink:
print('You must be a lady')
elif name3 == blue:
print('Boys love this')
elif....#continues with as many colors as possible
模块2,3,4等有不同的游戏,比如汽车,家庭,食品,玩具等 回到上面的相同问题,一旦我导入MODULES,只运行第一个模块。我希望它的工作方式是,如果问题不在MODULE1中,它将跳转到MODULE2。 再一次,我是Python新手,非常感谢您的帮助!
答案 0 :(得分:1)
使用各个游戏的功能或类来使它们更紧凑。我举个简单的例子:
main.py:
import games
GAMES = ('color', 'food', 'car', 'toy')
while True:
question = input('Please enter your question: ').lower()
if not question:
break
for g in GAMES:
if g in question:
getattr(games, g)()
break
else:
print('I do not have a game for that! :(')
print('Byebye!')
games.py:
COLORS = {
'blue': 'Boys love this.',
'pink': 'You must be a lady.',
'red': 'You are hot!',
}
def color():
print('You found the color here.')
while True:
answer = input('What is your favorite color? ').lower()
if answer in COLORS:
print(COLORS[answer])
return
else:
print('I don\'t know such a color.')
def food():
print('Don\'t eat so much!')
示例运行:
D:\test>python main.py
Please enter your question: what color I like
You found the color here.
What is your favorite color? blue
Boys love this.
Please enter your question: what food I like
Don't eat so much!
Please enter your question: when I was born
I do not have a game for that! :(
Please enter your question:
Byebye!
编辑回答评论:导入它们并将匹配的函数放到字典中。例如:
main.py:
import games
import games2
import games3
GAMES = {
'color': games.color,
'food': games.food,
'car': games.car,
'toy': games.toy,
'somethingelse': games2.somethingelsefunction,
}
while True:
question = input('Please enter your question: ').lower()
if not question:
break
for key, func in GAMES.items():
if key in question:
func()
break
else:
print('I do not have a game for that! :(')
print('Byebye!')