dspano
dspano

Reputation: 3

how to do a factorial for loop and get final output

# Get N from the command line
import sys
N = int(sys.argv[1])

for N in range(1,4):
    N *= 4
print(N)

So, 4! is 4*3*2*1 = 24.

My output is only 16 and it wants me to output 24

Upvotes: 0

Views: 235

Answers (4)

Olivier Melançon
Olivier Melançon

Reputation: 22294

A few things are wrong with your program.

  1. It overwrites the input by using N as your loop variable.

  2. The loop's range does not depend on the input.

  3. The multiplied value is always 4 instead of being incremented from 1 to N in your loop.

Here is the correct way to implement the factorial:

# Get N from the command line
import sys
n = int(sys.argv[1])

result = 1

for i in range(1, n + 1):
    result *= i

print(result)

Or alternatively, use the math standard library.

import math

n = int(sys.argv[1])

result = math.factorial(n)

print(result)

Upvotes: 1

offeltoffel
offeltoffel

Reputation: 2801

You inquire N from sys.argv and then overwrite it within your loop. That's one problem.

Next: range(a,b) will create integers from a to b-1 (assuming stepsize is 1). So range(1,4) will create [1,2,3].

Your code does the following: It changes N to 1*4, then to 2*4, then to 3*4 (which is 12, not 16).

If you want to code a factorial the hard way, you need a seperated iterator (usually indicated as i) and multiply all the way up to N times.

Upvotes: 0

Kevin DS.
Kevin DS.

Reputation: 131

I recommend use math lib: https://docs.python.org/3/library/math.html (cf math.factorial(x))

# Get N from the command line
from math import factorial
import sys

N = factorial(int(sys.argv[1]))

Upvotes: 1

Austin
Austin

Reputation: 26039

This finds factorial of number inputted from command line:

# Get N from the command line
import sys
N = int(sys.argv[1])

for i in range(1, N):
    N *= i
print(N)

# if input is 4, it outputs 24.

Upvotes: 1

Related Questions