Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print the default value if argument is None in python

Tags:

python

[sample.py]

def f(name='Hello Guest'):
    print(name)


def A(name=None):    
    f(name)

A()

Expected Output: 'Hello Guest'

Current Output: None

I'm expecting the answers by without using much more codes like 'name = name if name is not None else some_default_value'

Thanks in advance!

like image 374
Jai K Avatar asked Jan 18 '19 06:01

Jai K


People also ask

How do you pass a default argument in Python?

Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.

What is default argument in Python with example?

Python Default Arguments Here is an example. def greet(name, msg="Good morning!"): """ This function greets to the person with the provided message. If the message is not provided, it defaults to "Good morning!" """ print("Hello", name + ', ' + msg) greet("Kate") greet("Bruce", "How do you do?")

What is default and non default argument Python?

The Python "SyntaxError: non-default argument follows default argument" occurs when we define a function with a positional parameter that follows a default parameter. To solve the error, make sure to specify all default parameters after the positional parameters of the function.

What is default parameters in Python?

Default arguments in Python functions are those arguments that take default values if no explicit values are passed to these arguments from the function call. Let's define a function with one default argument. def find_square(integer1=2): result = integer1 * integer1 return result.


2 Answers

Does this work for you?

def f(name):
    print(name or 'Hello Guest')

def A(name=None):    
    f(name)

A()
Out: "Hello Guest"

A("Hello World")
Out: "Hello World"

If the name variable is being used multiple times in the function, you could just reassign it in the beginning of the function. name = name or "Hello Guest"

like image 193
najeem Avatar answered Oct 21 '22 23:10

najeem


The best way to do this will be to use a shared default:

DEFAULT_NAME = "Hello Guest"

def f(name=DEFAULT_NAME):
    print(name)

def A(name=DEFAULT_NAME):
    f(name)
like image 23
wim Avatar answered Oct 21 '22 23:10

wim