How to check arguments passed to the function call are empty?

时间:2018-02-03 10:21:55

标签: python python-3.x function

I want the function to simply check if an argument is passed or not. If not, print something, else say some hello and that argument.

Here is sample of my code:

def say_name(name):
  if name is None:
    print("Hello there")
  else:
    print("Hello, "+ name + "!")

run code:

class Test(unittest.TestCase):
  def test_should_say_hello(self):
    self.assertEqual(say_name("Michael"), "Hello, Michael!")

I have tried using None, Kwargs and still not working. How can I check whether argument is passed to the function?

2 个答案:

答案 0 :(得分:3)

To make a parameter optional assign it a default value:

def say_name(name=None):
    if name is None:
        print("Hello there")
    else:
        print("Hello, "+ name + "!")

Addendum: As Barmar pointed out in the comments to your question, your function needs to return a string to make your check work.

def say_name(name=None):
    if name is None:
        return "Hello there"
    else:
        return "Hello, "+ name + "!"

答案 1 :(得分:0)

To check whether "any" of the argument is passed with the function call

In general, in order to check whether any argument is passed or not, you may create your function using *args (for non-keyworded variable length argument list) and **kwargs (for keyworded variable length argument list). For example:

def check_argument(*args, **kwargs):
    if args or kwargs:   # check if any among the `args` or `kwargs` is present
        return "Argument Passed!"
    else:
        return "Argument Not passed!"

Sample Run:

# For "non-keyworded" argument
>>> check_argument('something')
'Argument Passed!'

# For "keyworded" argument
>>> check_argument(some_param='some_value')
'Argument Passed!'

# For no argumenet    
>>> check_argument()
'Argument Not passed!'

To check if any "specific" argument is passed with the function call

For your scenario, since you only care about one specific parameter name and perform operation based on the value passed, you may assign a default value to it's function definition as:

#                  v Default value as `None`
def say_name(name=None):
    if name is None:
        return "Hello, there!"
    else:
        return "Hello, "+ name + "!"

Above function could be simplified as:

#                    v setting default name as "there"
def say_name(name="there"):
    return "Hello, {}!".format(name)

# Or you may also check it within the format as
def say_name(name=None):
    return "Hello, {}!".format(name or "there")

Sample Run:

>>> say_name()
Hello, there!
>>> say_name('StackOverflow')
Hello, StackOverflow!