Learn by reading through in order

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.

Functions, arguments, and return values
argument(input)function(body)return value(output)pass inreturn

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.

Defining and calling a function
defineexecutedef greet(name): return ...greet("Alice")run the bodyreturn valueflows backname: Alicereturn ...

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

Write a function that applies a discount rate.

① Define def apply_discount(price, rate): and return price * (1 - rate).

② Put apply_discount(1000, 0.2) into sale_price and print it with print(f"Sale price: {sale_price}").

③ Call apply_discount(500, 0.1) directly inside print() to confirm the same function can be reused with different values.

(The explanation appears once the code runs correctly.)

Python Editor

Run code to see output

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.

Three call patterns and how parameters get filled
def greet(name, greeting="Hello"):① greet("Alice")name="Alice"greeting="Hello"(default applied)greet(name="Alice"greeting="Hello")② greet("Bob", "Good morning")name="Bob"greeting="Good morning"(positional override)greet(name="Bob"greeting="Good morning")③ greet(greeting="Good evening", name="Carol")name="Carol"greeting="Good evening"(order can be swapped)greet(name="Carol"greeting="Good evening")omitpositionalkeywordrunrunrun
# 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

Write a function that formats user info.

① Define def format_user(name, role="member"): and return f"{name} ({role})".

② Print format_user("alice") (role omitted).

③ Also print format_user("bob", "admin") (positional) and format_user(role="owner", name="carol") (keyword).

Python Editor

Run code to see output

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.

QUIZ

Knowledge Check

Answer each question one by one.

Q1What does the following code print?
def f(x, y=10):
return x + y

print(f(3))

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)