In this post, we will see how to get rid of None in Python.
Consider the following example.
def test(): a = 4 b = 5 c = 10 result = a + b + c print("Result is", result) print(test())
Result is 19 None
In the above example, all the code is working fine, except we get None in the output. It might seem unexpected, but it is not.
The thing is, in Python, every function has a return value. Therefore, if you do not explicitly return anything, None will get returned by default.
In the above code, we are printing the return value of test(). Since it returns None, it gets displayed in the output.
To solve this problem, we can do two things. First, we can remove the print() function. In this way, we won’t print something unwanted. Let’s see.
def test(): a = 4 b = 5 c = 10 result = a + b + c print("Result is", result) test()
Result is 19
Second, instead of displaying the result in the test() function, we can return it. We can print it after the function returns. This can also be useful if the returned value is required later. Let’s see.
def test(): a = 4 b = 5 c = 10 result = a + b + c return result result = test() print("Result is", result)
Result is 19
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!