问题创建一个函数

时间:2015-12-07 03:14:13

标签: python function

我试图把这段代码放到一个函数中,但是当我运行它时它不打印,这是我写的下面的代码,'失踪了吗?谢谢你的帮助!

def pred():   

    with open('AquaticFoodWeb.txt') as input:
        for line in input:
            animal, prey = line.strip().split(' eats ')
            foodweb.setdefault(animal, []).append(prey)

        print ("Predators and Prey:")

        for animal, prey in sorted(foodweb.items()):
            if len(prey) > 1:
                print ("{} eats {} and {}".format(animal, ",     ".join(prey[:-1]), prey[-1]))
            else:
                print ("{} eats {}".format(animal, ", ".join(prey)))


    if __name__ == "__pred__":
        pred()

1 个答案:

答案 0 :(得分:1)

执行python文件时,会为其分配一个名称。通过“python file.py”执行的初始文件被赋予名称“main”,并存储在变量__name__下。在其他情况下,假设导入文件(“导入文件”),则为__name__分配不同的名称。

请参阅https://docs.python.org/3/library/main.html

def pred():   

    with open('AquaticFoodWeb.txt') as input:
        for line in input:
            animal, prey = line.strip().split(' eats ')
            foodweb.setdefault(animal, []).append(prey)

    print ("Predators and Prey:")

    for animal, prey in sorted(foodweb.items()):
        if len(prey) > 1:
            print ("{} eats {} and {}".format(animal, ",     ".join(prey[:-1]), prey[-1]))
        else:
            print ("{} eats {}".format(animal, ", ".join(prey)))


if __name__ == "__main__":
    pred()