简体   繁体   中英

Check statement for a loop only once

Let's say I have following simple code:

useText = True

for i in range(20):
    if useText:
        print("The square is "+ str(i**2))
    else:
        print(i**2)

I use the variable useText to control which way to print the squares. It doesn't change while running the loop, so it seems inefficient to me to check it every time the loop runs. Is there any way to check useText only once, before the loop, and then always print out according to that result?

This question occurs to me quite often. In this simple case of course it doesn't matter but I could imagine this leading to slower performance in more complex cases.

The only difference that useText accomplishes here is the formatting string. So move that out of the loop.

fs = '{}'
if useText:
    fs = "The square is {}"

for i in range(20):
    print(fs.format(i**2))

(This assumes that useText doesn't change during the loop! In a multithreaded program that might not be true.)

The general structure of your program is to loop through a sequence and print the result in some manner.

In code, this becomes

for i in range(20):
    print_square(i)

Before the loop runs, set print_square appropriately depending on the useText variable.

if useText:
    print_square = lambda x: print("The square is" + str(x**2))
else:
    print_square = lambda x: print(x**2)

for i in range(20):
    print_square(i)

This has the advantage of not repeating the loop structure or the check for useText and could easily be extended to support other methods of printing the results inside the loop.

If you are not going to change the value of useText inside the loop, you can move it outside of for :

if useText:
    for i in range(20):
        print("The square is "+ str(i**2))
else:
    for i in range(20):
        print(i**2)

我们可以移动if外面for ,因为你提到useText没有改变。

If you write something like this, you're checking the condition, running code, moving to the next iteration, and repeating, checking the condition each time, because you're running the entire body of the for loop, including the if statement, on each iteration:

for i in a_list:
    if condition:
        code()

If you write something like this, with the if statement inside the for loop, you're checking the condition and running the entire for loop only if the condition is true:

if condition:
    for i in a_list:
        code()

I think you want the second one, because that one only checks the condition once, at the start. It does that because the if statement isn't inside the loop. Remember that everything inside the loop is run on each iteration.

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