有没有办法将2个非常相似的代码转换为一个函数并重复执行?

时间:2019-04-08 23:32:47

标签: python python-3.x function

我想编写两段非常相似的代码,以防止重复多次

这是我的新课,所以我想知道是否所有人都知道。我试图在参数中放入一些值,但是没有用。

pizzaType1 = {
    "Hawaiian":"$8.50", "Pepperoni":"$8.50", "Simply Cheese":"$8.50", "Ham & Cheese":"$8.50", "Beef & Onion":"$8.50", "Cheesy Garlic":"$8.50", "BBQ Pork & Onion":"$8.50"
    }
pizzaType2 = {
    "Mr. Wedge":"$13.50", "Apricot Chicken":"$13.50", "Cranberry & Chicken":"$13.50", "BBQ Meatlovers":"$13.50", "Godfather":"$13.50"
    }

for x,y in pizzaType1.items():
    print(x,y)
for x,y in pizzaType2.items():
    print(x,y)

这是我要放入函数中的代码

1 个答案:

答案 0 :(得分:2)

我认为这是您要追求的目标,但是我不确定:

pizzaType1 = {
    "Hawaiian":"$8.50", "Pepperoni":"$8.50", "Simply Cheese":"$8.50", "Ham & Cheese":"$8.50", "Beef & Onion":"$8.50", "Cheesy Garlic":"$8.50", "BBQ Pork & Onion":"$8.50"
    }
pizzaType2 = {
    "Mr. Wedge":"$13.50", "Apricot Chicken":"$13.50", "Cranberry & Chicken":"$13.50", "BBQ Meatlovers":"$13.50", "Godfather":"$13.50"
    }

def print_items(dictionary): # make our function
    for x, y in dictionary.items():
        print(x,y)

print_items(pizzaType1) # use our function
print_items(pizzaType2)

输出:

Hawaiian $8.50
Beef & Onion $8.50
Pepperoni $8.50
Simply Cheese $8.50
Cheesy Garlic $8.50
BBQ Pork & Onion $8.50
Ham & Cheese $8.50
Mr. Wedge $13.50
Apricot Chicken $13.50
Godfather $13.50
BBQ Meatlovers $13.50
Cranberry & Chicken $13.50