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.
With that said, to get rid of None in Python, 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()
Output
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)
Output
Result is 19
Hey guys! It’s me, Marcel, aka Maschi. On MaschiTuts, it’s all about tutorials! No matter the topic of the article, the goal always remains the same: Providing you guys with the most in-depth and helpful tutorials!