所以这只是基本的Python。它使用if,else语句和while循环来创建基于选择的响应。有没有办法使其更简洁?另外,我真的很想知道如何做到这一点,因此,如果用户输入的内容不是“是”或“否”,它就会重复这些问题。谢谢:)!
def func1():
while True:
raining = input('Is it raining?: ')
if raining == 'yes':
A1 = input('Have an umbrella?: ')
if A1 == 'no':
Q1 = 'yes'
while Q1 == 'yes':
print('Wait a while.')
Q1 = input('Is it raining? ')
if Q1 == 'no':
print('go outside')
elif A1 == 'yes':
print('go outside...')
elif raining == 'no':
print('go outside...')
答案 0 :(得分:1)
您可以在出门时跳出while
循环,将预定义的答案放入列表中,而不必将问题存储在变量中,您可以这样做:
yes = ['y','yes']
no = ['n', 'no']
def func1():
cant_go_outside = True
while cant_go_outside:
if input('Is it raining?: ') in yes:
if input('Have an umbrella?: ') in no:
while cant_go_outside:
print('Wait a while.')
if input('Is it raining?: ') in no:
print('go outside...')
cant_go_outside = False
else:
print('go outside...')
cant_go_outside = False
else:
print('go outside...')
cant_go_outside = False
答案 1 :(得分:1)
您可以将问题循环放在返回布尔值的通用函数中。这将允许其余代码直接使用和/或逻辑:
def getAnswer(question):
while True:
answer = input(question)
if answer in ["yes","no"]: return answer == "yes"
def func1():
while True:
if getAnswer("Is it raining?: ") \
and not getAnswer("Have an umbrella?: "):
while getAnswer("Wait a while.\nIs it still raining?: "): pass
print("go outside...")
另一种方法是构建“元数据”(即将驱动通用程序行为的数据)。这样,您无需编写新功能/程序即可创建完全不同的决策树。
def decide(decisions, step="Q1"):
while True:
prompt,*nextSteps = decisions[step]
if "Q" in step: answer = input(prompt+": ")
else: answer = print(prompt) or "no"
if answer not in ["yes","no"]: continue
step = nextSteps[answer=="yes"]
在这种情况下,元数据是步骤的词典,可以是是/否问题或简单的打印语句。每个步骤都表明下一步是什么,可以选择两个(针对问题),也可以选择一个下一步(针对语句)。
example1:
rainyDay = { "Q1":("Is it raining?","P1","Q2"),
"P1":("go outside...","Q1"),
"Q2":("Have an umbrella?","P2","P1"),
"P2":("Wait a While.","Q3"),
"Q3":("Is it still raining?","P1","P2")
}
decide(rainyDay)
Is it raining?: no
go outside...
Is it raining?: r
Is it raining?: yes
Have an umbrella?: yes
go outside...
Is it raining?: yes
Have an umbrella?: no
Wait a While.
Is it still raining?: no
go outside...
Is it raining?: yes
Have an umbrella?: yes
go outside...
Is it raining?:
example2:
happiness = { "Q1":("Do you have a problem ?","P1","Q2"),
"P1":("Be Happy!","Q1"),
"Q2":("Can you do something about it","P1","P2"),
"P2":("Do It!","Q1"),
}
decide(happiness)
Do you have a problem ?: no
Be Happy!
Do you have a problem ?: yes
Can you do something about it: no
Be Happy!
Do you have a problem ?: yes
Can you do something about it: yes
Do It!
Do you have a problem ?: no
Be Happy!
Do you have a problem ?: