Understanding Functions in Python
Functions allow you to organize code into reusable blocks. In this article, you’ll learn how to define functions in Python, use parameters, apply type hints, and handle return values. Whether you’re a beginner or transitioning from Mojo, this guide will give you a strong foundation.
Basic Function Syntax
A basic Python function uses the def
keyword followed by the function name and parameters:
def greet(name):
return "Hello, " + name
This function takes a single argument name
and returns a greeting string.
Multiple Parameters
Functions can accept multiple parameters, separated by commas:
def add(a, b):
return a + b
You can call this function like add(2, 3)
and get the result 5
.
Default Parameter Values
Python supports default values for optional parameters:
def greet(name="World"):
return "Hello, " + name
greet()
will return "Hello, World"
.
Using Type Hints
Python allows you to optionally add type hints to improve code readability and catch type-related bugs:
def add(a: int, b: int) -> int:
return a + b
These hints do not enforce types at runtime but help with static analysis tools like mypy
.
Return Values
A function can return any data type. If no return
statement is used, it returns None
by default.
def log_message(msg: str) -> None:
print(msg)
Anonymous Functions (Lambda)
Python supports simple one-line anonymous functions using lambda
:
square = lambda x: x * x
print(square(4)) # Outputs: 16
Summary
- Define functions using
def
keyword - Use parameters with or without default values
- Type hints improve clarity but are optional
- Return values can be of any type, including
None
In the next article, we’ll compare Python and Mojo side-by-side to highlight key syntax differences.
Comment