Functions in Python are blocks of reusable code that perform a specific task. They help in making the code more modular, readable, and maintainable. A function is defined using the def keyword, followed by a function name, parentheses (which may contain parameters), and a colon. The function body contains the actual code to execute and often returns a value.
def greet(): print("Hello, World!") greet() # Hello, World!
Arguments and Parameters
def greet(name): # 'name' is a parameter print(f"Hello, {name}!") greet("Alice") # 'Alice' is an argument
Sending Arguments to a Function
Python functions accept different types of arguments:
- Positional Arguments
These are arguments that must be passed in the correct order.
def add(a, b): return a + b result = add(5, 3) print(result) # 8
- Named Arguments (Keyword Arguments)
Named arguments allow you to pass values to specific parameters, regardless of order. This improves readability and prevents errors when dealing with multiple parameters.
def introduce(name, age): print(f"My name is {name} and I'm {age} years old.") introduce(age=25, name="Bob") # My name is Bob and I'm 25 years old.
- Default Argument Values
You can set default values for function parameters. If an argument is not passed, the default value is used.
def greet(name="Guest"): print(f"Hello, {name}!") greet() # Hello, Guest! greet("Alice") # Hello, Alice!
- Arbitrary Number of Arguments (*args)
If you don’t know the number of arguments beforehand, use *args to accept multiple positional arguments as a tuple.
def add_numbers(*numbers): return sum(numbers) print(add_numbers(1, 2, 3, 4)) # 10 print(add_numbers(10, 20)) # 30
- Arbitrary Keyword Arguments (**kwargs)
If you need to accept an arbitrary number of keyword arguments, use **kwargs. These are stored in a dictionary.
def print_details(**details): for key, value in details.items(): print(f"{key}: {value}") print_details(name="Alice", age=25, city="New York") ''' name: Alice age: 25 city: New York '''
- Passing Lists and Dictionaries as Arguments
Lists and dictionaries can be passed as arguments to functions.
- Passing Lists:
def total_marks(marks): return sum(marks) print(total_marks([90, 80, 70])) # 240
- Passing Dictionaries:
def show_info(person): print(f"Name: {person['name']}, Age: {person['age']}") show_info({"name": "John", "age": 30}) # Name: John, Age: 30
Importing Functions from Modules
Python allows you to import functions from other modules.
- Import a Specific Function
from math import sqrt print(sqrt(16)) # 4.0
- Import with an Alias
import math as m print(m.sqrt(25)) # 5.0
- Import All Functions
from math import * print(sin(3.14)) # Using sin() directly
import math print(math.sin(3.14)) # Using sin() via math
Caution: Importing everything (*) can lead to conflicts with existing functions.