If your function is written in plpgsql you should learn here about
control structures
If you preferred to use SQL then read about
conditional expressions
You may also be interested in using a
sequence
This way you'll never have to worry about checking for NULL or incrementing value.
What is also important sequence will provide safety, otherwise you may need to lock the table to prevent two processes intervening with each other in the process of checking/incrementing the value.