Say:
def sumer(num1,num2)
if num1 or num2 is a non-defined variable
print("variable isnt defined")
how can I write that in a way taht actually works?
Edit: I should clarify that I want python to carry on an action if it is defined.
Say:
def sumer(num1,num2)
if num1 or num2 is a non-defined variable
print("variable isnt defined")
how can I write that in a way taht actually works?
Edit: I should clarify that I want python to carry on an action if it is defined.
In the example you gave
def foo( var1 = None, var2 = None ):
if var1 is not None: ...
if var2 is not None: ...
Note that they will always be defined, as written, because they are in the function signature. What you want to check is if they were supplied, which is what the above code does.
In the above example I've used "is" instead of "==". This is a preference (String comparison in Python: is vs. ==) here, but I like it since "==" could throw an exception, say with a numpy array
Checking off-hand if a variable name has been used is very weird practice, but could be done by using locals() and globals(), as given in other answers. More pythonic would be to duck-type and cover your tracks with exceptions. This is often the way to go if you don't want to explicitly check if the argument was passed.
Yet another way is to use **kwargs, or variable length keyword arguments. Consider:
def foo( **kwargs ):
if 'my_variable_name' in kwargs.keys(): ...
would accomplish the task too.
Reading the python page on control flow might be a good starting reference place:
inside your function try to check if it exists
try:
num1
except NameError:
print "num1 does not exists"
else:
print "num1 exists"
try:
num2
except NameError:
print "num2 does not exists"
else:
print "num2 exists"
En alternative way not relying on exceptions:
if num1 in locals() or num1 in globals():
print('Exists')
Assuming that num1 is a string variable containing name to look for.