A function in Python is a block of reusable code that performs a specific task. Functions help you:
def keyword: Used to define a function.return: Sends a value back from the function to the caller.Basic syntax of a user-defined function in Python:
def function_name(parameters):
# function body
# write your logic here
return value # optional
# calling the function
function_name(arguments)
Indentation is very important in Python. The code inside the function must be indented at the same level, usually 4 spaces.
This function prints a greeting message. It has no parameters and no return value.
def greet():
print("Hello, World!")
greet() # Call the function
This version of greet() takes a name parameter so it can greet different people.
# define a function that greets a person by name
def greet(name):
print(f"Hello, {name}!") # print a personalized greeting
# call the function with different names
greet("Alice")
greet("Bob")
This function adds two numbers and returns the result instead of printing it directly.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
greet() function:
Hello, World!
greet("Alice") and greet("Bob"):
Hello, Alice! Hello, Bob!
add(5, 3) call:
8
When you call a function, Python jumps to the function body, executes it, and then comes back to the line after the call. If the function uses return, the returned value can be stored in a variable or used in an expression.
return to get results from a function instead of printing inside it.