0

Write a function (python3) named depends_on_the_type() that takes in a single parameter obj short for object. The function will work on the data types

  • boolean,
  • str,
  • float,
  • int

What is returned depends on the data type of the object:

  • If the obj is an int:

    • The function will return 'Zero' if obj == 0
    • The function will return the square of that integer if it is even
    • The function will return the cube of that integer if it is odd
  • If the obj is a float, the function will return the number multiplied by 1.5

  • If the obj is a str, the function will return the string concatenated with itself

  • If the obj is a bool, return the negation of that boolean

  • If the obj is not one of the above data types, return None

attempt:

def depends_on_the_type(obj):
    if obj == class(int):
        if obj == 0:
            return 'Zero'
        elif obj % 2 == 0:
            return obj**2
        elif obj % 2 == 1:
            return obj**3
    if obj == class(float):
        return obj*1.5
    if obj == class(str):
        return str(obj)
    if obj == class(bool):
        return not bool
    else:
        return None
emluk
  • 261
  • 1
  • 8
  • 1
    Hi Lukas, welcome on SO. Do you mind to have a read at [how-to-ask](/help/how-to-ask) and [mcve](/help/mcve) and edit your question accordingly? – rpanai Jul 30 '20 at 16:30
  • https://docs.python.org/3/library/functools.html#functools.singledispatch – Dima Tisnek Jul 31 '20 at 05:07

2 Answers2

0

You should have a look at the builtin function isinstance(). It takes two arguments object and classinfo. If the object argument is an instance of the classinfo argument it returns True. This is how you can handle the case of obj being an integer. I guess you'll figure the rest out by yourself.

def depends_on_the_type(obj):
    if isinstance(obj, int):
        if obj == 0:
            return 'Zero'
        elif obj % 2 == 0:
            return obj ** 2
        elif obj % 2 == 1:
            return obj ** 3

Here is the documentation for isinstance()

emluk
  • 261
  • 1
  • 8
0

Ok, to know the type of some data you have to use function type (), which takes an argument and returns the type of value, then so that in the end it doesn't always come out None uses "if", "elif", "else ", if you modify your code it will end like this :

if type(obj) == int :
    if not obj % 2 :
        return "zero"
    elif obj % 2 :
        return obj ** 3
    else:
        return obj ** 2
elif type(obj) == float:
    return obj ** 1.5
elif type(obj) == str:
    return obj
elif type(obj) == bool
    return not bool
else:
   return None