Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if there is a missing argument

Tags:

python

I wrote this code:

def suma(num1,num2):

    if(isinstance(num1,int)) or (isinstance(num2,int)) :
       if num1<0 or num2<0:
            print("iavo")
       elif num1!=int(num1)or num2!=int(num2):
            print("iao")
       else:
            suma_a = num1+num2
            return suma_a
    else:
        print("ia")

I need to check whether there is a num1 or num2. If there is none, the program should print that there is a missing argument.

like image 462
Sokonit Skr Avatar asked Mar 02 '15 02:03

Sokonit Skr


2 Answers

If you do not assign default values and a user did not supply two args you would get a TypeError: suma() missing 1 required positional argument before you got into the function at all:

def suma(num1=None,num2=None):
     # make sure user has entered two args and both are numbers
    if num1 is None or num2 is None:
        return "You Must choose two numbers"
    # rest of code
like image 185
Padraic Cunningham Avatar answered Sep 22 '22 18:09

Padraic Cunningham


That function will throw an error if you don't send both numbers. There is no way to leave out an argument in your function.

If you did i.e. something like:

def summ(a, b=None):
    return a+b

then you could leave out b, however this will throw an unsupported operand error again because you can't add a number and None.

You can check if you have all numbers present if you're calling that function in the scope of some other function, or in a class, you can wrap it in a try except block and try to handle the error like shown in the dumbest example possible:

try: 
    summ(1)
except: 
    print("Missing arguments, you can't add numbers and None in Python!"\
          " Please send b.")
like image 30
ljetibo Avatar answered Sep 20 '22 18:09

ljetibo