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)
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.
Hey guys! It’s me, Marcel, aka Maschi. I earn a full-time income online and on MaschiTuts I gladly share with you guys how I stay on top of the game! I run several highly profitable blogs & websites and love to speak about these project whenever I get a chance to do so. I do this full-time and wholeheartedly. In fact, the moment I stopped working an 8-to-5 job and finally got into online business as a digital entrepreneur, is problably one of the best decisions I ever took in my life. And I would like to make sure that YOU can get on this path as well! Don’t let anyone tell you that this can’t be done. Sky’s the limit, really…as long as you BELIEVE in it! And it all starts right here..at Maschituts!