我无法弄清楚回叫的正确缩进。我或者收到“ SyntaxError:在函数外返回”的错误或意外缩进。
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")
答案 0 :(得分:1)
按照错误显示的内容: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")
答案 1 :(得分:0)
这是根据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")