A function in Python is a reusable block of code that performs a specific task. Instead of repeating code, you can put it inside a function and call it whenever you need.
You define a function in Python using the def keyword:
def greet():
print("Hello, welcome to Python!")
def → keyword to define a function
greet → function name
() → parentheses for parameters (if any)
: → start of the function block
print(...) → function body
Calling the function:
greet()
Output:
Hello, welcome to Python!
Function with Parameters
You can pass data into a function using parameters.
def greet_user(name):
print(f"Hello, {name}!")
Call it:
greet_user("Anna")
greet_user("John")
Output:
Hello, Anna!
Hello, John!
Function with Return Value
Functions can return data using the return keyword.
def add(a, b):
return a + b
result = add(5, 7)
print(result) # 12
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
You define a function in Python using the
defkeyword:def→ keyword to define a functiongreet→ function name()→ parentheses for parameters (if any):→ start of the function blockprint(...)→ function bodyCalling the function:
Output:
Function with Parameters
You can pass data into a function using parameters.
Call it:
Output:
Function with Return Value
Functions can return data using the
returnkeyword.Default Parameters
If no value is given, default values are used.
Multiple Return Values
A function can return multiple values (as a tuple).
Keyword Arguments
You can pass arguments in any order by naming them.
Output:
Variable Number of Arguments
*args→ allows multiple positional arguments**kwargs→ allows multiple keyword argumentsLambda Functions (Anonymous Functions)
Short functions written in one line using
lambda.