在for循环中调用函数

2024-05-08 04:48:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有10个函数必须在一个循环中调用。。。

但如果用户输入5,则应调用前5个函数。

如果用户给出11,在调用10个函数之后,它应该从头开始调用其余的1

我写了所有10个函数,但我不知道如何实现这一点。

def function_one():
    print("This is the first function")


def function_second():
    print("This is the second function")

.....

Tags: the函数用户isdeffunctionthisone
2条回答

将函数放入列表中,然后使用模运算符循环遍历列表,其中N是您应该调用的函数数:

functions = [function_one, function_two, function_three, ..., function_ten]
num_of_funcs = len(functions)

for i in range(N):
    functions[i % num_of_funcs]()

i % num_of_funcs将确保从第一个函数开始,并在命中列表中的最后一个函数后再次返回到第一个函数。

将您的功能放入列表中:

functions = [function_one, function_two, function_three, ...]

在它们上面循环:

n = int(input('Number: '))
for i in range(n):
    functions[i]()

现在你的要求是:

If user gives 11 , after calling the 10 functions , it should start calling the rest 1 from the Beginning

有很多方法可以做到这一点,但是如果我们想坚持上面的代码,我们可以使用模运算符(%)来允许“越过”结尾:

n = int(input('Number: '))
for i in range(n):
    functions[i % len(functions)]()

您还可以完全更改方法,使用^{}而不是循环遍历列表的索引,并使用内置的^{}来获取函数:

import itertools

functions = [function_one, function_two, function_three, ...]
functions_it = itertools.cycle(functions)

n = int(input('Number: '))
for i in range(n):
    next(functions_it)()

相关问题 更多 >