脚本打印乱序

时间:2013-01-26 18:42:32

标签: python printing python-2.7

我正在使用Python 2.7.3并试图理解为什么这个脚本不按顺序执行print语句。即“ - ”在第二次循环后打印。

我的剧本:

def cheeseshop(kind, *arguments, **keywords):
    print "-- Do you have any", kind, "?"
    print "-- I'm sorry, we're all out of", kind
    for arg in arguments:
        print arg
    print "-" * 40
    keys = sorted(keywords.keys())
    for kw in keys:
        print kw, ":", keywords[kw]

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           {'shopkeeper':'Michael Palin',
           'client':"John Cleese",
           'sketch':"Cheese Shop Sketch"})

输出:

-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
{'shopkeeper': 'Michael Palin', 'sketch': 'Cheese Shop Sketch', 'client': 'John Cleese'}
----------------------------------------

为什么要打印“ - ”* 40在字典之前按预期执行?

1 个答案:

答案 0 :(得分:8)

您没有将字典作为关键字传入。使用**语法执行此操作:

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           **{'shopkeeper':'Michael Palin',
           'client':"John Cleese",
           'sketch':"Cheese Shop Sketch"})

或根本不使用字典:

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper='Michael Palin',
           client="John Cleese",
           sketch="Cheese Shop Sketch")