Python functions are reusable blocks of code designed to perform a specific task. They help prevent code repetition, break complex programs into smaller manageable pieces, and only run when explicitly called.
Basic Syntax - Defining and Calling a Function
- Functions are defined using the def keyword, followed by a custom name, parentheses (), and a colon :. The body of the function must be indented.
# 1. Defining the function
def greet():
print("Hello! Welcome to Python.")
# 2. Calling the function
greet()
Parameter vs Arguments
- Parameters are names used in a function defination that describes what data the function expects.
- Arguments are the actual values passed in a function call that are assigned to parameters.
def greet_user(username): # username is a parameter
print(f"Hello, {username}!")
greet_user("Alice") # "Alice" is an argument
Core Argument Types
Positional
- Values map directly to parameters based on the order they are written.
# 'name' is the first parameter, 'age' is the second
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
# Calling the function using positional arguments
greet("Alice", 25)
# Output: Hello Alice, you are 25 years old.
Keyword
- Keyword argument (or named argument) is an argument passed to a function by explicitly stating the parameter name and its value using the syntax parameter_name = value
def greet_user(name, greeting, punctuation="!"):
return f"{greeting}, {name}{punctuation}"
# 1. Standard positional call (order matters)
print(greet_user("Alice", "Hello")) # Output: Hello, Alice!
# 2. Keyword argument call (order doesn't matter)
print(greet_user(greeting="Hi", name="Bob")) # Output: Hi, Bob!
# 3. Mixing both (positional MUST come first)
print(greet_user("Charlie", greeting="Welcome", punctuation=".")) # Output: Welcome, Charlie.
Default argument
- Default argument is a fallback value assigned to a function parameter during its definition. If you omit that argument when calling the function, Python automatically uses this predefined default value; if you provide a value, it overrides the default
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Output: Hello, Guest! (Uses default)
greet("Alice") # Output: Hello, Alice! (Overrides default)
Args
- *args is a special syntax used in function definitions to allow a function to accept a variable number of positional arguments.
def multiply_all(*args):
result = 1
# args is treated as a tuple: (2, 3, 4)
for number in args:
result *= number
return result
# You can call the function with any number of inputs
print(multiply_all(2, 3)) # Output: 6
print(multiply_all(2, 3, 4, 5)) # Output: 120
Kwargs
- **kwargs stands for keyword arguments. It is a special syntax used in function definitions to allow a function to accept an arbitrary (variable) number of named arguments
- The values are stored in a dictionary.
def display_info(**kwargs):
# kwargs is a dictionary inside the function
print(kwargs)
# Calling the function with different keyword arguments
display_info(name="Alice", age=30, city="New York")
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
Return Values
- Use the return statement to exit a function and send data back to the program. If no return statement is defined, the function automatically returns None.
def add_numbers(a, b):
return a + b
result = add_numbers(5, 10)
print(result) # Output: 15
- You can return multiple values by separating them with commas. Python automatically packs them into a tuple, which you can then unpack into separate variables
def get_user_data():
name = "Bob"
age = 25
return name, age # Returns a tuple: ("Bob", 25)
user_name, user_age = get_user_data() # Unpacking
print(user_name) # Output: Bob
Conclusion
Python functions are the fundamental building blocks of clean, efficient, and reusable code. They allow developers to group a specific block of logic together, reducing repetition and making complex programs manageable.
Top comments (0)