Functions are named blocks of code designed to perform a specific task. They allow you to break down complex problems into smaller, manageable, and reusable parts, promoting code organization and reducing redundancy. In Python, you define functions using the def keyword.
Defining a Function
Syntax:
pythondef function_name(parameter1, parameter2, ...): """Docstring: Briefly describes what the function does.""" # Function body: code to execute statement1 statement2 return value # Optional: return a result
Example: A simple function without parameters or return value
pythondef greet(): """This function prints a simple greeting.""" print("Hello there!") # Calling the function greet() # Output: Hello there!
Parameters (Arguments)
Parameters are variables listed inside the parentheses in the function definition. They act as placeholders for values that will be passed into the function when it's called. These values are called arguments.
pythondef greet_user(name): """This function greets the user by their name.""" print(f"Hello, {name}!") # Calling the function with an argument greet_user("Alice") # Output: Hello, Alice! greet_user("Bob") # Output: Hello, Bob!
Return Values
Functions can perform operations and then return a result back to the caller using the return statement. If a function doesn't explicitly return a value, it implicitly returns None.
pythondef add_numbers(num1, num2): """This function takes two numbers and returns their sum.""" sum_result = num1 + num2 return sum_result # Calling the function and storing its return value result = add_numbers(5, 3) print(f"The sum is: {result}") # Output: The sum is: 8 # You can also use the return value directly print(f"Another sum: {add_numbers(10, 20)}") # Output: Another sum: 30 # Function returning multiple values (as a tuple) def get_full_name(first, last): return first + " " + last, len(first) + len(last) name, length = get_full_name("John", "Doe") print(f"Full name: {name}, Length: {length}") # Output: Full name: John Doe, Length: 8
Default Parameter Values
You can provide default values for parameters. If a caller doesn't provide an argument for that parameter, the default value is used. Default parameters must come after non-default parameters.
pythondef say_hello(name="Guest", message="Hello"): """Greets a person with a custom message or defaults.""" print(f"{message}, {name}!") say_hello("Charlie") # Output: Hello, Charlie! say_hello() # Output: Hello, Guest! say_hello(message="Hi", name="David") # Output: Hi, David! (keyword arguments)
Keyword Arguments
When calling a function, you can specify arguments by their parameter names. This allows you to pass arguments in any order and makes your code more readable.
pythondef describe_pet(animal_type, pet_name): print(f"I have a {animal_type} named {pet_name}.") describe_pet(animal_type="dog", pet_name="Buddy") describe_pet(pet_name="Whiskers", animal_type="cat") # Order doesn't matter with keyword arguments
Functions are the building blocks of modular programming. They enable you to write clean, efficient, and easily maintainable code by abstracting away specific tasks into reusable units.
Key Takeaways:
- Functions (
def) encapsulate reusable code blocks. - Parameters are placeholders for input values (arguments).
returnstatement sends a value back from the function; functions withoutreturnimplicitly returnNone.- Default parameters provide fallback values if arguments aren't supplied.
- Keyword arguments allow passing arguments by name, improving readability and order flexibility.