对不起,我是新来的人,但我希望有人可以帮助我解决一个非常简单的语法问题。我正在尝试输入"flowers"
或"the flowers"
,但是Python并未在字符串" "
中注册 SPACE ("the flowers"
)。 ,因此使"the candles"
的第二个选项始终无效。有人可以帮助我理解为什么会发生这种情况以及如何在字符串中输入带有空格的输入参数吗?
delay_print("Which decorations do you want to work on -- flowers or candles? ")
choice1 = input()
print('')
print('')
if choice1.lower() == 'flowers' or 'the flowers':
delay_print('''
Flowers! Great choice! You take those and I will take the candles!
Meet me outside once you're done trimming the thorns and cutting the stems from
the flowers. Don't forget to grab the water pail so we can keep them hydrated!
''')
elif choice1.lower() == 'candles' or 'the candles':
delay_print('''
Candles! Fantastic choice! You take those and I will take the flowers!
Meet me outside once you're done cleaning out the excess wax and trimming the wicks!
Don't forget to grab the light so we have something to light them with!
''')
else:
delay_print("Sorry little one, we don't have those this year.")
答案 0 :(得分:1)
您的条件“不正确”:
if choice1.lower() == 'flowers' or 'the flowers':
...
...的评估为:
choice1.lower() == 'flowers'
OR 要么只是'the flowers'
,要么永远是真实的(字符串'the flowers'
总是“真实的”) < / p>
您应该做的是这样:
if choice1.lower() == 'flowers' or choice1.lower() == 'the flowers':
...
...或更漂亮:
lower_choice = choice1.lower()
if lower_choice == 'flowers' or lower_choice == 'the flowers':
...
elif lower_choice == 'candles' or lower_choice == 'the candles':
...
答案 1 :(得分:0)
问题是您的if
/ else
条件的结构不正确。他们没有测试您的想法。
if choice1.lower() == 'flowers' or 'the flowers':
delay_print(''' ... ''')
elif choice1.lower() == 'candles' or 'the candles':
delay_print(''' ... ''')
让我们在python控制台中对此进行测试:
>>> choice1 = "Flowers"
>>> choice1.lower() == "flowers"
True
到目前为止,太好了。 花会怎样?
>>> choice1 = "The Flowers"
>>> choice1.lower() == "flowers"
False
# That's what we expected, now the second part after the 'or'
# is just a string, there's no comparison happening.
>>> "the flowers"
'the flowers'
# In python, this counts as a True in a condition
>>> bool("the flowers")
True
# So what's missing is the condition...
>>> choice1.lower() == "the flowers"
True
使用您的代码示例,您将第一个条件更新为:
if choice1.lower() == "flowers" or choice1.lower() == "the flowers":
delay_print(''' ... ''')
将相同的想法应用于您的elif
条件,它应该可以工作。
答案 2 :(得分:-2)
如果您不限制用户的输入,我会做出这样的提示:
if 'flower' in choice1.lower():
<do your flower stuff>
elif 'candle' in choice1.lower():
<do your candle stuff>
else:
<do your default stuff>
这将帮助您捕获带有花朵或蜡烛的任何用户输入。