Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 635
mukolweke Avatar asked Dec 03 '25 09:12

mukolweke


1 Answers

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 + "!"
like image 84
Ansgar Wiechers Avatar answered Dec 04 '25 21:12

Ansgar Wiechers