上下文 尝试构建一些非常小的东西来开发我非常有限的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()
当然。在python中用
def
关键字定义一个函数,参数在括号中。我们的第一个功能没有任何功能。你知道吗如果你想让事情变得有趣一点,我们可以给我们的函数起个名字:
相关问题 更多 >
编程相关推荐