函数采用 0 个位置参数,但给出了 1 个

问题描述 投票:0回答:1

我正在编写计算 nCr 的 Python 代码。我制作了一个阶乘函数以在该过程中使用。

我收到以下错误:

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.

这是代码:

#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()

我不知道怎么了?

python factorial ncr
1个回答
0
投票

你的函数

fact()
不接受任何参数,但是当你在这里调用它时你正在传递一个参数:
nCr=fact(n)/(fact(r)*fact(n-r))

你可以这样修复它:

# 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

现在你的函数

fact()
只计算你作为参数传递的数字的阶乘。获取用户输入现在在
nCr()
中完成,因为只需在开始时完成一次,而不是每次计算阶乘时完成。

我还添加了

else
语句来通知用户是否输入了无效输入,而不是只是默默结束。

© www.soinside.com 2019 - 2024. All rights reserved.