Python语法错误返回或缩进

2024-04-27 00:27:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想不出回电的正确缩进。我要么得到一个错误'SyntaxError:'return'outside function',要么得到意外的缩进

def fun(a, r):
    sum, term = 0, a
    print("1st term is: ", term)
    sum += term
for i in range(2, 20 + 1):
    term *= r
    sum += term
    print(str(i)+"th term is: "+str(term))
    print("Sum of first 20 terms is: ", sum)
    return sum
if __name__ == '__main__':
    a, r = 6, 2
    Sum_formula = a*(pow(r, 20)-1) / (r-1)
    Sum_loop = fun(a, r)
    print("Sum of first 20 terms using formula: ", Sum_formula)
if Sum_formula-Sum_loop == 0:
    print('Both sum are same, calculation is correct!!!')
else:
    print("There is some error in your calculation")

Tags: ofinloopreturnifisfirstsum
2条回答

按照错误所说的:SyntaxError: 'return' outside function,这是您问题的公认答案,要理解我的意思,该部分的工作代码是:

def fun(a, r):
    sum, term = 0, a
    print("1st term is: ", term)
    sum += term
    for i in range(2, 20 + 1):
        term *= r
        sum += term
        print(str(i)+"th term is: "+str(term))
        print("Sum of first 20 terms is: ", sum)
        return sum

整个代码是:

def fun(a, r):
    sum, term = 0, a
    print("1st term is: ", term)
    sum += term
    for i in range(2, 20 + 1):
        term *= r
        sum += term
        print(str(i)+"th term is: "+str(term))
        print("Sum of first 20 terms is: ", sum)
        return sum

if __name__ == '__main__':
    a, r = 6, 2
    Sum_formula = a*(pow(r, 20)-1) / (r-1)
    Sum_loop = fun(a, r)
    print("Sum of first 20 terms using formula: ", Sum_formula)
if Sum_formula-Sum_loop == 0:
    print('Both sum are same, calculation is correct!!!')
else:
    print("There is some error in your calculation")

下面是根据python语法的正确缩进(不改变逻辑)

def fun(a, r):
    sum, term = 0, a
    print("1st term is: ", term)
    sum += term
    for i in range(2, 20 + 1):
        term *= r
        sum += term
        print(str(i)+"th term is: "+str(term))
        print("Sum of first 20 terms is: ", sum)
        return sum

if __name__ == '__main__':
    a, r = 6, 2
    Sum_formula = a*(pow(r, 20)-1) / (r-1)
    Sum_loop = fun(a, r)
    print("Sum of first 20 terms using formula: ", Sum_formula)
    if Sum_formula-Sum_loop == 0:
        print('Both sum are same, calculation is correct!!!')
    else:
        print("There is some error in your calculation")

相关问题 更多 >