在python 3.3.2中仅允许整数输入

在python 3.3.2中仅允许整数输入,python,input,integer,dice,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:"))

嗨,我试图让程序只接受数字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()

将其放在一个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
试试看:
choice=int(原始输入(“输入选项1、2或3:”)

如果不是(1您可以在代码中查找以下内容:

  • 出于许多原因,包括知道错误的确切原因,建议使用try/catch测试输入
  • 您可以通过进一步考虑ifs和else的嵌套方式来减少它们
  • 让函数本身调用并使用while循环不是最好的方法,可以使用其中一种
  • 在您的例子中,实际上不需要只允许整数输入,您需要的是只允许0、4、6或12,这是您使用if语句所做的
这里是另一种方法,使用isalpha()。

我将把“受限输入”功能封装到一个单独的、可重用的函数中:

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
将以一个接受的整数结束,可能包括退出
0
值,这是因为您将输入转换为int,然后检查值。在调用int()之前检查值那么,我应该在检查值后将输入转换为int吗?使用try和expect来处理类型转换的异常。好的,我知道你在这里做了什么。我太傻了,没有在代码中包含try和except函数。非常感谢!你应该尽可能避免递归,因为堆栈每次都会增长这里有一个错误。在这种情况下,您可以简单地使用一个循环来代替。@serialk所说的。另一种改进代码(并解决堆栈问题)的方法除了输入0之外,还可以编写其他方法来逃避程序,例如计时器或计数器,用于计算接收输入的次数。仅供参考,我更新了我的答案。我已经有一段时间没有用Python编写代码了。我的原始答案使用了
raw\u input()
print
正如Python 3.0+所说,正确的语法是
input()
print()
。我更新了你的代码,使之更干净,使用foo
中整洁的
语法进行验证,并使用外部无限循环作为“主”程序。如前所述,使用递归最终会使你的程序崩溃。
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))