1. Defining Functions
A function in Python is a block of reusable code that performs a specific
task. You define a function using the def keyword.
Syntax:
def function_name(parameters):
# Code to execute
return result # Optional, used to return a value from the function
Example:
def greet():
print("Hello, World!")
greet() # Calling the function
Output:
Hello, World!
In this example:
def is the keyword used to define a function.
greet is the function name.
The parentheses () are used for parameters (in this case, there are none).
The print statement is the code that runs when the function is called.
, 2. Function Parameters
Functions can take parameters (also called arguments) that allow you to
pass data into the function.
Syntax:
def function_name(parameter1, parameter2):
# Code that uses the parameters
return result
Example:
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result) # Output: 8
In this case:
a and b are parameters.
The function returns the sum of a and b.
3. Default Parameters
You can set default values for parameters in case no value is passed during
the function call.
Syntax:
def greet(name="Guest"):
print(f"Hello, {name}!")
Example: