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
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
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'>
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
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
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'>