Home > Back-end >  How to set an argument in a function to False unless the user specifies otherwise?
How to set an argument in a function to False unless the user specifies otherwise?

Time:04-09

I have a function which contains two arguments. It doesn't really matter what the function does for it self. What it's important that when calling the function I want to set the second argument to a default boolean False value.

So let's supose that if the second argument it's False or not specified True it will print a different line than when it's True in the function call.

Here's the thing. I want that the second argument it's set to False by default even though when the user specifies it as False when calling the function and so, this will be only True when the user specifies it.

Example:

def example(stringy, printable):
    if printable == True:
        print(stringy, "Printable is set to True")
    else:
        print(stringy, "Printable is set to False")

example("A")

The thing is that if I call the function only as example("Hello World"), I will get

Traceback (most recent call last) line 7, in <module>
    example("A")
TypeError: example() missing 1 required positional argument: 'printable'

So is there a way to make printable set to False by default unless the user changes it when calling the function?

CodePudding user response:

In python, what you want involves using a keyword argument; these always take a default value. The syntax is almost identical to what you already have:

def example(stringy, printable=False):
    if printable == True:
        print(stringy, "Printable is set to True")
    else:
        print(stringy, "Printable is set to False")

The function can then be called any of these ways, with the same result:

example("A")
example("A", False)
example("A", printable=False)

CodePudding user response:

You have only to set the argument with a variable inside the def.

def example(stringy, printable = False):
if printable == True:
    print(stringy, "Printable is set to True")
else:
    print(stringy, "Printable is set to False")

This will make printable set to False by default unless the user changes it when calling it

example("A")
    A Printable is set to False

example("A", True)
    A Printable is set to True
  • Related