+ 1
str and int
Hi. Who can help me, i just started learning. I want to display separately positive numbers and if i have a string in list display the message "there is a line in the list" a = [1,4,78,56, -76, 'qwe'] for item in a: if item >= 0: print ('Positive numbers: {}'.format(item)) # elif in a str...... print ('There is a strung in list!') answer: Positive numbers: 1 Positive numbers: 4 Positive numbers: 78 Positive numbers: 56 Positive numbers: qwe #I don't want to see it here There is a string in list! #and it should work
4 Réponses
+ 7
If you do it like that you will get an error something like this when you use Python3
TypeError: '>=' not supported between instances of 'str' and 'int'
so it's better to first print str then print positive (use elif, not if)
+ 8
if isinstance(item, str): #or "type(item) is str"
print('string')
elif item >= 0:
print('Positive:', item)
+ 1
Mert Yazıcı thank you, I made my way, with your help
a = [1,4,78,56, -76, 'qwe']
for item in a:
if item >= 0 and type(item) is not str:
print ('Positive numbers: {}'.format(item))
if type(item) is str:
print('There is a string in list!')
+ 1
a = [1,4,78,56, -76, 'qwe']
for item in a:
if type(item) is str:
print('There is a string in list!')
elif item >= 0 and type(item) is not str:
print ('Positive numbers: {}'.format(item))