是否可以在python中调用函数之前运行函数的某些部分?

时间:2017-03-08 19:32:10

标签: python

所以现在我的代码看起来像这样(还没有添加其他两个选项):

def what_do(action):
  print "You can eat, move, hunt, or rest."
  for number in resources:
    print number + str(resources[number])
  if action == "eat":
    print "You ate. Hunger restored."
    resources['hunger'] == 0
  if action == "hunt":
    print "You went out and hunted. You found 10 food."
    resources['food'] += 10 
    print resources['food']

what_do(raw_input("What will you do?"))

除了此代码的其他问题之外,是否可以在调用函数之前直接打印我已经放置的字符串?

1 个答案:

答案 0 :(得分:1)

函数表示一起运行的语句块。虽然Python和其他语言确实定义了"协同例程"可以暂停和恢复运行,它们的使用比你所寻求的更先进。

现在你的模式可以通过将你的问题分成几个函数来解决 - 一个函数可以协调一下 - 一旦你掌握了这个安排并且可以随意增长函数组,你将能够继续需要时出现更复杂的形式。 (例如,你也可以使用一个类,或者甚至编排一些协同例程。)

def prompt():
    print "You can eat, move, hunt, or rest."

def get_action():
    return raw_input("What will you do?")

def what_do(action):
    for number in resources:
        print number + str(resources[number])
    if action == "eat":
        print "You ate. Hunger restored."
        resources['hunger'] == 0
    if action == "hunt":
        print "You went out and hunted. You found 10 food."
        resources['food'] += 10 
        print resources['food']

def game():
    while True:
        prompt()
        action = get_action()
        what_do(action)

game()