pythonfactorial

Unable to make a factorial function in Python


My code

import sys

number=int(sys.argv[1])

if number == 0
    fact=1
else
    fact=number
for (x=1; x<number; x++)
    fact*=x;             // mistake probably here

print fact

I get the error

File "factorial.py", line 5
    if number == 0
                 ^
SyntaxError: invalid syntax

How can you make a factorial function in Python?


Solution

  • Here's your code, fixed up and working:

    import sys
    number = int(sys.argv[1])
    fact = 1
    for x in range(1, number+1):
        fact *= x
    
    print fact
    

    (Factorial zero is one, for anyone who didn't know - I had to look it up. 8-)

    You need colons after if, else, for, etc., and the way for works in Python is different from C.