how do I declare a null value in python?

In writing about this question, it is important to understand a few things , before we step into the code.

Null values appear in almost every programming language, but they can have a different meaning.

A null value basically means it is empty. So when you return a value that is null, it has nothing in it.

Sometimes it can be confused with the value zero, but as zero is an actual integer, it is not an empty value in a field.

Python uses None to define the keyword null, that returns an empty value.

How can we show null in an output?

Lets look at the below output. From observation it can be seen that a,b,d retuns an int value, but that is quite straight forward.

Let’s focus on c. When it is printed out the value on the screen is showing nothing, and its data type is str. But why is that, surely it is None or empty as we were expecting?

Well Python will return as a string , unless it is explicitly declared as empty. The next section will take you through that.

a = 1
b = 1
c = ""
d = a-b
print(a)
print(b)
print(c)
print(d)
print(type(a))
print(type(b))
print(type(c))
print(type(d))

Returns:
1
1

0
<class 'int'>
<class 'int'>
<class 'str'>
<class 'int'>

So based on the above, how do I declare a null value in python?

We have modified the code above, and declared c as None, and in this instance the code now recognises the output as empty.

a = 1
b = 1
c = None
d = a-b
print(a)
print(b)
print(c)
print(d)
print(type(a))
print(type(b))
print(type(c))
print(type(d))

Result:
1
1
None
0
<class 'int'>
<class 'int'>
<class 'NoneType'>
<class 'int'>

What are the other scenarios that None will be returned?

Python also returns values on None, even though they have not been explicitly declared.

In the below if you try to print nothing, it will by default return an empty value.

On the other hand using an if statement you can check if a value is a None.

The final example is where you are using a function, to check if a value is in a list. If the value does not appear in the list it returns nothing.

This is especially handy , if you want to completely sure that that the returned values are nothing.

It gives you a level of comfort that that the code will not pass anything to other parts of the programme.

a = print()
print(a)

variable = None

if variable is None:
    print("Correct")
else:
    print("Incorrect")

variable1 = "today"
if variable1 is None:
    print("Correct")
else:
    print("Incorrect")


def returnnone():
    list = [1,2,3,4,5]
    for i in list:
        if i == 6:
            print("Six found")
        else:
            print(None)
            
returnnone()

Result:
None
Correct
Incorrect
None
None
None
None
None

Click here to get more information on other relevant data analytics posts.

raise an exception in python

Estimated reading time: 5 minutes

In a computer programme, there is a lot of different moving parts, that the programmer has created themselves.

And depending on the sophistication of the code written exceptions can occur, usually no one has an understanding of what they mean!

So we have established problems can occur, what next?

As part of the process of building out the logic , knowledge will lie with the computer programmer.

In this case the errors that they know about and programme for, may not always be understood by everyone.

If the computer programme does not explain them correctly, frequently it can lead to long hours trying to figure out the problem.

This is usually because the error message they code to explain the problem, may not always be designed with ease of understandability.

It must be remembered:

  • Not all errors may be known when the programme was developed.
  • Some error messages can be generated automatically, not on the request of the programmer.

Step into the frame, the ability to create your own error messages with understandable explanations.

Good programmers have a lot of traits that makes what they develop so powerful.

Surprisingly it is the simple things can be missed, but based on time and budget, generic error messages may be needed, certainly not ideal though.

With that in mind lets look at the following code:

def checkvalue():
    try:
        integervalues = input("Type something to test this out: ")
        if integervalue != "55" and integervalue.isdecimal():
            raise ValueError
        elif integervalue.isalpha():
            raise TypeError
        else:
            print("55 entered correctly")
    except ValueError:
        raise ValueError("Integervalue needs to be fifty five")
    except TypeError:
        raise TypeError("Number needs to be entered")
    finally:
        print("All checks completed")


checkvalue()
It returns:
NameError: name 'integervalue' is not defined

The problem is that the variable used has a misspelling.

Luckily we can easily see that the variable “integervalue” is misspelt with an extra “s”, however removing that will fix the issue.

In the light of that say we took the above code, without the try and except:

from distlib.compat import raw_input
def checkvalue():
    integervalue =raw_input("Type something to test this out: ")

    if integervalue == int(55):
        print("success")
    else:
        print("integervalue needs to be a fifty five")


checkvalue()
It returns:
Type something to test this out: aa
integervalue needs to be a fifty five

In essence, both do the same thing, above all the first piece of code allows for better customization.

This allows us to test for specific types of errors, resulting in more specific error trapping like:

  • Value Error
  • Type Error

The above two are just examples you can use for built in exceptions coded to trap errors.

But what if we want to create our own exception list?

The simple way around this is to build your own class that has the errors you need to capture.

Then you reference that class in the try/except and bingo, there you have it.

In order to achieve this, the first step is to build classes with the errors you want to catch:

class ValueTooSmall(Exception):
    """Raised when the input value is too small"""
    pass
class ValueLength(Exception):
    """Raised when the value entered is empty"""
    pass
class ValueAlphabetic(Exception):
    """Raised when the value is alphabetic"""
    pass

Then create a function that will hold all the try except logic to check for the errors

try:
        integervalue = input("Type something to test this out: ") # Creates a string here
        if len(integervalue) == 0:
            raise ValueLength
        elif integervalue.isalpha():
            raise ValueAlphabetic
        elif int(integervalue) != 55 and int(integervalue) < 10: # converting to integer to allow comparison
            raise ValueTooSmall
        elif int(integervalue) != 55 and int(integervalue) > 10: # converting to integer to allow comparison
            raise ValueError
        else:
            print("55 entered correctly")
    except ValueError:
        raise ValueError("Integervalue needs to be fifty five")
    except TypeError:
        raise TypeError("Number needs to be entered")
    except ValueTooSmall:
        raise ValueTooSmall("Number needs to be greater than 10")
    except ValueLength:
        raise ValueLength("Number needs to be entered, can't be empty")
    except ValueAlphabetic:
        raise ValueAlphabetic("You cannot enter an alphabetic value")
    finally:

Putting it all together

class ValueTooSmall(Exception):
    """Raised when the input value is too small"""
    pass
class ValueLength(Exception):
    """Raised when the value entered is empty"""
    pass
class ValueAlphabetic(Exception):
    """Raised when the value is alphabetic"""
    pass

def checkvalue():
    try:
        integervalue = input("Type something to test this out: ") # Creates a string here
        if len(integervalue) == 0:
            raise ValueLength
        elif integervalue.isalpha():
            raise ValueAlphabetic
        elif int(integervalue) != 55 and int(integervalue) < 10: # converting to integer to allow comparison
            raise ValueTooSmall
        elif int(integervalue) != 55 and int(integervalue) > 10: # converting to integer to allow comparison
            raise ValueError
        else:
            print("55 entered correctly")
    except ValueError:
        raise ValueError("Integervalue needs to be fifty five")
    except TypeError:
        raise TypeError("Number needs to be entered")
    except ValueTooSmall:
        raise ValueTooSmall("Number needs to be greater than 10")
    except ValueLength:
        raise ValueLength("Number needs to be entered, can't be empty")
    except ValueAlphabetic:
        raise ValueAlphabetic("You cannot enter an alphabetic value")
    finally:
        print("All checks completed")


checkvalue()

You will notice that the Classes we created are referenced within the code to call the exact exception we are looking to capture.

For this reason what are the benefits of approaching it this way:

  • You can capture exceptions tailored to the code you are writing.
  • Controls can easily be created and implemented so that specific errors with your data can be flagged straight away.
  • If you are going to be looking to catch the same exceptions in numerous places, this methodology will help to implement a better structure to handle those.
  • You can start to build a centralised repository of centralized exceptions and how to handle them.
  • All contributors to your project know how to raise an exception in python , you do not get multiple different v.

On our YouTube channel you can subscribe to find out more information about exceptions, and lots of tips and tricks for better Data Analytics.