Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials Python Functions
Python Beginner FREE

Functions

Lesson 1 of 14 Beginner Interactive

Functions are defined with def. They accept parameters, return values, and support defaults.

*args & **kwargs

*args for variable positional args; **kwargs for keyword args.

Scope

Local vs global variables. Use global keyword to modify globals.

Syntax

PYTHON
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

def total(*args, **kwargs):
    return sum(args)

print(greet("Alice"))
print(total(1, 2, 3))
Python Functions
PYTHON
def greet(name):
    return f"Hello, {name}!"

def power(base, exp=2):
    return base ** exp

def add(a, b):
    return a + b

# *args and **kwargs
def log(*args, **kwargs):
    print("args:", args)
    print("kwargs:", kwargs)

print(greet("Alice"))
print(power(3))
print(power(2, 10))
print(add(5, 3))

log(1, 2, name="Alice", age=25)

# Lambda as argument
nums = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, nums))
print("Evens:", evens)

Practice

1
Exercise

Write factorial function.

Answer
def factorial(n):
    return 1 if n<=1 else n*factorial(n-1)

Quick Quiz

1

What does **kwargs collect?

Collects keyword arguments into a dictionary.

Interview Questions

Functions can be assigned to variables, passed as args, returned from other functions.