What is a Function?
A function is a block of reusable code that performs a specific task. Functions help in code reusability, organization, and readability.
Defining a Function
Functions in Python are defined using the def keyword.
Example: Creating a Simple Function
def greet():
print("Hello, welcome to Python!")
Calling a Function
Once defined, a function is executed when it is called.
Example: Calling a Function
greet()
Function Parameters and Arguments
Functions can accept parameters to pass values.
Example: Function with Parameters
def greet(name):
print("Hello, " + name + "!")
greet("Alice")
Return Statement
Functions can return values using the return keyword.
Example: Function with Return Value
def add(a, b):
return a + b
result = add(3, 5)
print(result)
Default Parameter Values
If a function parameter has a default value, it can be omitted when calling the function.
Example: Function with Default Parameters
def greet(name="Guest"):
print("Hello, " + name + "!")
greet()
greet("Alice")
Key Takeaways
- Functions make code reusable and modular.
- Functions can have parameters and return values.
- Default parameters allow flexibility in function calls.