Skip to Content

How to get rid of None in Python

How to get rid of None in Python

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()

 

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

 

 

How To Add a Drop Shadow in Canva Updated
Previous
How to Add a Drop Shadow (to your Text/Elements) in Canva
How to tell Python to do nothing
Next
How to tell Python to do nothing