Python返回外部函数语法错误

时间:2014-11-09 03:27:31

标签: python

您好,我正在浏览Google的Python课程,并且正在进行其中一项练习。这是练习

# A. donuts
# Given an int count of a number of donuts, return a string
# of the form 'Number of donuts: <count>', where <count> is the number
# passed in. However, if the count is 10 or more, then use the word 'many'
# instead of the actual count.
# So donuts(5) returns 'Number of donuts: 5'
# and donuts(23) returns 'Number of donuts: many'
I have so far tried: 

def donuts(count):
    if count >= 10:
      print 'Number of donuts: many'
    else:
      print 'Number of donuts: %d' % (count)
return count

但到目前为止,我一直收到上面的语法错误。有人可以解释这个吗?

1 个答案:

答案 0 :(得分:4)

returndef的缩进位置相同。它应该是这样的:

def donuts(count):
    if count >= 10:
        print 'Number of donuts: many'
    else:
        print 'Number of donuts: %d' % (count) 
    return count

return命令是函数定义的一部分,因此必须在函数简介(def donuts())下缩进。如果不是,那么解释器就无法知道return语句不仅仅是更广泛代码的一部分。

然而,正如freeforall所说,问题要求返回一个字符串,所以正确的答案看起来更像:

def donuts(count):
    if count >= 10:
        return 'Number of donuts: many'
    else:
        return 'Number of donuts: %d' % count