Skip to main content

How to Run a Function or a Loop Only Once in Python

In programming, you may encounter situations where a block of code, either within a function or a loop, is intended to run only once.

This guide explores various techniques for achieving this in Python, covering approaches for both functions and loops using flags, attributes, and control flow mechanisms.

Running a Function Only Once

Several techniques can be used to execute the main body of a function only once, while any subsequent calls return without doing anything.

Using a Global Variable

You can use a global variable as a flag to track whether the function has already run.

sum_has_run = False  # Global flag

def sum(a, b):
global sum_has_run # Accessing the global scope
if sum_has_run:
return

sum_has_run = True # Set the flag to True
return a + b

print(sum(100, 100)) # Output: 200
print(sum(100, 100)) # Output: None
  • The global sum_has_run statement is used to modify the global variable in the function's local scope.
  • The if sum_has_run: condition checks whether the function's body has already been executed. If so, it returns, without executing the function's body.
  • The first time the function is called sum_has_run is False and the function's body is executed, setting sum_has_run to True. Any further function calls will encounter sum_has_run == True condition.

Using a Function Attribute

A more elegant approach is to store the execution status directly as an attribute of the function:

def sum(a, b):
if getattr(sum, 'has_run', False): # Check for attribute
return

sum.has_run = True # Set attribute to True
return a + b

print(sum(100, 100)) # Output: 200
print(sum(100, 100)) # Output: None
  • The getattr(sum, 'has_run', False) checks for the has_run attribute on the function. If it doesn't exist, it defaults to False.
  • The first time it runs, the has_run attribute is set to True. Subsequent calls return without executing any code since the attribute will exist and its value will be True.

Running a Loop Only Once

While loops generally repeat, but they can be modified to execute the block only once, or the loop can be terminated using a break statement.

Using range(1)

Use the range(1) function with the for loop:

for _ in range(1):
print('Loop is only run once') # Output: Loop is only run once
  • range(1) creates a sequence with only one element (0), so the loop runs exactly once.

Using while True with break

while True:
print('Loop is only run once') # Output: Loop is only run once
break # immediately exit loop
  • The break statement in a while loop causes immediate exit.
  • This is a useful way to only run the loop once.

Using break in a for Loop

You can also use break to terminate a for loop during the first iteration. This will only work if you don't need the elements from the iterable.

a_list = ['tutorial', 'reference', 'com']

for item in a_list:
print(item) # Output: tutorial
break # exit for loop
  • The break keyword exits the loop after the first item is printed.

Using a Boolean Flag Variable

Use a boolean flag to control loop execution:

a_list = ['tutorial', 'reference', 'com']
has_run = False
for item in a_list:
if has_run:
break
has_run = True # Set flag variable to True
print(item) # Output: tutorial

  • The loop runs once setting has_run to True. The if statement will then break the loop in the following iteration.