-4

I've been coding for my course. It wants input but it doesn't show the result. Here my code:

def XYZ():
    n = int(input("Enter A Number:"))
    z = list(range(1, n + 1))

    def fact(n):
        while True:
            if n == 1:
                return 1
            return n * fact(n - 1)

    def Summation(List):
        if len(List) == 1:
            return List[0]
        else:
            return List[0] + Summation(List[1:])

    z1 = [i / fact(i) for i in z]
    return Summation(z1)

XYZ()
martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

0

Try this code:

def XYZ():
    n = int(input("Enter A Number: "))
    z = list(range(1, n + 1))

    def fact(n):
        while True:
            if n == 1:
                return 1
            return n * fact(n - 1)

    def Summation(List):
        if len(List) == 1:
            return List[0]
        else:
            return List[0] + Summation(List[1:])

    z1 = [i / fact(i) for i in z]
    return Summation(z1)

result = XYZ()
print(result)
Dharman
  • 30,962
  • 25
  • 85
  • 135
Aditya
  • 1,132
  • 1
  • 9
  • 28
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Dharman Dec 05 '20 at 20:37
0

There are several IDEs available for python, which is based on user choice and preferences. For instance, much data scientist or related persons use the so-called Jupyter Notebook which comes with the anaconda distribution.

Now, Jupyter Notebook will show the output in-line of the last statement/code executed (if there is something to print) without actually providing a print(var) statement. But, this is not the case for many other IDEs or if you run the code from terminal/command prompt - there you must add print(XYZ()), as commented previously. Hope this answered your question!

Coming to coding prespective, I don't see any point of making your code so complicated just to do a "simple factorial" of a number. This can be achieved by just using a single line of code:

import math

def factorial(n):
    return math.prod(list(range(n, 0, -1)))

print(factorial(n = int(input("Enter a Number:"))))

There are several reasons for this:

  1. It is better to keep your input/arguments outside your function. This gives you more control.
  2. Using inbuilt basic tools like math or os etc. makes your code much faster.
  3. If you still want to go for functions without using a single library, you can include your summation within a single function.
Mr. Hobo
  • 530
  • 1
  • 7
  • 22