How to create a function with an optional parameter in Python

6 Answers

0 votes
def function(lang="python"):
    print(lang)

function("java")
function()



'''
run:

java
python

'''

 



answered Dec 14, 2017 by avibootz
edited 5 hours ago by avibootz
0 votes
def my_function(x, optional_value=10):
    print("x =", x)
    print("optional_value =", optional_value)


my_function(5)
my_function(5, 99)



'''
run:

x = 5
optional_value = 10
x = 5
optional_value = 99

'''

 



answered 5 hours ago by avibootz
0 votes
' Optional parameter with a default value

def greet(name, greeting="Hello"):
    print(greeting, name)

greet("R2D2")             
greet("R2D2", "Welcome")   



'''
run:

Hello R2D2
Welcome R2D2

'''

 



answered 5 hours ago by avibootz
0 votes
# Optional parameter using None as a sentinel
# This is useful when the default value must be computed inside the function.

def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items


print(add_item("apple"))          
print(add_item("banana"))         
print(add_item("strawberry", ["x"]))  



'''
run:

['apple']
['banana']
['x', 'strawberry']

'''

 



answered 5 hours ago by avibootz
0 votes
# Optional keyword‑only parameters

def draw(x, y, *, color="red"):
    print(f"Drawing at ({x}, {y}) in {color}")

draw(10, 20)               
draw(10, 20, color="blue") 



'''
run:

Drawing at (10, 20) in red
Drawing at (10, 20) in blue

'''

 



answered 5 hours ago by avibootz
0 votes
# Optional variable‑length arguments

def total(*numbers):
    return sum(numbers)

print(total())    
print(total(1, 2, 3))


'''
run:

0
6

'''

 



answered 5 hours ago by avibootz
...