Search code examples
pythonfactorialncr

Function takes 0 positional arguments but 1 was given


I am writing Python code that calculates nCr. I made a factorial function to use in the process.

I'm getting the following error:

ERROR! Traceback (most recent call last): File "<string>", line 16, in <module> File "<string>", line 13, in nCr TypeError: fact () takes 0 positional arguments but 1 was given.

This is the code:

#function that calculate the factorial
 def fact ():
 mul=1
 num=input ("enter number="))
 for i in range (1, num+1):
     mul=mul*i
 print ("the factorial of the number=",mul)
 fact ()
#function that calculate nCr=
def nCr():
    n=float (input ("enter 1st number(n)="))
    r=float (input ("enter 2nd number(r)="))
    nCr=fact(n)/(fact(r)*fact(n-r))
    if n>=r:
        print("the results of the fuction nCr=",nCr)
nCr()

How can I resolve this error?


Solution

  • Your function fact() does not take any arguments, but you are passing an argument when you call it here: nCr=fact(n)/(fact(r)*fact(n-r))

    You can fix it like this:

    # Function that calculates the factorial
    def fact(num):
        mul = 1
        for i in range(1, num + 1):
            mul *= i
        return mul
    
    # Function that calculates nCr
    def nCr():
        n = int(input("Enter 1st number (n): "))
        r = int(input("Enter 2nd number (r): "))
        
        nCr_value = fact(n) / (fact(r) * fact(n - r))
        if n >= r:
            print("The result of the function nCr =", nCr_value)
        else:
            print("Invalid input: n should be greater than or equal to r")
    
    nCr()  # Call the nCr function
    

    Now your function fact() only calculates the factorial of the number you pass as an argument. Getting the user input is now done in nCr() since it only needs to be done once at the beginning, not each time you calculate a factorial.

    I also added the else statement to inform the user if they enter invalid input instead of just ending silently.