Menu

Showing posts with label Python Basics. Show all posts
Showing posts with label Python Basics. Show all posts

Difference between function and method in Python

Let’s understand the difference between Python methods and functions and when and how to use function or method:

  1. Functions:

    • Functions are standalone blocks of code that can be called by their name.
    • They are defined independently and are not associated with any specific class or object.
    • Functions can have zero or more parameters.
    • They may or may not return any data.
    • Example of a user-defined function:
      def subtract(a, b):
          return a - b
      
      print(subtract(10, 12))  # Output: -2
      
  2. Methods:

    • Methods are special types of functions associated with a specific class or object.
    • They are defined within a class and are dependent on that class.
    • A method always includes a self parameter (for instance methods) or a cls parameter (for class methods).
    • Methods operate on the data (instance variables) contained by the corresponding class.
    • Example of a user-defined method:
      class ABC:
          def method_abc(self):
              print("I am in method_abc of ABC class.")
      
      class_ref = ABC()  # Create an object of ABC class
      class_ref.method_abc()  # Output: "I am in method_abc of ABC class." 

In final conclusion, functions are independent, while methods are associated with classes or objects. Functions can be called directly by their name, but methods require invoking the class or object they belong to. 

Different ways of writting loops in Python

Lets see we have a list of inetgers name x. 

x = [3,3,3,4,4,4,3,3,5,5,6,6,7,8,9,9,9]

Now iterate over this list using differnet loops.


  1. For loop

          #To read all  the elements from list

for elem in x:
    print(elem)


       #To read element from specific index using range(startindex, stopindex)

        for i in range(2, len(x)):

            print(x[i])

 

  1. While loop
    i = 4
while i < len(x):
    print(x[i])
    i+=1