2017-03-08 97 views
-3

所以现在我的代码看起来像这样(没有添加其他两个选项尚未):在使用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

您是否不想将'print'语句移动到'def'之前? – crookedleaf

+1

如果你希望这个代码在你调用函数之前运行,为什么它是函数的一部分? – user2357112

+0

我想要发生的事情(我应该指出这一点,我很抱歉)是代码无限期地运行,直到赢得条件满足。我很难搞清楚如何实现这一点,所以我打算弄清楚如何创建一个for循环来使用'continue'语句。我得到的答案是能够完成我想要的。再次,我对这个模糊的问题表示歉意,这是我在网站上的第一篇文章。我知道我不能以此为借口,所以我很抱歉。 – TheElderDogma

回答

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() 
相关问题