我有一个 Python 代码需要帮助。我的目标是让代码循环嵌套函数并根据我添加的文本数量运行多次。对于我的代码,我希望它运行 main_func() 3 次。
期望的输出
#First loop
I am first apple
I am second apple
I am third banana
#second loop
I am first apple
I am second apple
I am third banana
#third loop
I am first apple
I am second apple
I am third banana
def main_func():
fruits = [] # List
fruits.append("apple")
fruits.append("cherry")
fruits.append("banana")
for fruit in fruits:
for i in range(3): # Iterate 3 times
print(fruit)
def first():
print("I am first", (fruit))
first()
def second():
print("I am second", (fruit))
second()
def third():
print("I am third", (fruit))
third()
main_func()
您可以创建一个迭代 3 次的方法并调用
first
、second
、third
。
您可以在下面找到修改后的代码片段。
def main_func():
fruits = [] # List
fruits.append("apple")
fruits.append("cherry")
fruits.append("banana")
def first():
print("I am first", (fruits[0]))
def second():
print("I am second", (fruits[1]))
def third():
print("I am third", (fruits[2]))
def printFruits():
for i in range(3):
first()
second()
third()
printFruits()
main_func()
输出:
I am first apple
I am second cherry
I am third banana
I am first apple
I am second cherry
I am third banana
I am first apple
I am second cherry
I am third banana