1

Currently, I'm on Day 9 on the hackerrank 30 days of code (python 3) challenge, and I ran into this error, which I am not able to fix:

#!/bin/python3

import sys
from math import *

def factorial(n):

    n = int(input())

    if n == 0 :
        print("1") 
    else:
        print(factorial(n))

Thanks for the help

K. A. Buhr
  • 40,148
  • 3
  • 38
  • 66
Dank Dorito
  • 29
  • 1
  • 1
  • 5
  • Please read [How to ask](https://stackoverflow.com/help/how-to-ask). Reformat your code. – buhtz Jan 09 '18 at 01:45
  • 4
    If input is not zero, when does the recursion end? And, you don't return anything from `factorial` so what do you expect `print(factorial(n))` to print? – Johnny Mopp Jan 09 '18 at 01:47

3 Answers3

0

Ofcourse there wont be any output unless the the value of n is 0.

Your program gets struck into an infinite recursion when the input is different from 0, because there is no base case. In a base case, there must be a return statement for a definition. You should learn the difference between the return and print statements.

The correct code for finding factorial is as shown.

def factorial(n):

    if n == 0 :
        return 1 
    else:
        return n*factorial(n-1)
     
TheAztec
  • 33
  • 8
0

you have defined the function factorial but you should also call it for the number you want to calculate the factorial. for example ,factorial(10), later on in the code. i also got the same error no response on stdout and this is what i did to solve it. hopes it helps.

0
import sys

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