Q1What does the following code print?def f(x, y=10):
return x + y
print(f(3))
Defining Functions with def — Arguments, Return Values, Default and Keyword Arguments
Define your own Python functions with def and return, then call them with default and keyword arguments — every example runs in your browser.
When the same logic needs to run many times, you want a way to give that logic a name and call it from wherever you need it. That mechanism is a function, defined with the def keyword.
With functions, shared logic lives in one place and each call site is a single line. Everything you've used so far — print() / len() / int() / sum() — is a function too.
The basics of def and return
Define a function with def function_name(arguments): and indent the body. Return a value to the caller with return value. A function without return effectively returns None.
The argument is what the caller hands to the function, and the return value is what the function sends back via return. Because the same function can be called with different arguments for different results, a single definition can power many call sites.
A function created with def isn't executed by being registered in the namespace. The body only runs when a call like greet("Alice") happens — and the value of return flows back to the caller.
# No arguments, no return value
def print_hello():
print("Hello World")
print_hello() # Hello World
# Two arguments, one return value
def max_num(a, b):
if a >= b:
return a
return b
result = max_num(30, 20)
print(result) # 30
# return exits the function; anything after it doesn't run
def check(x):
if x < 0:
return "negative"
return "non-negative"
print(check(-5)) # negative
Default arguments and keyword arguments
Adding = value to an argument sets a default used when the caller omits it (a default argument).
On the calling side, argument_name=value lets you pass values by name regardless of position (keyword arguments). Default arguments are conventionally placed at the end of the argument list so order doesn't matter.
# Give greeting a default value
def greet(name, greeting="Hello"):
return f"{greeting}, {name}"
print(greet("Alice")) # Hello, Alice
print(greet("Bob", "Good morning")) # Good morning, Bob
print(greet(greeting="Good evening", name="Carol")) # keyword args can be reordered
# Output: Good evening, Carol
In this article you learned function definitions with def, return values with return, and default and keyword arguments. When you use functions fluently, the same logic can be invoked from anywhere as many times as you want, and code readability improves substantially.
Knowledge Check
Answer each question one by one.
Q2Which call is using keyword arguments?def greet(name, greeting="Hi"):
return f"{greeting}, {name}"
Q3What does the following code produce?def g(x):
x + 1 # no return
result = g(10)
print(result)