Functions

Functions

Functions are defined with def. They can take arguments and return a value.

Basic function

python
def greet(name): print(f\"Hello, {name}\") greet(\"Alice\")

Return value

python
def add(a, b): return a + b total = add(3, 5) # 8

Without return, the function returns None.

Default arguments

python
def greet(name, greeting=\"Hello\"): return f\"{greeting}, {name}\" greet(\"Bob\") # Hello, Bob greet(\"Bob\", \"Hi\") # Hi, Bob

Keyword arguments

You can call by name:

python
def describe(name, age, city): return f\"{name}, {age}, from {city}\" describe(age=25, city=\"NYC\", name=\"Alice\")

*args and **kwargs

  • *args – variable positional arguments (tuple).
  • **kwargs – variable keyword arguments (dict).

Used when you need flexible signatures or to pass through arguments.