【问题标题】:User input code returning incorrect responses用户输入代码返回错误响应
【发布时间】:2019-04-09 01:27:56
【问题描述】:

我正在用 Python 3 教我的学生一些简单的代码,我们使用 if/elif/else 语句以及用户输入来编写简单的“选择你自己的冒险”故事。我第一次编写此代码时,它按预期运行。现在,无论输入什么输入,它总是提供第一个选项。谁能解释这是为什么?谢谢!感谢大家!我的问题已经解决了。

cave=input('Would you like to enter the cave? Answer Y or N')

if cave == ('Y') or ('y'):
    print('The cave is cold.')
elif cave == ('N') or ('n'):
    print('Stay in the sunshine. Safe, but boring.')
else:
    print('That was not one of the choices.') 

tool= input ("You have two items in your bag: a torch and a sandwich. 
Which would you like to use?")
if tool == ("torch"):
    print ("The fire ignites the deadly gas that has built up in the 
cave. You die.")
elif tool ==("sandwich"):
    print ("Good idea. You'll need strength to explore the cave.")
else:
    print ("Why do you insist on making things difficult?")

【问题讨论】:

  • cave == ('Y') or ('y') 评估为(cave == 'Y') or True,始终为True
  • 顺便说一句,如果我说'N'然后是'Torch',如果我不在山洞里,我为什么会死?

标签: python-3.x


【解决方案1】:

计算这个语句是真还是假是模棱两可的

if cave == ('Y') or ('y'): 

应该是

if cave == ('Y') or cave == ('y'):

【讨论】:

    【解决方案2】:

    在 Python 中,没有“多重方程式检查”。当你想创建它时,你应该使用这样的东西:

    if a == b or a == c:
        #some code here...
    

    您也可以在中使用

    if a in (b, c):
        #some code here...
    

    if a in [b, c]:
        #more code...
    

    (这有点慢,所以在游戏中我推荐第一个)

    【讨论】:

      猜你喜欢
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 2016-02-20
      • 2017-05-27
      • 2014-11-13
      • 2021-11-07
      • 2014-03-14
      • 2018-02-13
      相关资源
      最近更新 更多