-3

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.

Grimxn
  • 22,115
  • 10
  • 72
  • 85
Sokonit Skr
  • 83
  • 1
  • 1
  • 3

3 Answers3

2

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:

https://docs.python.org/2/tutorial/controlflow.html

Community
  • 1
  • 1
en_Knight
  • 5,301
  • 2
  • 26
  • 46
1

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"
eLemEnt
  • 1,741
  • 14
  • 21
  • `num1` and `num2` will always exist as they are part of the function definition. –  Mar 02 '15 at 05:54
1

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.

Marcin
  • 215,873
  • 14
  • 235
  • 294
  • `num1` and `num2` will always exist as they are part of the function definition. –  Mar 02 '15 at 05:54
  • I think num1 would be a string containing variable name to look for. Otherwise you are correct. – Marcin Mar 02 '15 at 05:55