Search code examples
pythonoptimizationinputone-liner

Restricting the domain of integer values accepted as input in python


I'm building a command line game using python.A main feature of this game is to get the user's input of either 1 or 2 as integer values.Any other character must be rejected.I used try-except & if-else condition to do this like shown below.I want to know whether there is any better method to get this done in one line or some other way without having to indent a whole bunch of code.

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")

Solution

  • You can create a function to check user input and use below code.

    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