我有 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/