0
a=[1, 2, 3, -2, -5, -6, 'geo'] 

for I in a:
    if I == star:
        continue
    if I<0:
        print('I=', I) 

I don't know how to let my program to distill the negative numbers and print only them avoiding strings. Please help me.

jpp
  • 134,728
  • 29
  • 196
  • 240

3 Answers3

2

This is what I think you are looking for. I fixed several formatting issues.

a = [1, 2, 3, -2, -5, -6, 'geo'] 

for I in a:
    if I == 'star':
        continue
    try:
        if I < 0:
            print('I=', I) 
    except TypeError:
        continue

# I= -2
# I= -5
# I= -6

Updated to catch only errors other than TypeError.

jpp
  • 134,728
  • 29
  • 196
  • 240
1

As per my understanding, you want to print only negative integers.
Below code should do it:

a=[1, 2, 3, -2, -5, -6, 'geo']

for I in a:
    if type(I) is int:
        if I < 0:
            print('I=', I)

Output:
I= -2
I= -5
I= -6

sid8491
  • 5,865
  • 4
  • 28
  • 51
  • 2
    You should use `isinstance(I, int)` instead of checking for explicit type identity. – poke Feb 01 '18 at 12:51
  • @poke there was already an answer mentioning isinstance() method, so I wrote different one. plus its easier to read and understand. :) – sid8491 Feb 02 '18 at 05:09
0

isinstance is the way to go.

    if isinstance(l, int) and l < 0:
        print('l=', l)
shnorkel
  • 25
  • 1
  • 5
  • 3
    I don't necessarily agree with the python idiom, but it seems to prefer `try...except...` above `isinstance`: https://stackoverflow.com/questions/21024913/python-isinstance-vs-hasattr-vs-try-except-what-is-better – jpp Feb 01 '18 at 12:24
  • Agreed. Gave your answer a +1. – shnorkel Feb 01 '18 at 12:27