What are functions in Python
Functions in Python are blocks of code that perform a specific task and can be called repeatedly. They are a fundamental element of programming and help structure code, making it more readable and reusable.Syntax of function definition
To create a function in Python, the keyword def is used, followed by the function name and parentheses with parameters.:
def function_name(parameters):
"""Function documentation (optional)"""
# Function body
return value # Not necessarily
A simple example of a function
def greet(name):
"""Function for greeting the user"""
print("Hello, " + name + "!")
# Function call
greet("Alice") # Outputs: Hello, Alice!
Function parameters
Default parameters
Functions can have parameters with default values, which makes them more flexible:
def greet(name="World"):
"""Greeting with the default parameter"""
print("Hello, " + name + "!")
greet() # Outputs: Hello, World!
hello("Python") # Outputs: Hello, Python!
Named parameters
Python allows passing arguments by name:
def create_profile(name, age, city="Not specified"):
print(f"Name: {name}, Age: {age}, City: {city}")
create_profile(name="Anna", age=25, city="Moscow")
create_profile(age=30, name="Peter") # Order is not important
Returning values from functions
Functions can return the result of their work using the return keyword:
def add(a, b):
"""Function for adding two numbers"""
return a + b
result = add(3, 5)
print(result) # 8
# The function can return multiple values
def get_name_age():
return "Ivan", 25
name, age = get_name_age()
Variable number of arguments
Using *args
To process an arbitrary number of positional arguments, *args is used:
def sum_values(*args):
"""Function for adding any number of numbers"""
total = 0
for num in args:
total += num
return total
result = sum_values(1, 2, 3, 4, 5)
print(result) # 15
Using **kwargs
To work with named arguments, use **kwargs:
def print_info(**kwargs):
"""Function for displaying user information"""
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Anna", age=25, city="Moscow")
Types of functions in Python
Built-in functions
Python provides many built-in functions: print(), len(), max(), min(), sum() and others.
Custom functions
Functions that a programmer creates to solve specific tasks.
Lambda functions
Anonymous functions for simple operations:
square = lambda x: x**2
print(square(5)) # 25
Python function naming rules
Basic principles
-
Description of the action: The name should reflect the action being performed
calculate_sum()instead offunc1()get_user_data()instead ofdata()
-
Using verbs: Functions perform actions, so use verbs
create_report(),validate_email(),process_data()
-
snake_case style: Separate words with underscores
get_data_from_api()instead ofgetDataFromAPI()
-
Talking names: Avoid abbreviations and obscure names
calculate_monthly_salary()instead ofcalc_sal()
What to avoid
- Reserved Python words (
if,else,for,while) - The names are too general (
data,info,process) - Single-letter names (except for short loops)
- Names of the built-in functions (
print,len,max)
Scope of variables
Local variables
def my_function():
local_var = "Local variable"
print(local_var)
Global variables
global_var = "Global variable"
def access_global():
global global_var
global_var = "Changed in function"
print(global_var)
Recursive functions
Functions can call themselves:
def factorial(n):
"""Calculating the factorial of a number"""
if n<= 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120
Function Decorators
Decorators allow you to modify the behavior of functions:
def timer_decorator(func):
"""Decorator for measuring execution time"""
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Run time: {end - start:.4f} seconds")
return result
return wrapper
@timer_decorator
def slow_function():
import time
time.sleep(1)
return "Done"
Best practices when working with functions
- The principle of sole responsibility: Each function must perform one task
- Documentation: Use docstring to describe the function
- Checking the input data: Validate the function parameters
- Error handling: Use try/except to handle exceptions
- Testing: Write tests to test how functions work
Understanding how to work with functions in Python is crucial for creating high-quality and maintainable code. Proper use of functions makes programs more modular, readable, and efficient.