【问题标题】:Is there any easier way to write this comparison operator statement?有没有更简单的方法来编写这个比较运算符语句?
【发布时间】:2020-09-28 03:59:32
【问题描述】:

我对 Python 还很陌生。我有以下 if 语句:

if(userGuess == "0" or userGuess == "1" or userGuess == "2" or userGuess == "3" or userGuess == "4" or userGuess == "5" or userGuess == "6" or userGuess == "7" or userGuess == "8" or userGuess == "9"):
    print("\n>>>error: cannot use integers\n")
    continue

基本上,如果用户输入任何数字,循环将重置。有什么办法可以写出这个语句来让它更有效率吗? (即更少的代码和更清洁)

【问题讨论】:

  • 试试if userGuess.isnumeric(): - 见str.isnumeric()
  • 数字 > 9 怎么样?
  • userGuess 是否仅限于单个字符?
  • 作为示例说明,continue 不能在循环之外使用。最好发布一个运行示例。在您的情况下,将值分配给 userGuess 并省略 continue
  • 感谢所有帮助。我不知道你可以 int() 用一个数字的 str

标签: python if-statement


【解决方案1】:
possibilities = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]

if userGuess in possibilities:
    #do something

或者,如果您同意与整数进行比较,则可以执行以下操作:

if userGuess < 10:
    #do something

【讨论】:

  • 你能解释一下如果 userGuess in possible: 的循环是如何工作的吗?
  • 当然,没问题。 if 语句后跟一个条件检查(如果评估为真,则执行下一个缩进的代码块)。这个答案(stackoverflow.com/a/38204487)已经很好地解释了关键字 in 的使用。它只是检查 userGuess 的值是否在可能性项目列表中。
【解决方案2】:

你可以这样做:

nums = [str(i) for i in range(10)] # gets a list of nums from 0 to 9    

if userGuess in nums:
    print("Num found")

【讨论】:

    【解决方案3】:

    假设userGuess 是一个字符串并且可以不是单个字符,

    if(any(c.isdigit() for c in userGuess):
        ....
    

    如果猜测应该是一个字符,你可以

    if(len(userGuess) != 1 or userGuess in "0123456789"):
        ....
    

    if(len(userGuess) != or userGuess.isdigit()):
        ...
    

    想想看,isdigit 是更好的选择。假设用户输入孟加拉语号码৩.isdigit()True

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多