如何创建一个将分数分成最简单形式的函数

2024-09-29 17:20:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在上课,我很困惑。如果你能指导我完成这个过程,告诉我我做错了什么,那真的会很有帮助。我有一个与括号有关的错误,因为括号里什么都没有。我是个新手,所以我很抱歉。你知道吗

def FractionDivider(a,b,c,d):
    n = ()
    d = ()
    n2 = ()
    d2 = ()
    print int(float(n)/d), int(float(n2)/d2)
    return float (n)/d / (n2)/d2

Tags: return过程def错误float括号intd2
3条回答

n=()是一个有效的python语句,没有任何问题。但是n=()正在将n求值为空tuple()。我相信你想做的事情如下。你知道吗

def FractionDivider(a,b,c,d):
    '''
        Divides a fraction by another fraction...
        '''

    n = a #setting each individual parameter to a new name.
    d = b #creating a pointer is often useful in order to preserve original data
    n2 = c #but it is however not necessary in this function
    d2 = d
    return (float(n)/d) / (float(n2)/d2) #we return our math, Also order of operations exists here '''1/2/3/4 != (1/2)/(3/4)'''

print FractionDivider(1, 2, 3, 4) #here we print the result of our function call.

#indentation is extremely important in Python

这里有一个简单的方法来编写相同的函数

def FractionDivider_2(n,d,n2,d2):
    return (float(n)/d) / (float(n2)/d2)

print FractionDivider_2(1,2,3,4)

您的函数正在接受参数abcd,但是您没有在任何地方使用它们。而是定义了四个新变量。尝试:

def FractionDivider(n, d, n2, d2):

去掉你的空括号,看看这是否符合你的意图。你知道吗

不能在执行n=()时声明变量,然后尝试为其分配整数或字符串。你知道吗

n=()并不意味着:

n equals nothing at the moment but i will assign a variable shortly.

()->;元组https://docs.python.org/3/tutorial/datastructures.html

They are two examples of sequence data types (see Sequence Types — list, tuple, range). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple.

所以在函数中,如果你想给变量赋值,那么就把它作为参数传递

例如:

def FractionDivider(a,b,c,d):

    n = a
    d = b
    n2 = c
    d2 = d

考虑从上面的链接阅读更多关于元组的内容

相关问题 更多 >

    热门问题