python 如何区分负数与非数字输入

vlju58qv  于 2022-11-21  发布在  Python
关注(0)|答案(5)|浏览(428)

我正在尝试构建一个简单的游戏,我希望Python在玩家输入负数时返回一条消息。我的问题是,当玩家试图输入负数时,负数被解释为字符串。
下面是我的脚本:

while True:
    user_guess = input("Guess a number: ")
    if user_guess.isdigit():
        user_guess = int(user_guess)
        if user_guess < 0:
            print("Too low, guess a number between 0 and 10.")
        if user_guess > 10:
            print("Too high, guess a number between 0 and 10.")
    else:
        print("It is not a number.")
        break
yfjy0ee7

yfjy0ee71#

你写的代码并没有 * 错误 *,但是它在Python中不是很符合习惯,因此你不得不与语言斗争来添加“parse negative”功能。考虑一下你可以写这样的代码:

user_guess = input("Guess a number: ")
if is_positive_or_negative_number(user_guess):
    user_guess = int(user_guess)
# continue as before

def is_positive_or_negative_number(s: str) -> bool:
    """Checks if a given string represents a positive or negative number"""
    if s.startswith('-'):
        s = s[1:]  # strip off the optional leading unary negation
    return s.isdigit()  # do not allow decimals, so no need to worry
                        # about allowing a "."

然而,如果你只写惯用的Python,这会更容易!你的代码是用一种被亲切地称为LBYL(三思而后行)的风格编写的,代码检查是为了确保一件事在做之前可以完成。Python更喜欢EAFP(比请求许可更容易请求原谅),它让你尝试做一件事,并在抛出错误时捕捉错误。
然后,惯用代码只尝试将输入转换为int,如果失败,则会引起注意。

while True:
    user_guess = input("Guess a number: ")
    try:
        user_guess = int(user_guess)
    except ValueError:
        print("It is not a number.")
        break
    # if we get here, user_guess is guaranteed to be an int
    # and int(user_guess) knows how to parse positive and
    # negative numbers
    if user_guess < 0:
        print("Too low, guess a number between 0 and 10.")
    elif user_guess > 10:
        print("Too high, guess a number between 0 and 10.")
llmtgqce

llmtgqce2#

对于负数,它返回“It is not a number”的原因是因为user_guess.isdigit()将负数视为字符串(或非数字)。
下面是一段代码,可以按您的预期工作:

while True:
    user_guess = input("Guess a number: ")
    try:
        user_guess = int(user_guess)
        if user_guess < 0:
            print("Too low, guess a number between 0 and 10.")
        if user_guess > 10:
            print("Too high, guess a number between 0 and 10.")
    except ValueError:
        print("It is not a number.")
        break

由于int()函数可以识别负数,因此使用try-except可以帮助您捕获ValueError异常,该异常在您尝试对非整数使用int()函数时引发。

xpcnnkqh

xpcnnkqh3#

isdigit()有问题。如果是减号,isdigit()将返回False。一个解决方法是让int()验证user_guess。

while True:
  try:
    user_guess = int( input( "Guess a number: "))
  except ValueError:
    print( "It is not a number.")
    break # exit loop
  # validate user entry
  if user_guess < 0:
    print("Too low...")
    continue
  elif user_guess > 10:
    print("Too high...")
    continue
  # do processing
  ...
kcugc4gi

kcugc4gi4#

def input_number(message):
    while True:
        user_guess = input(message)
        try:
            n = int(user_guess)
            if n < 0:
                print("Too low, guess a number between 0 and 10.")
            elif n > 10:
                print("Too high, guess a number between 0 and 10.")
            else:
                return n
        except ValueError:
            print("It is not a number. Try again")
            continue

if __name__ == '__main__':
    number = input_number("Guess a number.")
    print("Your number", number)
shstlldc

shstlldc5#

编辑:我将解释我的代码以及为什么它能解决你的问题。你使用的isdigit方法只会检查字符串中的字符是否由数字组成。减号不是数字,所以它返回False。
相反,我尝试将字符串转换为数字,如果python失败,我就再次循环(继续)并要求输入一个新的数字。如果输入确实是一个数字,代码的下半部分会检查有效的区间。只有当数字在区间内时,控制循环的变量才会被设置,循环退出。
我的代码不依赖于isdigit,因此避免了您的问题。希望这有帮助,并提供洞察力。

user_guess = None
while user_guess is None:
    inp = input("Guess a number: ")

    try:
        nr_inp = int(inp)
    except ValueError:
        print("It is not a number.")
        continue

    if nr_inp < 0:
        print("Too low, guess a number between 0 and 10.")
    elif nr_inp > 10:
        print("Too high, guess a number between 0 and 10.")
    else:
        user_guess = nr_inp

print("Done:", user_guess)

相关问题