What You Will Learn
Beginner
- How to define and call functions
- Parameters and return values
- Docstrings for documentation
Terminalpython
# Basic function
def greet(name):
return f"Hello, {name}!"
# Call the function
message = greet("Anita")
print(message) # Hello, Anita!
# Function with multiple parameters
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
# Function with no return (returns None)
def print_greeting(name):
print(f"Hi, {name}!")
result = print_greeting("Ravi") # Prints: Hi, Ravi!
print(result) # NoneDocstrings
Terminalpython
def calculate_area(length, width):
"""Calculate the area of a rectangle.
Args:
length: The length of the rectangle
width: The width of the rectangle
Returns:
The area (length * width)
"""
return length * width
# Access docstring
print(calculate_area.__doc__)Functions are reusable blocks
If you write the same code twice, put it in a function. Functions make code: reusable, testable, readable, and maintainable.Practical Exercise
Define: def greet(name): return f"Hello, {name}!"
Call: greet("Anita")
Define: def add(a, b): return a + b
Add a docstring to your function
Call help(greet) to see the docstring
Key Takeaways
- Define with def. Call with function_name(args).
- return sends a value back. No return = returns None.
- Parameters receive values. Multiple params separated by commas.
- Docstrings (triple quotes) document your function.
- If code is repeated, put it in a function.
Comments
Comments
Post a Comment