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.
Related
who can say me:
What is the difference between writing code inside else or just after the loops?
for x in range(6):
print('hello')
print('bye')
or
for x in range(6):
print('hello')
else:
print('bye')
From for/else documentation:
The else clause executes after the loop completes normally. This means that the loop did not encounter a break statement.
This means that in your specific example there is no difference in using else or not.
In the second example you're using conditional statement, Whereas in the first scenario after the loop completes, It automatically executes the next line.
Basically your post is an example of getting same result with alternative solutions.
Though your first solution can be considered as valid practice comparing with second one.
Although I would suggest you to read this article before posting any questions on stack overflow.
I'm trying to exit an infinite loop but I'm stuck in it. I've tried using the break statement in different ways but the result is always the same: the program terminates after exiting the loop and it doesn't perform the rest of the code. What should I change in the code to solve this problem?
moylist = []
import copy
while True:
thing = input()
if thing == '':
break
moylist.append(thing)
moylist.insert(-2, 'and')
moynovlist = copy.deepcopy(moylist)
moynovlist1 = moynovlist[-2:] # cutting the end
perv = str(moynovlist1)
perv1 = perv[:4] + perv[4:] #without the comma (and ...)
The code is running fine! The reason you think it is exiting the whole program instead of just the while loop is because you don't have any print statements. Simply add, print(perv1) at the end of your program and you'll see that perv1 changes, meaning the loop was exited properly.
every time I am debugging a code that contains a for-loop e.g.
# When I debug this code
for i in range(3):
print(i)
I come to want to fix a variable and execute the code, such as
# I want to do this
i = 2
# for i in range(3):
print(i)
However, the above code results in an error because there is an unexpected indent. So I always have to unindent the lines inside the for-loop, which is repetitive work:
# But I have to do this
i = 2
# for i in range(3):
print(i)
Question
Are there any ways to leave the indentation unchanged while commenting out the for line?
Replace the for loop with a block statement that executes the contents unconditionally:
i = 2
# for i in range(3):
if 1: # Or if you prefer, if True:
print(i)
Now the indent is expected, but since if 1:/if True: execute unconditionally (in Python 3, on the CPython reference interpreter, both of them optimize out the if completely; it executes without any sort of test), it behaves identically to the manually dedented version.
Alternatively, without adding an i = 2 at all, you can make the for loop loop over a single constant value:
for i in [2]: # range(3): Old code
print(i)
to get the same effect. for i in (2,): (parens optional) would also work, but that trailing comma that one-tuples require messes a lot of people up, and as it happens, loops over lists of constant literals are optimized to loops over tuples of constant literals anyway, so no performance loss is incurred.
You can make the for loop iterate over a single-item tuple instead:
for i in 2,:
# for i in range(3):
print(i)
I have a kinda weird problem, here is my attempt at an explanation:
I'm currently making a program which opens a txt file and then reads a line for that file, using the following command linecache.getline(path,number), after the function is done I then use commmand linecache.clearcache.
If I then change something in the text file it keeps returning the pre-changed line.
Following is the code I'm using (I know it aint really pretty)
def SR(Path,LineNumber):
returns = lc.getline(Path,LineNumber)
x = np.array([])
y = np.array([])
words = returns.split()
for word in words:
x = np.append([x],[word])
for i in range(len(x)):
t = float(x[i])
y = np.append([y],[t])
return y
del x
del y
del t
del words
lc.clearcache()
Nothing after the return statement will ever be executed. If you want to call clearcache, you need to call it before the return statement.
Also, as a side note, your del statements aren't really going to do anything either, even if they were placed before the return. del effectively just decrements the reference counter in the gc, which will happen when the interpreter exits the function scope anyway.
This question already has answers here:
Is there a difference between "pass" and "continue" in a for loop in Python?
(13 answers)
Closed 5 years ago.
My test shows that both pass and continue can be used equivalently to construct a empty for-loop for test purpose. Are there any difference between them?
The pass keyword is a "no-operation" keyword. It does exactly nothing. It's often used as a placeholder for code which will be added later:
if response == "yes":
pass # add "yes" code later.
The continue keyword, on the other hand, is used to restart a loop at the control point, such as with:
for i in range(10):
if i % 2 == 0:
continue
print(i)
That loop will only output the odd numbers since continue returns to the loop control statement (for) for iterations where i is even.
Contrast that with the exact same code, but using pass in place of continue:
for i in range(10):
if i % 2 == 0:
pass
print(i)
That loop prints all the numbers in the range, since pass does not return to the loop control statement for even (or any) values of i. It simply drops through to the print statement.
In terms of an empty for loop, you're correct that they're functionally identical. You can use either of:
for i in range(10):
pass
for i in range(10):
continue
pass does nothing (no operation), while continue make control flow to continue to next cycle of the loop.
If the loop contains only a single statement, a pass or continue won't make any difference. But if there are multiple statements, then it matters:
for item in my_list:
pass
print(item) #This will be executed
for item in my_list:
continue
print(item) #won't be executed
Basically, the pass statement do nothing, while the continue statement will restart the loop.
But in your case:
for item in my_list:
pass
#Since there's nothing after pass, the loop is finished.
for item in my_list:
continue
#You're restarting the loop
There difference is not very visible.
Hope this helps!
continue means "skip to the end of the loop body". If it's a while loop, the loop continues on to the loop test; if it's a for loop, the loop continues on to the next element of whatever it's iterating over.
pass does absolutely nothing. It exists because you have to have something in the body of an empty block statement, and pass is more readable than executing 1 or None as a statement for that purpose.
This will lead to an infinite loop if you use continue:
i = 0
while i<1:
continue
i = i + 1
print i
because continue only goes to the next iteration. But pass will work for this case.
pass and continue both work, but may create infinite loops.
For example, the following code will create infinite loop.
i = 0
while i<100:
continue # replacing continue with pass still creates an infinite loop.
If you want to avoid this (perhaps you intend to modify i withe loop, but you haven't written the code yet), use break.