Functions

A function in Python is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

Here’s how you can define a function:

def greet(name):
    print(f"Hello, {name}!")

And here’s how you can call it:

greet("Alice")  # Output: Hello, Alice!

Functions can also return a value using the return statement:

def add(a, b):
    return a + b

result = add(5, 3)  # result is now 8

Methods

Methods in Python are very similar to functions except they are associated with object/classes. Methods in Python are in fact functions that are called using dot notation. For example, list objects have methods called append, insert, remove, sort, and so on.

Here’s how you can define a method:

class MyClass:
    def greet(self):
        print("Hello, World!")

And here’s how you can call it:

obj = MyClass()
obj.greet()  # Output: Hello, World!