2015-08-26 106 views
0

经过一番研究,我无法找到为什么我在此codeacademy练习中得到指定的错误(SyntaxError: 'return' outside function)。“返回外部函数”错误

name=input(" input name ") 
print("welcome, {}".format (name)) 

class player(): 

    def __init__(self, atk, hp,): 
     self.atk=atk 
     self.hp=hp 

    def __str__(self): 
     return "{}, {}".format (self.atk, self.hp) 

input("Time for a questionnaire to define your stats") 
input("press enter to continue....") 
print("in an intense battle when both you and your enemy are on the edge of consciousness and you have a chance to flee do you finish off the opponent taking a chance on being struck down or do you flee with your life?") 
statq1=input("fight or flee") 
if statq1 == "fight": 
    return 5+self 
elif statq1 == "flee": 
    return 5+hp 
+2

它告诉你'return'是功能之外,因为它_is_(这就是坏的)。我建议刷新缩进以及'return'语句的具体含义。 – TigerhawkT3

+0

您能否提供一个最简单的工作示例?您在问题中提供的代码根本不可用。 – XaF

+0

那我该如何解决这个问题呢? –

回答

3

returnreturn必须在函数内。现在,代码位于脚本的底部,因此您可以将5+self保存到变量以供稍后使用,或者将它打印到屏幕上。

,使之成为一个功能:

def start(): 
    input("Time for a questionnaire to define your stats") 
    input("press enter to continue....") 
    print("in an intense battle when both you and your enemy are on the edge of consciousness and you have a chance to flee do you finish off the opponent taking a chance on being struck down or do you flee with your life?") 
    statq1=input("fight or flee") 
    if statq1 == "fight": 
     return 5+self 
    elif statq1 == "flee": 
     return 5+hp 

print(start()) 
+0

谢谢,这可以帮助我很多 –

+0

@ErRds'返回'大致意味着像“退出一个函数,并带回你的价值”。如果你把'return'放在外部范围内,而没有功能,它应该去哪里?困惑? Python也是如此。因此,错误。 :) –

+0

@CasualDemon 谢谢了。 认为这让我更清楚地知道为什么我不断得到返回错误的类型。 –