factorial.py


Below is the syntax highlighted version of factorial.py from §2.3 Recursion.


#-----------------------------------------------------------------------
# factorial.py
#-----------------------------------------------------------------------

import sys
import stdio

#-----------------------------------------------------------------------

# Return n!.

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n-1)

#-----------------------------------------------------------------------

# Accept integer n as a command-line argument, compute n!, and write
# the result to stdout.

def main():
    n = int(sys.argv[1])
    fact = factorial(n)
    stdio.writeln(fact)

if __name__ == '__main__':
    main()
    
#-----------------------------------------------------------------------

# python factorial.py 1
# 1

# python factorial.py 2
# 2

# python factorial.py 3
# 6

# python factorial.py 4
# 24


Copyright © 2000–2015, Robert Sedgewick, Kevin Wayne, and Robert Dondero.
Last updated: Fri Oct 20 20:45:16 EDT 2017.