【问题标题】:Python code is skipping to elsePython 代码跳到 else
【发布时间】:2016-03-23 21:37:51
【问题描述】:

嗨,这是我的代码,由于某种原因,在最后一个 for 循环之后,代码直接跳到 else 语句并打印大约 4 次,然后转到 if 语句并打印解决方案。请有人帮忙解决这个问题。

while True:
   d = {}
   with open("keyword_database.txt") as f:
       for line in f:
          (key,val) = line.split(":")
          d[str(key)] = val
   try:
      userinput=input(str("What is the problem with your phone?\nEnter here in lower:"))
      print()
   except:
      print ("Invalid Input")
   for word in userinput.split(): 
           if word in d:
              print(d[word])
              print()
           else:
              print("Please Re-Phrase your problem and Try Again")
              print()

这就是我运行代码后打印的内容。

您的手机有什么问题?在下面输入:我的手机是 坏了

请重新表述您的问题并重试

请重新表述您的问题并重试

请重新表述您的问题并重试

问题 = 损坏的解决方案 = 将您的手机带到维修店并获得 它从那里修复但是请记住,如果其他人打开您的 苹果以外的手机,则保修将无效(未激活)。

【问题讨论】:

  • 这是因为'my''phone''is' 不在d 中。所以对于这三个词,你的else 分支被使用了。您需要重新考虑如何测试单词匹配。

标签: python if-statement for-loop skip


【解决方案1】:

试试这个:

for word in userinput.split(): 
    result = ""
    if word in d:
        result += d[word] + "\n"

if (len(result) == 0):
    result += "Please Re-Phrase your problem and Try Again\n"
print (result)

【讨论】:

    猜你喜欢
    • 2016-08-26
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    相关资源
    最近更新 更多