codegurukool.com · Free coding tutorials & online compiler

Home › Python Tutorial › Python functions

Python functions

Reusable blocks of code.

Define a function with def. Parameters can have defaults, be passed by name, or collect extra values with *args. A lambda is a small one-line function.

Example code

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

print(greet("Ada"))
print(greet("Bob", greeting="Hi"))
square = lambda n: n * n
print(square(5))

def total(*nums):
    return sum(nums)
print(total(1, 2, 3))

Run this code in the online editor

← Python for and while loopsPython modules, dates and math →