Skip to Content

How to tell Python to do nothing

How to tell Python to do nothing

In this post, we will see how to tell Python to do nothing. Python does not allow empty code at many places, for example, in loops, if conditions, and functions, etc.

Often, we do not want to execute any code statements there or will do in the future. To be able to do that, Python provides us the pass statement.

A pass statement is a null operation, which means that when we use it, nothing happens.

Let’s take an example.

 

def calculateOddSum(values):
  sum = 0
  for val in values:
    if val%2 == 0:
      pass
    else:
      sum += val
  
  return sum

values = [1, 2, 5, 4, 7, 8, 10, 9, 12, 13, 15, 17]
sum = calculateOddSum(values)
print("The sum of odd numbers in the list is:", sum)

 

Output

 

The sum of odd numbers in the list is: 67

 

In the above example, we have a function calculateOddSum(), which calculates the sum of odd values. It takes a list and iterates over it.

If a number is even, it does nothing by using the pass statement. Otherwise, it adds it to the sum variable. Finally, we return that sum. 

Let’s take the above example, where we do nothing when a number is even. Now, we want to have a function that will take this value and perform some calculations.

Its logic will be implemented later. So, for now, we want to have a function that does not do anything. Here, we can use the pass statement. Let’s see.

 

def evenNumber(even):
  pass

def calculateOddSum(values):
  sum = 0
  for val in values:
    if val%2 == 0:
      evenNumber(val)
    else:
      sum += val
  
  return sum

values = [1, 2, 5, 4, 7, 8, 10, 9, 12, 13, 15, 17]
sum = calculateOddSum(values)
print("The sum of odd numbers in the list is:", sum)

 

Consider the following code, where we create a class and ask Python to do nothing.

 

class A:
  pass

a = A()
print(a)

 

<__main__.A object at 0x7fdd45fd8588>

 

A class has been created, but it doesn’t contain any methods or attributes.