quaductas quaductas - 4 years ago 116
Python Question

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download