functions¶
- In Python, functions are reusable blocks of code that perform a specific task.
- They promote code modularity, readability, and maintainability by encapsulating logic into well-defined units.
- The
def
keyword is used to define a function. - Function Arguments
- Functions can accept zero or more arguments (inputs) that provide data to the function.
- Arguments are defined within the parentheses after the function name in the definition.
- When calling the function, you pass the actual values (arguments) you want to use within parentheses.
- Return Values
- Functions can optionally return a value using the
return
statement. The returned value becomes the output of the function call. - If no
return
statement is present, the function implicitly returnsNone
.
- Functions can optionally return a value using the
- Using Functions Effectively
- Break down complex problems into smaller, well-defined functions.
- Give functions descriptive names that reflect their purpose.
- Use docstrings to explain what the function does and how to use it.
- Consider using default arguments to provide optional parameter values.
- Key Points
- Functions improve code reusability by allowing you to write a block of code once and call it multiple times with different inputs.
- Arguments provide flexibility in how you use a function.
- Return values enable functions to provide data back to the calling code.
- Docstrings enhance code readability and understanding.
In [ ]:
Copied!
def greet(name):
"""This function greets a person by name."""
print(f"Hello, {name}!")
# Call the function with different names
greet("chaitu-ycr")
greet("Bob")
greet("Charlie")
def greet(name):
"""This function greets a person by name."""
print(f"Hello, {name}!")
# Call the function with different names
greet("chaitu-ycr")
greet("Bob")
greet("Charlie")
def greet(name):
: This line defines the function namedgreet
. The parameter name specifies that the function expects a value to be passed when it's called."""This function greets a person by name."""
: This is a docstring, an optional line that provides a brief description of the function's purpose. It improves code readability and understanding.print(f"Hello, {name}!")
: This indented code block defines the function's body. The code within this block executes when the function is called.greet("chaitu-ycr")
,greet("Bob")
, etc.: These lines call thegreet
function with different arguments ("chaitu-ycr", "Bob", etc.) for thename
parameter.
In [ ]:
Copied!
def add(x, y):
"""This function adds two numbers."""
return x + y
result = add(5, 3) # result will be 8
print(result)
def add(x, y):
"""This function adds two numbers."""
return x + y
result = add(5, 3) # result will be 8
print(result)