【问题标题】:how to kill a program in python如何在python中杀死一个程序
【发布时间】:2014-12-14 16:02:15
【问题描述】:

当用户说“不”开始数学测验时,我正试图在 python 3 中杀死一个程序:这是我正在使用的代码

import sys

while True:
    new_item = input("> ")
    if new_item == "Yes" or "yes":
        break
    elif new_item == "no":
        sys.exit()

任何指针都不起作用?

【问题讨论】:

  • 你的问题究竟是什么?
  • 你想在这里做什么???

标签: python python-3.x


【解决方案1】:

你的问题在这里:

if new_item == "Yes" or "yes":

你需要使用:

if new_item in ["Yes", "yes"]:

或:

if new_item == "Yes" or new_item == "yes"

你的原始代码被解析为:

if (new_item == "Yes") or "yes":

这总是计算为True,因为"yes" 是一个真值。

【讨论】:

    【解决方案2】:
    if new_item == "Yes" or "yes":
    

    这个条件总是True。可以这样表述:

    (new_item == "Yes") or ("yes")
    

    非空字符串 'yes' 始终被评估为 True

    条件改为:

    if new_item in ['Yes', 'yes']:
    

    【讨论】:

      【解决方案3】:

      您需要更改您的 if 语句,它没有正确评估。您需要使用此代码来解决您的问题:

      import sys
      
      while True:
          new_item = input("> ")
          if new_item == "Yes" or new_item == "yes":
              break
          elif new_item == "no":
              sys.exit()
      

      【讨论】:

        【解决方案4】:

        怎么样

        import sys
        
        while True:
            new_item = input("> ")
            new_item = new_item.lower() 
            #everything you wrote in input will be lowercase, no more "or" problems
            if new_item.lower() == "yes":
                break
            elif new_item.lower() == "no":
                sys.exit()
        

        【讨论】:

          猜你喜欢
          • 2017-03-11
          • 2020-02-20
          • 2012-07-11
          • 1970-01-01
          • 1970-01-01
          • 2022-11-29
          • 1970-01-01
          • 2010-11-07
          • 2017-08-05
          相关资源
          最近更新 更多