如何打印出结果:

时间:2013-08-06 02:56:31

标签: python python-2.7

我正在尝试打印此代码,但是当我在Python 2.7中使用print命令时,我一直遇到错误
所以我非常理解解释器如何读取和执行该程序。将“print s”放在屏幕上查看结果的理想位置是什么?非常感谢你。

n = raw_input('input an integer value to compute its factorial:\n')
n = int(n)

def f(n):
    if n==0:                    
        return 1                
    else:
        m = f(n-1)
        s = n * m
        return s

3 个答案:

答案 0 :(得分:3)

我将f的定义移到了raw_input之上的上方。然后在最后,您可以使用f致电n并打印结果:

print f(n)

如果您愿意,可以将结果存储在变量中,尽管这里没有优势:

result = f(n)
print result

答案 1 :(得分:3)

根据我的经验,你可能想要更接近这个:

def f(n):
    if n==0:                    
        return 1                
    else:
        m = f(n-1)
        s = n * m
        return s

if __name__ == '__main__':
    n = raw_input('input an integer value to compute its factorial:\n')
    n = int(n)
    result = f(n)
    print result
    # or alternatively for the last two lines, if you don't want to save the result
    print f(n)

这样,当您从IDLE(或直接从命令行)执行此脚本时,它会运行if __name__块,但除此之外它只定义了该函数。

答案 2 :(得分:0)

如果要打印函数的返回值而不仅仅是s,则可以存储返回值并打印:

n = raw_input('input an integer value to compute its factorial:\n')
n = int(n)

def f(n):
    if n==0:                    
        return 1                
    else:
        m = f(n-1)
        s = n * m
        return s

result = f(n)
print result