无法使用 isdigit() 方法从 python 中的用户输入中排除数字“0”

unable to rule out number "0" from the user input in python using isdigit() method

我必须为 python 中的用户创建一个列表,其中必须包含 0-10 之间的数字。应排除为“0”和大于 9。我已经使用“.isdigit()”编写了一个代码,以便消除单词,但由于控制台也在执行“0”,所以我坚持使用“0”消除。作为 newbie.Can 我尽了最大的努力有人帮助我吗!?

def playerposition(): 
    p_keys= list(range(1,10))

    print('pick a position now: ')
    postn=input('choose a position between (1-9): ')
    
    while postn not in p_keys:
        while postn.isdigit()==False or postn==0:
            print('wrong input! enter again!: ')
            postn=input('choose a position between (1-9): ')
            
        print(int(postn))
        print(p_keys)
        break
playerposition()

执行输出(控制台):

选择(1-9)之间的位置:你好 输入错误!再次输入!:

选择(1-9)之间的位置:1 1个 [1, 2, 3, 4, 5, 6, 7, 8, 9]

朗塞尔 选择 (1-9) 之间的位置:0 0 [1, 2, 3, 4, 5, 6, 7, 8, 9] ---> 这是问题,其中 0 也通过作为输入而不是显示为('错误的输入再试一次!: )

预期输出样本: 选择 (1-9) 之间的位置:0 输入错误!再次进入!: 选择 (1-9) 之间的位置:

此行不正确:

 while postn.isdigit()==False or postn==0:

应该是

while postn.isdigit()==False or postn=="0":

在您当前的代码中,会发生以下情况:

  1. p_keys 是整数列表,而 postn 是字符串 return by input().
  2. 字符串不会出现在整数列表中,因此 while postn not in p_keys: 始终为真并将 postn 传递给下一个 while 循环。
  3. while postn.isdigit() == False or postn == 0: 成功停止非数字字符串,但无法停止值为 "0"postn,因为字符串 "0" 不等于整数 0
  4. 将条件从 postn == 0 变为 postn == "0" 确实排除了 "0" 作为输入,但您仍然在这里遗漏了一些东西。 "46""82""100"等所有数字字符串都可以通过检查,实际上"1"在你的测试中通过检查运行因为它是数字而不是它在 p_keys.
  5. 范围内

所以我改变条件:

def playerposition():
    p_keys = list(range(1,10))

    print('pick a position now: ')
    postn = input('choose a position between (1-9): ')
    # 1. not postn.isdigit() stop non-numeric string so we can confirm postn is a numeric string
    # 2. we can safely convert postn to integer and check if it is in p_keys,
    #    it will stop 0 and other numbers as they are not in p_keys 
    while not postn.isdigit() or int(postn) not in p_keys:
        print('wrong input! enter again!: ')
        postn = input('choose a position between (1-9): ')

    print(int(postn))
    print(p_keys)

playerposition()

另一种方法是将 p_keys 更改为字符串列表:

def playerposition():
    p_keys = [str(i) for i in range(1,10)]
    print('pick a position now: ')
    postn = input('choose a position between (1-9): ')
    # no need to check if postn is numeric or not, words not in p_keys can be ruled out already
    while postn not in p_keys:
        print('wrong input! enter again!: ')
        postn = input('choose a position between (1-9): ')

    print(int(postn))
    print(list(range(1,10)))

playerposition()

测试运行:

pick a position now:
choose a position between (1-9): hello
wrong input! enter again!:
choose a position between (1-9): 10
wrong input! enter again!:
choose a position between (1-9): 0
wrong input! enter again!:
choose a position between (1-9): 1
1
[1, 2, 3, 4, 5, 6, 7, 8, 9]