How can i define a function with a output if *Args* is empty or not given

Question:

my intention:

I want to define a function, but if the Args of the function is empty → should print something

what i did:

def test(name):    
       if name == None:
          return print("The Args is empty")    
       else:
          return print('The Args is ', name, ', and TNX.')

What i want:

test():

The output should be →

The Args is empty

where is my fault?

Asked By: Jsmoka

||

Answers:

When you defined the argument for test, you should provide a default value for that said argument ..

def test(name = None): ...
Answered By: rasjani

In your if statement you are checking if the argument ‘name’ is equal to None. However, when the argument is not passed in, it will be assigned the default value of None. Instead, you should check if the variable is not defined using the keyword "not" or check if the variable is empty by checking its length

def test(name):    
    if not name or len(name) == 0:
        return print("The Args is empty")    
    else:
        return print('The Args is ', name, ', and TNX.')
Answered By: Razvan I.

You could use an arbitrary argument list, see https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists and check its length, e.g.

def test(*args):
    # check if args are provided
    if not args:
        print("The Args is empty")
    # unpack arguments manually and raise error if too many are given
    name, = args
    print(f'The Args is {name} and TNX.')
Answered By: Carlos Horn
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.