Create a function called printtype that takes one parameter

Question:

If the parameter is a string, return "String"
If the parameter is an int, return "Int"
If the parameter is a float, return "Float"

Code:-

def printtype(x): 
    if isinstance(x,int):
        return x
    elif isinstance(x,float):
            return x
    else:
        isinstance(x,str)
        return x
print(type(printtype(5)))
print(type(printtype(5.0)))
print(type(printtype("5")))

Error:-
Float’ != 2.5 : You must retrun Float if a dloat is passed into the printtype function

Asked By: Abrar

||

Answers:

This could solve your issue.

def printtype(x): 
    if isinstance(x,int):
        return "Int"
    elif isinstance(x,float):
        return "Float"
    elif isinstance(x,str):
        return "String"
    else:
        return "Unknown type"
      
print(printtype(5))
print(printtype(5.0))
print(printtype("5"))

Output::

Int
Float
String
Answered By: gsb22

Let’s try this :

def printtype(x): 
    if type(x) in [str, int, float]:
        return type(x)
    else:
        return "Unknown type"

Input

print(printtype(5))
print(printtype(5.0))
print(printtype("5"))

Output

<class 'int'>
<class 'float'>
<class 'str'>
Answered By: Khaled DELLAL
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.