In: Computer Science
Python 3
Calculate factorial
Create a function that uses a loop to calculate the factorial of a number.
* function name: get_fact
* parameters: num (int)
* returns: int
* operation:
Must use a loop here. Essentially calculate and return the
factorial of
whatever number is provided.
but:
- If num is less than 1 or greater than 20, print "num is out of
range"
and exit the function
- If num is not an int, print "invalid num parameter" and exit
(easy way
to do this is to use exception handling around your range()
function if you
use a for loop)
Recall that factorial of n is the product of all integers from 1 to
n. For
example the factorial of 5 (5!) is 1*2*3*4*5 which is equal to 120.
4! is 24.
6! is 720. This will be extremely similar to the adding maching
problem from
last time EXCEPT instead of adding a user-entered number each time,
you are
instead multiplying by the next number in a sequence.
E.g.,
INITIALIZE PROD VARIABLE
LOOP X FROM 1 TO NUM
PROD GETS THE VALUE OF PROD TIMES X
RETURN PROD
Though of course you'll need a little more than that logic there
to handle
the input validation.
* expected output:
>>> get_fact(5)
# RETURNS 120
>>> get_fact(6)
# RETURNS 720
>>> get_fact(21)
num is out of range
# RETURNS None
>>> get_fact('dude')
invalid num parameter
# RETURNS None
>>> get_fact(7.1)
invalid num parameter
# RETURNS None
Factorial of what: 6
6! is 720
Factorial of what: 25
num is out of range
Factorial of what: 0
Goodbye!
Code:
def get_int(num):
if(num<1 or num>20):
print("num is out of
range")
return None
else:
PROD=1;
for x in
range(1,num):
PROD=PROD*x;
return PROD
a=int(input("Factorial of what:"))
j=get_int(a);
if(j!=None):
print(a,"! is ",j);
Output: