Reputation: 21
It is not giving output, as expected, which says" {friend} is my friend", when {friend} is a string. And "you are not a name.......," when {friend} is a string.
Friends=["ankit","kanishk","manish","vansh","tanmay",34]
for friend in Friends:
if friend is int:
print(f"you are not a name, you are a number {friend}")
elif friend is str:
print( friend.title()+" is my friend.")
Upvotes: 0
Views: 50
Reputation: 2379
What you are doing is checking the value as int
and not the datatype of it. To check the datatype we have to use type()
.
>>> 34 is int
False
>>> type(34) == int
True
Friends=["ankit","kanishk","manish","vansh","tanmay",34]
for friend in Friends:
if type(friend) == int:
print(f"you are not a name, you are a number {friend}")
elif type(friend) == str:
print( friend.title()+" is my friend.")
Output:
Ankit is my friend.
Kanishk is my friend.
Manish is my friend.
Vansh is my friend.
Tanmay is my friend.
you are not a name, you are a number 34
Upvotes: 0
Reputation: 1005
You can use isinstance like below,
Friends=["ankit","kanishk","manish","vansh","tanmay",34]
for friend in Friends:
if isinstance(friend, int):
print(f"you are not a name, you are a number {friend}")
elif isinstance(friend, str):
print( friend.title()+" is my friend.")
Upvotes: 0
Reputation: 52
Friends=["ankit","kanishk","manish","vansh","tanmay",34]
for friend in Friends:
if type(friend) is int:
print(f"you are not a name you are a number which is {friend}")
elif type(friend) is str:
print( friend.title()+" is my friend.")
you should add the 'type()' function for friend. friend's type is int or str.
Upvotes: 1