简体   繁体   English

如何运行多个函数直到一个函数返回 False?

[英]How to run through a number of functions until one returns False?

I'd like the score function to run the while loop until 1 of the "checks" returns False, and exit the loop if none return False.我希望score function 运行 while 循环,直到“检查”中的 1 个返回 False,如果没有返回 False,则退出循环。 The "check" also returns a string that defines the message we'll display to user “检查”还返回一个字符串,该字符串定义了我们将显示给用户的消息



def check_args(args, number_of_expected_args):
    if len(args) < number_of_expected_args:
        return False, 'cmd_missing_param'
    elif len(args) > number_of_expected_args:
        return False, 'cmd_extra_param'

def check_numbers(args, value):
    if args[value].isdigit() == False:
        return False, 'scores_invalid', 'var3'

def check_score(args, etc):
    if not blahblah....
        return False, 'response3'

def score(ctx, *args):

    test = []
    test[0], test[1] = True, 'Success'
    while test[0] == True:
        test = check_args(args, 4)
        test = check_numbers(args, 2)
        test = check_score(args, 3)
    
    print(test[1])

score(0, 1, 2, 3, 4)

Here is a snip of my working code.这是我的工作代码的片段。 This is using discord.py to create a channel command bot, and the checks are to validate the arguments attached to the command.这是使用 discord.py 创建通道命令机器人,检查是为了验证附加到命令的 arguments。

There are 2 commands defined here, score and schedule , and both call the check_test function, although future commands may only need to run lesser amounts of the checks.这里定义了 2 个命令, scoreschedule ,它们都调用check_test function,尽管未来的命令可能只需要运行较少数量的检查。 So I'm trying to move each individual check outside of my larger check_test function as I'll have many more checks to define and want to be able to call only specific ones所以我试图将每个单独的支票移到我较大的check_test function 之外,因为我将有更多的支票来定义并希望只能调用特定的支票

strings = {
    "english": {
        "cmd_missing_param": "Your submission is missing a parameter.",
        "cmd_extra_param": "Your submission has too many parameters.",
        "players_not_found": "Your submission user(s) {var1} cannot be found.",
        "scores_invalid": "Your submitted scores are not valid numbers.",
        "score_submitted": "Score successfully submitted",
        "schedule_submitted": "Schedule successfully submitted"
    }
}
    
async def reply(ctx, dict_string, arg1 = None, arg2 = None):
    # this function is to return a response to the user containing the success/fail message

    author = ctx.author.mention
    dict = strings['english']
    greeting = dict['greeting']
    response = dict[f'{dict_string}']

    return await ctx.reply(f"{greeting} {author}! {response}".format(var1 = arg1, var2 = arg2))

async def check_test(ctx, args, number_of_expected_args, args_players_index, args_scores_index, datetime_index, check_attachment):
    # this function is to perform a number of validations on our command args

    # check if command has expected number of args
    if args != '':
        if len(args) < number_of_expected_args:
            return False, 'cmd_missing_param'
        elif len(args) > number_of_expected_args:
            return False, 'cmd_extra_param'

    # check if the scores are valid numbers
    if args_scores_index != None:
        for each in args_scores_index:
            if args[each].isdigit() == False:
                return False, 'scores_invalid'
        
@client.command()
async def score(ctx, *args):
    # this command is to submit the score record for 2 players

    is_valid, response = await check_test(ctx, args, 4, [0, 1], [2, 3], None, '.w3g')
    if is_valid:
        player1, player2 = args[0], args[1]
        bot_message = await reply(ctx, 'score_submitted', player1, player2)
    else:
        await reply(ctx, response)
    
@client.command()
async def schedule(ctx, *args):
    is_valid, response = await check_test(ctx, args, 4, [0, 1], None, True, None)
    if is_valid: 
        player1, player2 = args[0], args[1]
        bot_message = await reply(ctx, 'schedule_submitted', player1, player2)
    else:
        await reply(ctx, response)

Here's an example of how you might write a validation function for args :以下是您如何为args编写验证 function 的示例:

expected_number_of_args = 5


def validate_score_args(args):
    # example: test that exactly 'expected_number_of_args' were passed
    n = len(args)
    if n != expected_number_of_args:
        raise ValueError(f"Expected {expected_number_of_args} args, but got {n}.")

    # example: make sure all args are numeric
    if not all(type(arg) in {int, float} for arg in args):
        raise TypeError(f"Expected all arguments to be numeric.")

    # example: if the above test passed, then check values
    if not all(arg > 0 for arg in args):
        raise ValueError(f"Expected all arguments to be positive.")

    # and so on


def score(ctx, *args):
    try:
        validate_score_args(args)
    except (ValueError, TypeError) as err:
        # Do something about error instead of 're-raising' it, but for now:
        raise err
    
    # If args were valid, then use them:
    return sum(args)

Add any number of "tests" to validate_score_args() .添加任意数量的“测试”到validate_score_args() They'll run in order from top to bottom, and if any test fails, none of the following tests will run.它们将按从上到下的顺序运行,如果任何测试失败,则不会运行以下任何测试。

However, I'd recommend always running all your tests, and then "collecting" all the errors and doing something with them (like displaying them to the user) so that the user can see everything they did wrong at once instead of having to play whack-a-mole, fixing one bug at a time.但是,我建议始终运行所有测试,然后“收集”所有错误并对其进行处理(例如将它们显示给用户),以便用户可以立即看到他们做错的所有事情,而不必玩打地鼠,一次修复一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何计算 TRUE 的数量,直到 numpy 数组中的 FALSE? - How to count the number of TRUE until a FALSE in numpy array? 如果有一个错误,如何不运行 If 语句的其余部分? - How to not run the rest of an If statement if one is false? 如何遍历固定数量的文件,直到文件夹的最后一个文件? - How to iterate through a fixed number of files until the last file of the folder? 如何通过解析python中的列表来运行多个函数? - How to run a number of functions by parsing a list in python? 如果内部调用的所有函数都为真,我如何编写一个返回真的函数,否则返回假/错误? - how do i write a function that returns true if all the functions called inside it are true, returns false/errror otherwise? 创建具有未指定返回次数的函数 - Creating functions with unspecified number of returns 执行一个函数以在循环上返回值,直到该函数返回False-Python - Execute a function to return a value on a loop until that function returns False - Python 检查数字是否步进的函数返回false - Function to check if number is stepping returns false 质数函数返回true而不是false - Prime number function returns true instead of false 如何在 Elasticsearch 中并行运行多个 Azure 函数? - How to run multiple Azure Functions in parallel which scroll through Elasticsearch?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM