只允许在python 3.3.2中输入Integer

时间:2014-12-30 17:36:05

标签: python input integer dice

您好我正在尝试让程序只接受数字0,4,6和12,并且不允许输入任何其他内容。到目前为止,我已经成功地只允许输入某些整数,但是我不能允许输入任何字母。输入一个字母后,整个程序崩溃。请问你能帮助我只输入整数吗?谢谢。

我的代码如下:

from random import randint 
def simul():
    dice = int(input("What sided dice would you like to roll? 4, 6 or 12? 0 to not roll:"))
    if dice != 4 and dice!=6 and dice!=12 and dice!=0:
        print('You must either enter 4, 6, or 12')
        simul()
    elif dice==0:
        exit()
    else:
        while dice !=0 and dice==4 or dice==6 or dice ==12 :
            print (randint(1,dice))
            dice = int(input("What sided dice would you like to roll? 4, 6 or 12? press 0 to stop."))
simul()

4 个答案:

答案 0 :(得分:1)

将它放在try catch块中,如下所示:

try:
    choice = int(raw_input("Enter choice 1, 2 or 3:"))
    if not (1 <= choice <= 3):
        raise ValueError()
except ValueError:
    print "Invalid Option, you needed to type a 1, 2 or 3...."
else:
    print "Your choice is", choice

复制自:limit input to integer only (text crashes PYTHON program)

我还不知道如何标记重复项。请不要因为这个原因而投票。

希望我的回答有所帮助。

答案 1 :(得分:1)

您可以在代码中查找以下几项内容:

  • 使用try / catch是测试输入的推荐方法,原因很多,包括了解错误的确切原因
  • 你可以通过更多地考虑如何嵌套来减少你的一些ifs和elses
  • 使用函数调用本身并使用while循环不是最好的方法,使用一个或另一个
  • 在你的情况下,你真的不需要只允许整数输入,你正在寻找的只是允许0,4,6或12,你使用if语句
from random import randint
def simul():
    while True:
        try:
            dice = int(input("What sided dice would you like to" \
                    " roll? 4, 6 or 12? 0 to not roll: "))
            if dice not in (4, 6, 12, 0):
                raise ValueError()
            break  # valid value, exit the fail loop
         except ValueError:
            print("You must enter either 4, 6, 12, or 0")

    if dice == 0:
        return 0

    print(randint(1, dice))
    return dice

if __name__ == '__main__':
    while simul() != 0:
        pass

答案 2 :(得分:1)

我会将“约束输入”功能封装到一个单独的可重用函数中:

def constrained_int_input(prompt, accepted, toexit=0):
    msg = '%s? Choose %s (or %s to exit)' % (
       prompt, ', '.join(str(x) for x in sorted(accepted)), toexit)
   while True:
       raw = raw_input(msg)
       try:
           entered = int(raw)
       except ValueError:
           print('Enter a number, not %r' % raw)
           continued
       if entered == toexit or entered in accepted:
           return entered
       print('Invalid number: %r -- please enter a valid one' % entered)

现在你可以打电话给例如

dice = constrained_int_input('What sided dice would you like to roll', (4,6,12))

如果需要,请确保dice最终会使用其中一个可接受的整数,包括to-exit 0的{​​{1}}值。

答案 3 :(得分:0)

while True:
    x=input("4,6 or 12? 0 to not roll: ")
    if x.isalpha():
        print ("only numbers.")
        continue
    elif int(x)==0:
        print ("quiting..")
        break
    elif int(x)!=4 and int(x)!=6 and int(x)!=12:
        print ("Not allowed.")
    else:
        print (random.randint(1,int(x)))

这是另一种方法,使用 isalpha()