限制在 python 中作为输入接受的整数值的域

Restricting the domain of integer values accepted as input in python

我正在使用 python.A 构建一个命令行游戏这个游戏的主要特点是让用户输入 1 或 2 作为整数 values.Any 其他字符必须是 rejected.I 使用 try-exceptif-else condition 来做到这一点 below.I 想知道是否有更好的方法可以在一行或其他方式中完成此操作而不必缩进一大堆代码。

if __name__ == '__main__':
# INITIALIZE THE TOTAL STICKS , DEPTH OF THE TREE AND THE STARTINGG PLAYER
i_stickTotal = 11 # TOTAL NO OF STICKS IN THIS GAME
i_depth = 5 # THE DEPTH OF THE GOAL TREEE THE COMPUTER WILL BUILD
i_curPlayer = 1 # THIS WILL BE +1 FOR THE HUMAN AND -1 FOR THE COMPUTER
print("""There are 11 sticks in total.\nYou can choose 1 or 2 sticks in each turn.\n\tGood Luck!!""")
# GAME LOOP
while i_stickTotal > 0:
    print("\n{} sticks remain. How many would you pick?".format(i_stickTotal))
    try:
        i_choice = int(input("\n1 or 2: "))
        if  i_choice - 1 == 0 or i_choice - 2 == 0:            
            i_stickTotal -= int(i_choice)
            if WinCheck(i_stickTotal, i_curPlayer):
                i_curPlayer *= -1
                node = Node(i_depth, i_curPlayer, i_stickTotal)
                bestChoice = -100
                i_bestValue = -i_curPlayer * maxsize

                #   Determine No of Sticks to Remove

                for i in range(len(node.children)):
                    n_child = node.children[i]
                    #print("heres what it look like ", n_child.i_depth, "and",i_depth)
                    i_val = MinMax(n_child, i_depth-1, i_curPlayer)
                    if abs(i_curPlayer * maxsize - i_val) <= abs(i_curPlayer*maxsize-i_bestValue):
                        i_bestValue = i_val
                        bestChoice = i
                        #print("Best value was changed @ ", i_depth, " by " , -i_curPlayer, " branch ", i, " to ", i_bestValue)



                bestChoice += 1
                print("Computer chooses: " + str(bestChoice) + "\tbased on value: " + str(i_bestValue))
                i_stickTotal -= bestChoice
                WinCheck(i_stickTotal, i_curPlayer)
                i_curPlayer *= -1
            else:
                print("You can take only a maximum of two sticks.")

    except:
        print("Invalid input.Only Numeric Values are accepted")

编写一个循环函数,调用 input,直到值满足您的约束。也许称它为 get_user_input。然后在您的主函数中调用它而不是 input。对于附加值,将 lambda 作为谓词传递到该函数中以测试用户输入值 - 这将使 get_user_input 更通用。

您可以创建一个函数来检查用户输入并使用以下代码。

while True:
    var = int(input('Enter value (1 or 2) - '))
    if var not in range(1, 3):
        print('Invalid entry, please try again...')
        continue
    else:
        break