Yoni Agronov
Yoni Agronov

Reputation: 23

i want to break the loop when there string in the list python

lst1 = [1,2,3,4,5,"hello",6,7,8,9,]
countodd = 0
counteven = 0
for i in range(len(lst1)):
    if i%2 != 0:
     countodd += 1
    else:
     counteven += 1
    else:
    type(lst1) == str:
        break
     print("this is string!!")
print("this counter of even numbers:",counteven)
print("this counter of odd numbers:",countodd)

Create a python program that will count the number of appearances of odd and even values in a list. In case that the program encounters a string use break statement and return a print that says, “It’s a string!!!” and nullify the values of odd and even numbers counters.

Upvotes: 0

Views: 864

Answers (2)

orby
orby

Reputation: 352

    lst1 = [1, 2, 3, 4, 5, "hello", 6, 7, 8, 9, ]

    countodd = 0
    counteven = 0

    # no need to do range(len(lst1)) to iterate
    for i in lst1:

        if isinstance(i, str):
            print("this is string!!")
            countodd = 0
            counteven = 0
            break

        if i % 2 != 0:
            countodd += 1
        else:
            counteven += 1

    print("this counter of even numbers:", counteven)
    print("this counter of odd numbers:", countodd)

Upvotes: 0

Yoav Sheetrit
Yoav Sheetrit

Reputation: 149

As you said, break the loop once you find a string, and nullify the counters:

for i in range(len(lst1)):
    if isinstance(lst1[i], str):
        print("It’s a string!!!")
        countodd = 0 # or None
        counteven = 0 # or None
        break
    .
    .
    .

Upvotes: 1

Related Questions