-3

I want to define a function factorial(x), but the way I want to do it

x = int(input("x"))

needs to be inside the function

The function should be recursive. So it needs to call on itself.

I tried to do it but since taking input is called every recursive step, the function doesn't work in expected way.

Can anyone define such a working function?

ndrwnaguib
  • 5,623
  • 3
  • 28
  • 51
dhlee
  • 37
  • 1
  • 8

1 Answers1

1

You can let input to factorial be an optional parameter with a default of None. A value is prompted when there is no input value. After the input is set, just use the well-known recursive formula for factorial.

   def factorial(n=None):  # optional default parameter
        if n == None:      # sets value when no input
            n = int(input('Enter number: '))

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

    print(factorial())  # prompts for input
DarrylG
  • 16,732
  • 2
  • 17
  • 23