Skip to content Skip to sidebar Skip to footer

Break Is Not Activated Inside A For Loop In Python

I want to print the first 10 key-value pairs from the dictionary word_index and I wrote this code: for key, value in enumerate(word_index): count = 0 if count <10:

Solution 1:

You need to move the declaration of count before the for loop. It is reset to 0 at each iteration.

As a side note (I don't have enough reputation to comment) the for loop is probably not doing what you want. You named your variables key and value, which makes me believe that you want to iterate over the entries (key and value pairs) of the dictionary. To achieve that you should write:

fork,v in word_index.items():
  // omitted

What enumerate() does is to return an index that starts from 0 and it is incremented at each iteration. So the in your code, key is actually an index and value is the dictionary's key!

If you actually wanted to iterate over the keys and associate an index to each key, you should rename your variable to something more correct, for example index and key.

I recommend to spend some time studying Python, it will save you lots of debugging time.

Solution 2:

Initialize count outside the for loop.

count=0#intialize count herefor key, value inenumerate(word_index):
if count <10:
    print(f'key {key} : value: {value}')
    count = count + 1else:
    break

Post a Comment for "Break Is Not Activated Inside A For Loop In Python"