Search code examples
pythonfunctionvariablesarguments

Writing a function that calculates the ratio of two numbers


I am brand new to Python coding, so keep that in mind for the following problem. I am just learning the use of defining functions, arguments, and variables.

Define a function called ratioFunction that takes two numbers called num1 and num2 as arguments and calculates the ratio of the two numbers, and displays the results as (in this example num1 is 6, num2 is 3): ‘The ratio of 6 and 3 is 2’. The output after running the code should look like this:

Enter the first number: 6
Enter the second number: 3
The ratio of 6 and 3 is 2.

So here's what I've cooked up with my limited knowledge of coding and my total confusion over functions:

def ratioFunction(num1, num2):
    num1 = input('Enter the first number: ')
    int(num1)
    num2 = input('Enter the second number: ')
    int(num2)
    ratio12 = int(num1/num2)
    print('The ratio of', num1, 'and', num2,'is', ratio12 + '.')
ratioFunction(num1, num2)

I am utterly confused, any help would be appreciated!


Solution

  • The problem is that you aren't capturing the results of the call to int.

    def ratioFunction(num1, num2):
        num1 = input('Enter the first number: ')
        int(num1) # this does nothing because you don't capture it
        num2 = input('Enter the second number: ')
        int(num2) # also this
        ratio12 = int(num1/num2)
        print('The ratio of', num1, 'and', num2,'is', ratio12 + '.')
    ratioFunction(num1, num2)
    

    Change it to:

    def ratioFunction(num1, num2):
        num1 = input('Enter the first number: ')
        num1 = int(num1) # Now we are good
        num2 = input('Enter the second number: ')
        num2 = int(num2) # Good, good
        ratio12 = int(num1/num2)
        print('The ratio of', num1, 'and', num2,'is', ratio12 + '.')
    ratioFunction(num1, num2)
    

    Also, when you call ratioFunction(num1, num2) in your last line, this will be a NameError unless you have num1 and num2 definied somewhere. But honestly, this is totally unecessary because you are taking input. This function has no need for arguments. Also, there will be another bug when you print because you are using the + operator on ratio12 + '.' but ratio12 is an int and '.' is a string. Quick fix, convert ratio12 to str:

    In [6]: def ratioFunction():
       ...:     num1 = input('Enter the first number: ')
       ...:     num1 = int(num1) # Now we are good
       ...:     num2 = input('Enter the second number: ')
       ...:     num2 = int(num2) # Good, good
       ...:     ratio12 = int(num1/num2)
       ...:     print('The ratio of', num1, 'and', num2,'is', str(ratio12) + '.')
       ...:
    
    In [7]: ratioFunction()
    Enter the first number: 6
    Enter the second number: 2
    The ratio of 6 and 2 is 3.
    

    Although, likely, your function is suppose to take arguments, and you get input outside the function and pass it to it.