Python 3.x - 快速修复函数?

时间:2016-09-27 13:44:08

标签: python project quickfix

上下文 尝试构建一些非常小的东西,以便开发我非常有限的Python知识。

代码是什么?想象一下,你是在游戏中,然后和NPC角色交谈购买东西。这是互动,使用字典作为'库存'

问题:我希望代码能够通过交互运行,如果没有购买,请再次调用该函数。简单。

UserMoney = 500

NPC = {
    "Cotton": 20,
    "Wool": 20,
    "Silk": 20,
}

Price_List = {
    "Cotton": 5,
    "Wool": 10,
    "Silk": 20,
}

User = {
    "Wool": 0,
    "Crystal": 0,
    "Gemstone": 0,
}
def hi_npc():
    print 'Hi, my name is NPC'
    print 'I see you have ' + str(UserMoney) + ' coins'
    print 'What would like to buy?'
    print NPC
    product = raw_input()

    if product in NPC:
        print 'How many would you like?'
        quantity = input()
        NPC[product] = NPC[product]-quantity
        User[product] = User[product]+quantity
        UserMoney = UserMoney - (Price_List[product]*quantity)
        print
        print 'NPC:' + str(NPC)
        print 'User:' + str(User)
        print
        print 'You have %s coins left to spend' % UserMoney
    else:
        print "Sorry I don't have that item"
        hi_npc()

1 个答案:

答案 0 :(得分:1)

不确定。您可以使用def关键字在python中定义一个函数,并在括号中使用参数。我们的第一个功能没有任何优势。

def hi_npc():
    print('Hi, my name is NPC')

如果你想稍微调整一下,我们可以将我们的功能命名为:

def hi_npc(name):
    print('Hi, my name is {}'.format(name))
相关问题