简体   繁体   中英

How do you make a function that divides fractions into simplest form python

I am taking a class and i'm confused. It would really help if you could guide me through the proccess of this and tell me what I am doing wrong. I have an error that has to do with the parentheses since theres nothing in them. I am a newbie so i'm sorry.

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

Your function is taking in arguments a , b , c , and d , but you're not using them anywhere. You're instead defining four new variables. Try:

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

and get rid of your empty parentheses bits, see if that does what you are trying to do.

you cannot declare a variable as you are doing n = () and then try to assign an integer or string to it.

n=() does not mean:

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

() ---> Tuples 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.

so within your function, if you want you varialbes to be assigned what is passed as an argument

for Ex:

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

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

consider reading more on tuples from the above link

n=() is a valid python statement and there is no issue with that. However n=() is evaluating n to an empty tuple() . I believe that what you are trying to do is as follows.

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

here is a simpiler way of writing the same function

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

print FractionDivider_2(1,2,3,4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM