Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Function Help
#1
Hey everyone,

I'm a graduate student taking a Python course, and while the professor is great, his homework is unreasonably difficult. Seeing as I'm a beginner at this, my classmates and I have spent well over 10 hours each on five questions, and have only answered three of them thus far. I'm looking for some tips on how to code a function that only uses integers as inputs. I've attempted nested conditionals with "if" and "elif", tried using "try" and "except", and am just not able to come up with anything that gives me an error when floats are being entered. I don't feel that this really necessitates the modulus operator or Boolean expressions, but if they help, I'm all ears. The question is as follows.



"Implement a Python function that takes two integer arguments. Your function should return the result of the division of the two integers. If the result is an integer, the return type should be an integer. If the result is a floating point number, the return type should be a floating point number.

Write a main program that requests the two integers (perform error checking for non-integer inputs). Also in the main program you should call your defined function that takes 2 arguments and displays the result of the division and the return type."



I'm not so concerned about the second one as I am with the first. Writing the function in and of itself would not be so difficult if it wasn't restricted to integers only. Any assistance that could help me get started with this would be greatly appreciated. Thank you!
Reply
#2
Did the teacher not provide any lessons? Course material? You say you tried using try and except, what was the try?

Most of your problem can be solved by understanding int() and type().
Reply
#3
Many people struggle with this problem and some find really elegant solutions. Look for example at this thread: Homework 5.2. I think you can use this principle.
Let us see what you make of it and we will help you further. First read the instructions how to post your code and error message Smile in BBcode format.
Reply
#4
isinstance() would be useful here too.
Reply
#5
Quote:Implement a Python function that takes two integer arguments. Your function should return the result of the division of the two integers. If the result is an integer, the return type should be an integer. If the result is a floating point number, the return type should be a floating point number.

The solution for Python:
def division(a, b):
    return a / b
Oh, wait. But what happens if we divide Decimal / Decimal?
from decimal import Decimal

a = Decimal("0.1") + Decimal("0.2")
b = Decimal("0.1")

print(a / b, type(a/b))                                                                                                                                                              
Output:
3 <class 'decimal.Decimal'>
I guess the professor does this test also, if he knows Python well.
The other point is, that the division return always as float.
A float has the method is_integer().
From there you can get the information if the float should represent a integer.
Another trick could be, to use the modulo operator.
For example 10 % 5 == 0. The result is the rest. Rest 0 means, you can divide it.


  1. First check if the input arguments are int, if not raise ValueError("a is not an integer")
    if not isinstance(a, int):
        raise ValueError("The argument a is not an int.")
    Same check for b
  2. Then do the division, assign the result to a name.
  3. Then check, if the result is an integer, if this is the case, cast the float to an int.
    x = a / b
    if x.is_integer():
        x = int(x)
  4. return x
If you want to make your Professor angry, use also type annotations and then tell him, that this is meaningless for the interpreter :-D

from typing import Union


def division(a: int, b: int) -> Union[int, float]:
    ...
Quote:Write a main program that requests the two integers (perform error checking for non-integer inputs). Also in the main program you should call your defined function that takes 2 arguments and displays the result of the division and the return type."

I guess he want that you import the previous defined function into your main program and impement the function to ask the user for input.
The implementation to ask for integer (don't ask for permission, ask for forgiveness):

while True:
    user_input = input("Please enter an valid integer: " )
    try:
        int_value = int(user_input)
    except ValueError:
        print(user_value, "is not an valid integer.")
    else:
        # than branch is executed if no error happens
        # means, the cast to int was successful
        # if this is in a function (it should),
        # use return int_value instead of break
        break
Exception handling is in Python very important and the dirty little secret is,
that it's also used for for-loops as well for generators/coroutines.

It's a part of the control-flow in Python.
If an exception was raised inside a function and it was not catched, this exceptions bubbles up to the caller.
Then the caller has to handle the exception.

Exceptions you should know: ValueError, TypeError, IndexError, KeyError, NameError, ZeroDivisionError
  • int('1.5') -> ValueError
  • 'a' + 1.5 -> TypeError
  • my_list = []; my_list[5] -> IndexError
  • my_dict = {}; my_dict[5] -> KeyError
  • not_known_name -> NameError
  • 1/0 -> ZeroDivisionError
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
Man, you guys were great! Thank you all for your help. It was the "isinstance" that did the trick and helped me define the function. I'm very new to all of this, so I may have trouble posting code in BBC, but I'll try. Below is what I came up with, and it seems to work. I can't tell you how grateful I am.

def SmartDivision(x,y): 
    if not isinstance(x, int):
        raise ValueError('The argument x is not an int.')
    if not isinstance(y, int):
        raise ValueError('The argument y is not an int.') 
    else:
        if (x % y) == 0:
            return int(x/y)
        else: return float(x/y)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020