DEV Community

Python Tutorial
Python Tutorial

Posted on

Python Functions and Method

Python Functions

Image description


Introduction

Python marks itself as an adaptable multiple-use language as developers value its text-based simplicity and readable features. Python programming consists of functions that establish one of its foundational constructs. Programs benefit from functions when developers write code once for reuse because this approach makes programs more efficient and modular as well as easier to manage. Methods within object-oriented programming (OOP).


Function in Python: Python functions in Python programming embodies standardized programming sections that enable developers to execute particular tasks multiple times. Function definitions enable developers to create a single code block that they can execute anytime by calling it through its name.


Key Features of Functions:

  1. The reuse of code becomes possible through functions that eliminate duplicate sections, thus improving code maintenance.
  2. The program becomes easier to manage through the usage of modularity, which segments the code into smaller parts.
  3. The organization structure of well-written functions creates more understandable programs that perform better.
  4. When debugging happens, it becomes easier to track code errors since they point to specific functions rather than require a full program scan.

Types of Functions in Python

The Python programming language includes two basic function types:

1. Built-in Functions

The Python programming language includes print(), len(), type() and sum() and other built-in functions that handle common operations. Users do not need to define these functions since they are already available to them.

2. User-Defined Functions

The programmer establishes functions that operate for distinct operations, which are named user-defined functions. Dimension and semantics of user-defined functions are set through the def keyword.


Defining a Function in Python

A function is created using the following syntax:
def function_name(parameters):
# Function body
return result # Optional return statement

Components of a Function:

def (keyword) – Used to define a function.
Function name – A valid Python identifier – following Python naming rules.
Parameters (optional) – Input values your function will accept.
Docstring (optional) – Consists of a short description of what the function does.
Body of function – The actual code that does the introverted job.
Return statement (optional) – Returns the output of the function.


Calling a Function

After it is defined, a function can be invoked any number of times using its name followed by parentheses:
function_name(arguments)

For example:

**def greet(name):
return "Hello, " + name + "!"
print(greet("Alice")) # Output: Hello, Alice!

Function Parameters and Arguments

1. Positional Arguments

Arguments are matched in order:
def add(a, b):
return a + b
print(add(3, 5)) # Output: 8

2. Default Arguments

The parameter obtains an automatically assigned default value when declared in the function definition.
def power(base, exponent=2):
return base *
exponent
print(power(3)) # Output: 9
print(power(3, 3)) # Output: 27*

3. Keyword Arguments

Parameter names work as the method to pass arguments down to the function.
print(power(exponent=3, base=2)) # Output: 8

4. Variable-Length Arguments

For unknown numbers of arguments:
** args (Non-keyword Arguments): *
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3, 4, 5)) # Output: 15

** kwargs (Keyword Arguments): **
*def display_info(
details):
for key, value in details.items():
print(f"{key}: {value}")
display_info(name="Alice", age=25, country="USA")*


What is a Method in Python?

A method functions like a function as an object associate property. To execute a method, you call it from an object while it gains access to object properties for both reading and modifying them.

Key Features of Methods:

  1. A method exists as a dedicated member of either a particular class or its instance.
  2. There exists a critical parameter called self which stands for the current class instance.
  3. Classes hold methods that exist as opposed to independent functions.

Defining and Using Methods

Instance Methods

All instance methods target instance attributes while needing the self-parameter for their operation.
*class Car:
def init(self, brand):
self.brand = brand

def display_brand(self):
    return f"The car brand is {self.brand}"
Enter fullscreen mode Exit fullscreen mode

car1 = Car("Toyota")
print(car1.display_brand()) # Output: The car brand is Toyota*

Class Methods

The decorator @classmethod enables creation of static methods that work with class-level attributes in Python.
class Vehicle:
wheels = 4 # Class attribute

@classmethod
def change_wheels(cls, new_wheels):
cls.wheels = new_wheels

Vehicle.change_wheels(6)
print(Vehicle.wheels) # Output: 6*

Enter fullscreen mode Exit fullscreen mode




Static Methods

This method gets defined by using @staticmethod yet it completely ignores both class-level and instance-level attributes.
class MathUtils:
@staticmethod
def add(a, b):
return a + b
print(MathUtils.add(5, 3)) # Output: 8

Function vs Method: Key Differences

Aspect Function Method
Definition Independent block of code Defined inside a class
Call Syntax function_name() object.method_name()
Self-Parameter Not required Requires self for instance methods
Scope Can exist independently Tied to a class or object
Access to Object Data No access Can modify object attributes

Conclusion

Programmers depend on functions and methods in Python development to produce efficient modular code that remains easy to understand. Functions enable flexible code definition encapsulation. Writers of Python applications must determine function and method usage to achieve both maintainability and scalability.

Top comments (0)