0

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

# 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

4 回答 4

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 编码风格指南建议使用小写下划线分隔的变量名称。

于 2013-05-03T10:40:06.717 回答
1

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

于 2013-05-03T10:41:39.267 回答
0

您可以使用类型方法

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 方法

my_number = 'Four'
if isinstance(my_number, int):
    # do something
raise Exception("Please, enter valid number: %d" % my_number)
于 2013-05-03T12:18:45.350 回答
0

Make a function out of:

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

And call it when you want to get input. You should also give an option to quit e.g. by pressing 0. Also you should try catch for invalid number. There is an exact example in Python doc. Note that input always try to parse as a number and will rise an exception of it's own.

于 2013-05-03T10:47:14.863 回答