Skip to content Skip to sidebar Skip to footer

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 va

Solution 1:

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 inrange(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.)

Solution 2:

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 inrange(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.

Solution 3:

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 inrange(20):
        print("The square is "+ str(i**2))
else:
    for i inrange(20):
        print(i**2)

Solution 4:

We can move if outside of for since you mentioned useText is not changing.

Solution 5:

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:

ifcondition:
    foriina_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.

Post a Comment for "Check Statement For A Loop Only Once"