检查输入是python中的一个数字

时间:2013-05-03 10:34:37

标签: python

我需要帮助,我的程序正在模拟骰子的动作。我想进行错误检查以检查输入字符串是否为数字,如果不是,我想再次问问题,直到他输入一个整数

# This progam will simulate a dice with 4, 6 or 12 sides.

import random 

def RollTheDice():

    print("Roll The Dice")
    print()


    NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: "))

    Repeat = True 

    while Repeat == True:


        if not NumberOfSides.isdigit() or NumberOfSides not in ValidNumbers:
            print("You have entered an incorrect value")
            NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides")

        print()
        UserScore = random.randint(1,NumberOfSides)
        print("{0} sided dice thrown, score {1}".format (NumberOfSides,UserScore))

        RollAgain = input("Do you want to roll the dice again? ")


        if RollAgain == "No" or RollAgain == "no":
            print("Have a nice day")
            Repeat = False

        else:
            NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: "))

4 个答案:

答案 0 :(得分:2)

作为评论者,我不喜欢try: except ValueError的第一个答案,并且OP询问了如何使用isdigit,这就是你如何做到的:

valid_numbers = [4, 6, 12]
while repeat:
    number_of_sides = 0      
    while number_of_sides not in valid_numbers:
          number_of_sides_string = input("Please select a dice with 4, 6 or 12 sides: ")
          if (not number_of_sides_string.strip().isdigit() 
              or int(number_of_sides_string) not in valid_numbers):
              print ("please enter one of", valid_numbers)
          else:
              number_of_sides = int(number_of_sides_string)
    # do things with number_of_sides

有趣的一行是not number_of_sides_string.strip().isdigit()。为方便起见,strip删除了输入字符串两端的空格。然后,isdigit()检查完整字符串是否由数字组成。

在您的情况下,您只需检查

即可
 if not number_of_sides_string not in ['4', '6', '12']:
     print('wrong')

但如果您想接受任何数字,则另一种解决方案更为通用。

另外,Python coding style guidelines建议使用小写下划线分隔的变量名称。

答案 1 :(得分:1)

捕获变量中的字符串,例如text。然后执行if text.isdigit()

答案 2 :(得分:0)

创建一个函数:

while NumberOfSides != 4 and NumberOfSides != 6 and NumberOfSides != 12:
    print("You have selected the wrong sided dice")
    NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: "))

当你想要输入时调用它。您还应该选择退出,例如按0.还应该尝试捕获无效数字。有一个确切的example in Python doc。请注意,输入总是尝试解析为数字,并且会增加它自己的异常。

答案 3 :(得分:0)

您可以使用type method

my_number = 4
if type(my_number) == int:
    # do something, my_number is int
else:
    # my_number isn't a int. may be str or dict or something else, but not int

或更多«pythonic»isinstance method

my_number = 'Four'
if isinstance(my_number, int):
    # do something
raise Exception("Please, enter valid number: %d" % my_number)