【请教贴】如何限制input的输入范围


import random
#(当输出非整数时,程序会崩溃,如何解决??)
#现需求编码一个限制玩家输出值的范围,如输入值不在范围内,则提示再次输入(只能是0,1,2)

hand = int(input("请出招!![0:石头    1:剪刀    2:布]"))  # 玩家出招
while hand != 0 and hand != 1 and hand != 2:
    print('别瞎搞,按套路输出(输入0~2的整数)')
    hand = int(input("请出招!![0:石头    1:剪刀    2:布]"))  # 玩家出招
ai = random.randint(0, 2)  # ai出招
while hand == ai:
    print('我刚刚出的也是:' + str(ai))#返回ai的招数
    print("平手!再来~")
    hand = int(input("请出招!![0:石头    1:剪刀    2:布]"))  # 玩家再出招
    while hand != 0 and hand != 1 and hand != 2:
        print('别瞎搞,按套路输出(输入0~2的整数)')
        hand = int(input("请出招!![0:石头    1:剪刀    2:布]"))  # 玩家再出招
    ai = random.randint(0, 2)  # ai再出招
if (hand < ai and hand != 2 or hand == 2 and ai == 0):#3种玩家获胜的情况 01 12 20
    print('我刚刚出的是:' + str(ai))  # 返回ai的招数
    print("好家伙!你居然赢了我")
else:#其余都是输
    print('我刚刚出的是:' + str(ai))  # 返回ai的招数
    print("你输了,愚蠢的人类!")
print("game over")

img

用try except来解决:

import random
# (当输出非整数时,程序会崩溃,如何解决??)
# 现需求编码一个限制玩家输出值的范围,如输入值不在范围内,则提示再次输入(只能是0,1,2)
try:
    hand = int(input("请出招!![0:石头    1:剪刀    2:布]"))  # 玩家出招
    while hand != 0 and hand != 1 and hand != 2:
        print('请输入0-2的整数')
        hand = int(input("请出招!![0:石头    1:剪刀    2:布]"))  # 玩家出招
    ai = random.randint(0, 2)  # ai出招
    while hand == ai:
        print('我刚刚出的也是:' + str(ai))  # 返回ai的招数
        print("平手!再来~")
        hand = int(input("请出招!![0:石头    1:剪刀    2:布]"))  # 玩家再出招
        while hand != 0 and hand != 1 and hand != 2:
            print('别瞎搞,按套路输出(输入0~2的整数)')
            hand = int(input("请出招!![0:石头    1:剪刀    2:布]"))  # 玩家再出招
        ai = random.randint(0, 2)  # ai再出招
    if (hand < ai and hand != 2 or hand == 2 and ai == 0):  # 3种玩家获胜的情况 01 12 20
        print('我刚刚出的是:' + str(ai))  # 返回ai的招数
        print("好家伙!你居然赢了我")
    else:  # 其余都是输
        print('我刚刚出的是:' + str(ai))  # 返回ai的招数
        print("你输了,愚蠢的人类!")
except:
    print('输入的不是数字')
print("game over")

img

用异常捕获来处理这种情况。