我的Python代码中有一个我无法理解的错误

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

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

这是我第一次学习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.

   ` this is the code i wrote:  
     \#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()`

我不知道出了什么问题?

function error-handling compiler-errors 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.