0
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.

2
  • 1
    put a if statement in to check if i is str, if it is print 'It's a string' and break, else do your calculations Commented Dec 7, 2021 at 9:56
  • can u show it in code? i got syntax error Commented Dec 7, 2021 at 10:09

2 Answers 2

1

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
    .
    .
    .
Sign up to request clarification or add additional context in comments.

Comments

0
    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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.