python - 在for循环中调用函数

标签 python python-3.x

我有 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")

.....

最佳答案

把你的函数放到一个列表中:

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)]()

您也可以完全改变方法并使用 itertools.cycle()而不是遍历列表的索引,并使用内置的 next()获取功能:

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)()

关于python - 在for循环中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47741844/

相关文章:

python - 将列表作为查询参数传递

python - 如何限制调用函数失败的次数?

python - 从 OrderedDict : preserving columns order 列表构建 Pandas DataFrame

python - from .. import 和 from .. 之间的区别进口

python-3.x - 如何(重新)设置整个 python 3 脚本的默认文件 open() 编码?

Python:SystemError 父模块未加载,无法执行相对导入

python-3.x - 使用生成的变量,其值在一个函数中分配给另一个函数

python - 将浮点列转换为字符串并测试字符串在 Pandas 中的存在

python - ZeroMQ 推送套接字导致客户端在没有进程监听时不终止

python - 无法使用 Jupyter Notebook 运行 python 代码