为什么导入的文件会产生一个重复的结果?

时间:2018-02-10 17:57:47

标签: python python-3.x

我已经制作了一个要导入的文件,比方说pizza.py。

def make_pizza(size, *toppings): 
    """Summarize the pizza we are about to make."""
    print("\nMaking a " + str(size) +
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

我在这个程序中调用了模块,假设make_pizza.py

import pizza

pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

我做的设置是否会产生一个重复的结果?

以下是一个重复的结果。

Making a 16-inch pizza with the following toppings:
- pepperoni

Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

Making a 16-inch pizza with the following toppings:
- pepperoni

Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

那么从这两个脚本中,是什么使得结果产生了一次重复的返回?

1 个答案:

答案 0 :(得分:3)

您需要在主要块中包含所有代码,以避免在导入过程中执行它,如下所示:

{{1}}