Python 3.7:如何检查用户输入的格式是否为特定格式,例如“ XdY”,如果无效则再次要求输入?

时间:2018-07-13 18:00:33

标签: python-3.x exception-handling dice

我正在尝试写一个骰子辊。我试过尝试一下,除了,虽然,但是,但没有按我的预期工作-在询问用户是否要继续之前,我想检查用户输入是否有效,如果无效,请返回user_number1 。我是从错误的角度看吗?我该怎么办? 很抱歉这个愚蠢的问题,我对此很陌生。

import random
print("Welcome to the dice roller!")

def roller():
    user_number1 = input("Please input the dice you want to use in the following format: XdY > ")
    user_number_fin = user_number1.split("d")
    num1 = int(user_number_fin[0])
    num2 = int(user_number_fin[1])

    if num1 == 1:
        result1 = random.randint(num1, num1*num2)
        print("Your roll is: " + str(result1) + " (" + str(num1) + "d" + str(num2) + ")" )

    else:
        dice_number = 1
        list_of_results = []
        while dice_number <= num1:
            result2 = random.randint(num1, num2)
            list_of_results.append(result2)
            dice_number += 1
        print("Your roll is: " + str(sum(list_of_results)) + " (" + str(num1) + "d" + str(num2) + ", " + str(list_of_results)+ ")")


def shouldi():
    roller()
    usercont = input("Do you want to continue? y/n > ")
    while usercont in ["Y", "y"]:
        roller()
        usercont = input("Do you want to continue? y/n > ")

    if usercont in ["N", "n"]:
        print("Thank you for using the dice roller. Bye!")
        quit()
    else:
        print("That is not a valid input.")
        usercont

2 个答案:

答案 0 :(得分:0)

类似下面的事情是使用正则表达式的另一种方法。如果您对regex感到满意,那么我宁愿用它代替它。这只是一种替代方法。

def roller():
user_number1 = input("Please input the dice you want to use in the following format: XdY > ")
if("d" in user_number1):
    if(len(user_number1) == 3):
        user_number_fin = user_number1.split("d")
        num1 = int(user_number_fin[0])
        num2 = int(user_number_fin[1])
 else:
     print("Your input not in valid format. Use the format XdX")    

答案 1 :(得分:0)

您可以使用正则表达式并编写一个完全满足您需要的函数,然后可以在roller()函数中使用它:

import re

def get_number():
    user_number1 = input("Please input the dice you want to use in the following format: XdY > ")
    user_number_fin = re.match("^(\\d*)d(\\d+)$",user_number1,re.I)
    if not user_number_fin: get_number()
    if user_number_fin.group(1) =='': num1 = 1
    else: num1 = int(user_number_fin.group(1)) 
    num2 = int(user_number_fin.group(2)) 
    if num1>num2:
        print("\n\tSorry--side to roll must be less than the number of sides!!")
        get_number()
    return {'num1':num1,'num2':num2}

这可以接受d4,即如果未指定为1,则取默认面;不能接受4d3,即要掷骰的面必须小于骰子中存在的面数。