简体   繁体   中英

Python print statement not executing

I have a function that I'm calling from my main function.

def generate_new(tokens, outfile):
    print('NO')
    new_sents = []
    for i in range(0, len(tokens)):
        first = tokens[i]
        second = tokens[i]
    print('YES')

This is working fine. However, when I'm adding one more statement, only the first print gets executed.

def generate_new(tokens, outfile):
    print('NO')
    new_sents = []
    for i in range(0, len(tokens)):
        first = tokens[i]
        second = tokens[i+1]
        first_found = first
    print('YES')

I've already tried flushing the buffer. I suspect it's an indentation issue but this code was running fine previously. I added some statements to the end of the function and since then it never executes the statements outside the loop. What could be the issue? Thank you.

The issue is that you are accessing the list tokens out of bounds,

range(0, len(tokens)) goes from 0 to len(tokens)-1

Now when you access tokens[i+1] , it throws an index out of bound exception and execution stops. As a result nothing after the loop gets executed.

You should be able to see the Exception on the console.

Anyway, the fix -

Either change the logic or iterate only till len(tokens)-1

I hope that explains the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM