tcam23
tcam23

Reputation: 1

Creating Python Factorial

Evening,

I'm an intro to python student having some trouble. I'm trying to make a python factorial program. It should prompt the user for n and then calculate the factorial of n UNLESS the user enters -1. I'm so stuck, and the prof suggested we use the while loop. I know I didn't even get to the 'if -1' case yet. Don't know how to get python to calc a factorial with out just blatantly using the math.factorial function.

import math

num = 1
n = int(input("Enter n: "))

while n >= 1:
     num *= n

print(num)

Upvotes: 0

Views: 1236

Answers (6)

user19863245
user19863245

Reputation:

i=1
f = 1
n = int(input("Enter n: "))
if n>=0:
  while n >= i:
    f=i*f
    i+=1
  print(f)

I am using this code in order to calculate factorial and it works.(Python 3.8)

Upvotes: 0

Praveen Acharya
Praveen Acharya

Reputation: 1

#Factorial using list
fact=list()
fact1=input("Enter Factorial Number:")
for i in range(1,int(fact1)+1):
    fact.append(i)
 print(fact)
 sum=fact[0]
 for j in range(0,len(fact)):
        sum*=fact[j]
        print(sum)

Upvotes: 0

Chris Yuh
Chris Yuh

Reputation: 77

You could do something like this.

    def Factorial(y):
        x = len(y)
        number = 1
        for i in range(x):
            number = number * (i + 1)
            print(number)

Upvotes: 0

keep learning
keep learning

Reputation: 1

I am new to python and this is my factorial program.

def factorial(n):

x = []
for i in range(n):
    x.append(n)
    n = n-1
print(x)
y = len(x)

j = 0
m = 1
while j != y:
    m = m *(x[j])
    j = j+1
print(m)

factorial(5)

Upvotes: 0

dawg
dawg

Reputation: 103774

The 'classic' factorial function in school is a recursive definition:

def fact(n):
    rtr=1 if n<=1 else n*fact(n-1)
    return rtr

n = int(input("Enter n: "))
print fact(n)

If you just want a way to fix yours:

num = 1
n = int(input("Enter n: "))

while n > 1:
    num *= n
    n-=1        # need to reduce the value of 'n' or the loop will not exit

print num

If you want a test for numbers less than 1:

num = 1
n = int(input("Enter n: "))

n=1 if n<1 else n    # n will be 1 or more...
while n >= 1:
    num *= n
    n-=1        # need to reduce the value of 'n' or the loop will not exit

print num

Or, test n after input:

num = 1
while True:
    n = int(input("Enter n: "))
    if n>0: break

while n >= 1:
    num *= n
    n-=1        # need to reduce the value of 'n' or the loop will not exit

print num

Here is a functional way using reduce:

>>> n=10
>>> reduce(lambda x,y: x*y, range(1,n+1))
3628800

Upvotes: 4

user2555451
user2555451

Reputation:

You are actually very close. Just update the value of n with each iteration:

num = 1
n = int(input("Enter n: "))

while n >= 1:
    num *= n
    # Update n
    n -= 1
print(num)

Upvotes: 1

Related Questions