# What is the error in this coding?

+1 vote
num=int(input("Enter a number:"))
if(num==0):
fact=1
fact=1
for i in range(1,num1+):
fact=fact*i
print("Factorial of",num,"is",fact)

answered Sep 9 by (4,660 points)
• Logical error in 'if statement' since the code would only execute further if the number entered is 0. We would want a number 1 or greater (only if one if statement is present). In your case, you would want if(num != 0)
• Double declaration and assignment of fact variable (not causes any issues but not needed)
• In your for loop, 1 and + are wrong way round. We would want for..... range(1, num+1)
• Alternative method of fact=fact*i is fact*=i
• However, with the fixes, the factorial statement is printed multiple times and only the last statement printed is correct. To only print once, we would move the print statement to indented inline with for.

A working solution but slightly different to support negative numbers, 0 and 1 or greater:

num = int(input("Enter a number: "))

factorial = 1

if num < 0:
print("Negative number don't have a factorial")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

answered Sep 19 by (200 points) 2 flags
• Logical error in 'if statement' since the code would only execute further if the number entered is 0. We would want a number 1 or greater (only if one if statement is present). In your case, you would want if(num != 0)
• Double declaration and assignment of fact variable (not causes any issues but not needed)
• In your for loop, 1 and + are wrong way round. We would want for..... range(1, num+1)
• Alternative method of fact=fact*i is fact*=i
• However, with the fixes, the factorial statement is printed multiple times and only the last statement printed is correct. To only print once, we would move the print statement to indented inline with for.

A working solution but slightly different to support negative numbers, 0 and 1 or greater:

num = int(input("Enter a number: "))

factorial = 1

if num < 0:
print("Negative number don't have a factorial")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

answered 3 days ago by (500 points)
Hello.

number = int(input("Enter number: "))
f = number
factorial_value = 1
while number > 0:
factorial_value *= number
number -= 1
print("{}! = {}".format(f, factorial_value))

#f variable is used to format the ans value
#because in loop, the last value of number will be 0
#and 0! is 0 and not the ans that we get.
#factorial_value is set to 1 because if set to 0
#ans will always be 0.
#In the loop, number is multiplied with factorial value
#then number is decreased by 1
#and the loop will continue till number = 0 and
#as 0 = 0 and not greater than 0
#loop breaks and program prints the factorial value