【问题标题】:Exit function in python [duplicate]python中的退出函数[重复]
【发布时间】:2020-11-19 04:32:23
【问题描述】:
import random
import sys

player_oneN = input("Enter Name for Player One")
player_twoN = input("Enter Name for Player Two")
player_oneS = 0
player_twoS = 0
if player_oneN == "stop" or "exit":
    c = int(input("Press 1 to continue and 0 to quit :"))
    if c == 0:
        sys.exit()
if player_twoN == "stop" or "exit":
    c = int(input("Press 1 to continue and 0 to quit :"))
    if c == 0:
        sys.exit()

每当我尝试运行此代码时,总是会显示退出程序的选项。我只希望当用户在玩家一和玩家二输入中进入退出或停止时此选项可用。

【问题讨论】:

标签: python-3.x


【解决方案1】:

如果您想在 if 语句中检查多个值,请使用 in 并检查项目列表。

import random
import sys

player_oneN = input("Enter Name for Player One")
player_twoN = input("Enter Name for Player Two")
player_oneS = 0
player_twoS = 0
if player_oneN.lower() in ["stop", "exit"]: # replace with in list items
    c = int(input("Press 1 to continue and 0 to quit :"))
    if c == 0:
        sys.exit()
if player_twoN.lower() in ["stop", "exit"]: # replace with in list items
    c = int(input("Press 1 to continue and 0 to quit :"))
    if c == 0:
        sys.exit()

由于您的两个 if 语句都在做同样的事情,您可以将它们组合成一个 if 语句。

if player_oneN.lower() in ["stop", "exit"] or player_twoN.lower() in ["stop", "exit"]:
    c = int(input("Press 1 to continue and 0 to quit :"))
    if c == 0:
        sys.exit()

你也可以这样做:

if any(i in ['stop','end'] for i in [player_oneN.lower(),player_twoN.lower()]):
    c = int(input("Press 1 to continue and 0 to quit :"))
    if c == 0:
        sys.exit()

【讨论】:

    【解决方案2】:

    问题是player_twoN == "stop" or "exit" 没有达到您的预期。它被解释为(player_twoN == "stop") or "exit"。由于非空字符串的计算结果为True,因此整个语句的计算结果为True

    【讨论】:

      【解决方案3】:

      您的or 条件不正确,只需检查exit 不是null,这始终是正确的。

      import random
      import sys
      
      player_oneN = input("Enter Name for Player One")
      player_twoN = input("Enter Name for Player Two")
      player_oneS = 0
      player_twoS = 0
      if player_oneN == "stop" or player_oneN == "exit": # <--- should be this
          c = int(input("Press 1 to continue and 0 to quit :"))
          if c == 0:
              sys.exit()
      if player_twoN == "stop" or player_twoN == "exit": # <--- should be this
          c = int(input("Press 1 to continue and 0 to quit :"))
          if c == 0:
              sys.exit()
      

      【讨论】:

        猜你喜欢
        • 2011-04-18
        • 2019-07-05
        • 2019-08-18
        • 2022-12-03
        • 2020-11-28
        • 1970-01-01
        • 2016-11-03
        • 1970-01-01
        • 2016-08-30
        相关资源
        最近更新 更多