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

Python Iterators: Understanding Iterables and Iterators in Python

← Back to Home

๐Ÿ” Python Iterators (Made Simple) 

Iterators are a way to go through all the elements in a collection (like a list or tuple), one item at a time. Python has built-in support for iterators, making it easy to loop through data.

If you've ever used a for loop in Python, you've already worked with iterators—even if you didn’t realize it!


✅ What Is an Iterator?

An iterator is an object that can be looped through (iterated over). It must follow two main rules:

  1. It must have a method called __iter__() → returns the iterator object itself.

  2. It must have a method called __next__() → returns the next item from the sequence.


๐Ÿ“˜ Example 1: Using an Iterator

my_list = [1, 2, 3]

# Get an iterator
my_iter = iter(my_list)

print(next(my_iter))  # Output: 1
print(next(my_iter))  # Output: 2
print(next(my_iter))  # Output: 3

๐Ÿ” Output:

1
2
3

If you call next() again after the list is finished, it will raise a StopIteration error.


๐Ÿ›  Behind the Scenes of a For Loop

When we use a for loop like this:

for item in [1, 2, 3]:
    print(item)

Python automatically:

  • Calls iter() to get an iterator.

  • Calls next() repeatedly until StopIteration is raised.


๐Ÿงฑ Building a Custom Iterator

Let’s create our own iterator to return numbers from 1 to 5.

๐Ÿ“˜ Example 2: Custom Iterator

class MyNumbers:
    def __iter__(self):
        self.num = 1
        return self

    def __next__(self):
        if self.num <= 5:
            x = self.num
            self.num += 1
            return x
        else:
            raise StopIteration

# Create object
nums = MyNumbers()
my_iter = iter(nums)

for number in my_iter:
    print(number)

๐Ÿ” Output:

1
2
3
4
5

๐Ÿ’ก Important Notes

  • iter() creates an iterator from an iterable (like a list or string).

  • next() returns the next value.

  • When there are no more items, StopIteration is raised to end the loop.

  • You can create custom iterators by defining __iter__() and __next__().


๐Ÿ“˜ Example 3: Iterating Over a String

Strings are also iterable!

my_str = "Hi"
my_iter = iter(my_str)

print(next(my_iter))  # Output: H
print(next(my_iter))  # Output: i

๐Ÿ” Output:

H
i

๐ŸŽฏ Conclusion

Iterators are a powerful tool in Python that let you go through items one at a time. Whether you’re working with lists, strings, or building custom sequences, understanding iterators helps us write clean and efficient code.


Python Inheritance

← Back to Home

 

๐Ÿ Inheritance in Python (Made Simple)

Inheritance is one of the most important concepts in Object-Oriented Programming (OOP). It allows a class to use the properties and methods of another class.

Inheritance allows us to define a class that inherits all the methods and properties from another class.


Think of it like a family: a child can inherit features from their parents.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.

 In programming, a class (child) can inherit features (methods and variables) from another class (parent).

For more on Python classes, check out our post on Python Classes and Objects.


✅ Why Use Inheritance?

  • To reuse code.

  • To make the program easier to manage.

  • To follow the DRY principle (Don't Repeat Yourself).


๐Ÿงฑ Basic Syntax

class Parent:
    # parent class
    pass

class Child(Parent):
    # child class that inherits from Parent
    pass

๐Ÿ“˜ Example: Simple Inheritance

# Parent class
class Animal:
    def speak(self):
        print("I am an animal")

# Child class
class Dog(Animal):
    def bark(self):
        print("Woof!")

# Creating object of Dog
my_dog = Dog()

my_dog.speak()  # Inherited from Animal
my_dog.bark()   # Defined in Dog

๐Ÿ” Output:

I am an animal
Woof!

Here, the Dog class inherits the speak() method from the Animal class. It also has its own method called bark().


๐Ÿ“˜ Example 2: Inheriting from a Person Class

Let’s create a simple example where a Student class inherits from a Person class.

๐Ÿ‘จ‍๐Ÿ‘ฉ‍๐Ÿ‘ง‍๐Ÿ‘ฆ Step 1: Create the Parent Class

# Parent class
class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)

# Creating an object of Person
x = Person("Steve", "Tendulkar")
x.printname()

๐Ÿ” Output:

Steve Tendulkar

๐Ÿง’ Step 2: Create the Child Class

# Child class that inherits from Person
class Student(Person):
    pass  # No additional code, just inheriting everything from Person

# Creating an object of Student
x = Student("Mike", "Olsen")
x.printname()

๐Ÿ” Output:

Mike Olsen

๐Ÿ“ Note:
The pass keyword is used when you don't want to add any extra functionality to the child class. The Student class automatically gets all the properties and methods from the Person class.



๐Ÿ”„ Types of Inheritance in Python

  1. Single Inheritance – One child inherits from one parent.

  2. Multiple Inheritance – One child inherits from multiple parents.

  3. Multilevel Inheritance – A child inherits from a parent, and another child inherits from that child.

  4. Hierarchical Inheritance – Multiple children inherit from one parent.

  5. Hybrid Inheritance – A mix of any of the above types.


๐Ÿงช Example: Multiple Inheritance

class Father:
    def skill(self):
        print("Good at driving")

class Mother:
    def talent(self):
        print("Good at cooking")

class Child(Father, Mother):
    def hobby(self):
        print("Loves painting")

c = Child()
c.skill()
c.talent()
c.hobby()

๐Ÿ” Output:

Good at driving
Good at cooking
Loves painting

๐Ÿ’ก Important Points

  • The super() function is used to call methods from the parent class.

  • Inheritance makes your code organized and reusable.

  • If both parent and child have the same method, the child’s method will override the parent’s method.


๐Ÿ›  Using super() Example

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        super().speak()
        print("Dog barks")

d = Dog()
d.speak()

๐Ÿ” Output:

Animal speaks
Dog barks

๐ŸŽฏ Conclusion

Inheritance helps us write cleaner and more efficient code. Once we understand it, we can build complex applications more easily by reusing and extending existing code.

For more on Python classes, check out our post on Python Classes and Objects.

Python File Handling

← Back to Home


๐Ÿ”น File Handling in Python – Beginner-Friendly 

In Python, file handling allows us to create, read, write, and delete files. This is useful when you want to store data permanently, such as saving user info, logs, reports, etc.


๐Ÿ”ธ Why is File Handling Important?

Without file handling, data disappears when the program ends. With files, we can store and retrieve data even after the program stops.


๐Ÿ”ธ Opening a File

Python uses the built-in open() function to open a file.

Syntax:

file = open("filename", "mode")

Mode Description
'r' Read (default)
'w' Write (creates new or overwrites file)
'a' Append (adds to end of file)
'x' Create (fails if file exists)
'b' Binary mode (e.g., 'rb', 'wb')

๐Ÿ”ธ Example 1: Writing to a File


file = open("example.txt", "w")  # Open in write mode
file.write("Hello, this is a test.\n")
file.write("Writing to a file in Python.\n")
file.close()  # Always close the file!

๐Ÿ“ This creates a file named example.txt and writes two lines to it.


๐Ÿ”ธ Example 2: Reading from a File

file = open("example.txt", "r")  # Open in read mode
content = file.read()
print(content)
file.close()

๐Ÿ“ This reads and prints the contents of example.txt.


๐Ÿ”ธ Example 3: Appending to a File

file = open("example.txt", "a")  # Open in append mode
file.write("Adding a new line.\n")
file.close()

๐Ÿ“ This adds a new line at the end of the file without deleting the old content.


๐Ÿ”ธ Reading Line by Line

file = open("example.txt", "r")
for line in file:
    print(line.strip())      # Here, strip() removes newline characters
file.close()

๐Ÿ”ธ Using with Statement (Recommended)

Python provides a cleaner way to handle files using the with statement. It automatically closes the file.

Example:

with open("example.txt", "r") as file:
    data = file.read()
    print(data)

Using this way, you don’t need to call file.close().


๐Ÿ”ธ Deleting a File

You can delete a file using the os module.

import os

if os.path.exists("example.txt"):
    os.remove("example.txt")
    print("File deleted.")
else:
    print("File does not exist.")

๐Ÿ”š Summary

  • Use open() to work with files.

  • Modes: 'r' (read), 'w' (write), 'a' (append), 'x' (create).

  • Always close the file after use (or use with).

  • Use the os module for file operations like deleting or checking existence.


✅ Quick Tip:

Use with open(...) as f: whenever possible—it’s safer and cleaner.

Python Classes and Objects

← Back to Home


๐Ÿ”น Classes and Objects in Python

Python is an object-oriented programming (OOP) language. This means it allows you to create and use classes and objects—which helps you organize and reuse code easily.



๐Ÿ”ธ What is a Class?

A class is like a blueprint for creating objects. Think of a class as a design for a car. It defines what a car is (wheels, engine, doors), but it's not a real car yet.

A class is a code template for creating objects. 

Objects have member variables and have behavior associated with them. 

In python, a class is created by the keyword class.

Example:

class Car:
    # attributes and methods go here
    pass


๐Ÿ”ธ What is an Object?

An object is a real-world instance of a class. If a class is the blueprint, then an object is the actual car built using that blueprint.

Example:

my_car = Car()

Now my_car is an object of the Car class.



๐Ÿ”ธ Let’s Build a Real Example

Let’s create a class that represents a Person with a name and age, and a method to display their info.

✅ Example:

class Person:
    def __init__(self, name, age):
        self.name = name      # attribute
        self.age = age        # attribute

    def greet(self):          # method
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Creating objects
person1 = Person("Surya", 25)
person2 = Person("Pawan", 30)

# Calling methods
person1.greet()
person2.greet()

๐Ÿ’ก Output:

Hello, my name is Surya and I am 25 years old.
Hello, my name is Pawan
and I am 30 years old.

๐Ÿ”ธ Breaking It Down

Part Description
class Person: Defines a class called Person
__init__ A special method called a constructor; runs when you create an object
self Refers to the current object (must be the first parameter in methods)
self.name = name Assigns the input to the object's attribute
greet() A method that prints a message using the object’s data

๐Ÿ”ธ Another Example: A Simple Bank Account

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        print(f"{amount} deposited. New balance: {self.balance}")

    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
            print(f"{amount} withdrawn. New balance: {self.balance}")
        else:
            print("Insufficient balance!")

# Create an account
account = BankAccount("John", 1000)

# Use the methods
account.deposit(500)
account.withdraw(300)
account.withdraw(1500)

๐Ÿ’ก Output:

500 deposited. New balance: 1500
300 withdrawn. New balance: 1200
Insufficient balance!

๐Ÿ”š Summary

  • A class defines the structure and behavior (attributes and methods).

  • An object is a real example of the class.

  • Use __init__ to initialize object attributes.

  • Use self to refer to the current object inside the class.

  • Classes help keep your code organized, reusable, and clean.


Creating a simple Function in python || python code for creating function

← Back to Home

๐Ÿ”น Functions in Python

A function is a block of code which only runs when it is called.

we can pass data, known as parameters, into a function.

A function can return data as a result.


# In Python a function is defined using the def keyword:

๐Ÿ”ธ Example : Creating a Function

def my_function():
  print("Hello function" )



๐Ÿ”ธ  Calling a Function

To call a function, we use the function name followed by parenthesis

 Example :


def my_function():
  print("Hello from function")

my_function()    # Here is Function call by its name


Python Functions Explained: A Beginner’s Guide with Code Examples

← Back to Home

๐Ÿ” Understanding Python Functions – A Beginner’s Guide

Functions are one of the most powerful and useful features in Python. They allow you to group code into reusable blocks, making your programs more organized, readable, and efficient.

Functions are the heart of clean, efficient Python programming. If you're a beginner, think of functions as named blocks of code that do something specific — like a recipe in a cookbook.


๐Ÿง  What is a Function?

A function is a reusable block of code that  that performs a specific task and runs only when called.  You define it once and call it whenever needed. 

You can pass data into it using parameters, and get a result back using the return keyword.

๐Ÿ“Œ Key Points:

  • A function is a block of code which only runs when it is called.
  • You can pass data, known as parameters, into a function.
  • A function can return data as a result.
  • In Python, a function is defined using the def keyword:

See example below:

def my_function():
  print("Hello from a function")

๐Ÿ”ง Basic Anatomy of a Function

def function_name(parameters):
    # code block
    return result

๐Ÿ‘️ Code Diagram

+---------------------------+
| def greet(name):         | <- Function Definition
|     print("Hello", name) | <- Function Body
+---------------------------+

        ⬇ Function Call

+--------------------+
| greet("Alice")     | <- Output: Hello Alice
+--------------------+

✅ Why Use Functions?

Functions help you:

๐Ÿงฉ Break complex tasks into manageable chunks
๐Ÿ” Reuse code instead of repeating
๐Ÿ“š Improve readability of your code
๐Ÿ› ️ Debug and maintain programs easily


✍️ Creating Your First Function

Let’s write a simple function:

def my_function():
    print("Hello from a function")

✍️ Defining and Calling a Function

Let’s write a above simple function again:

def my_function():
    print("Hello from a function!")

# Call the function
my_function()

๐Ÿ–ฅ️ Output:

Hello from a function!


๐Ÿงพ Function with Parameters

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

๐Ÿ–ฅ️ Output:

Hello, Alice!

๐Ÿ“Œ You can pass any data—strings, numbers, lists, etc.—as parameters.



๐Ÿ” Reusability at Work:

Want to greet different users? Use parameters.

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

greet("Alice")
greet("Bob")

๐Ÿ–จ️ Output:

Hello, Alice!
Hello, Bob!

๐Ÿ”„ Returning Values from Functions

Some functions return a result:

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

sum = add(4, 6)
print(sum)

๐Ÿ–จ️ Output:

10


๐Ÿ”„ Function with Conditional Logic

def is_even(num):
    if num % 2 == 0:
        return True
    else:
        return False

print(is_even(4))  # True
print(is_even(5))  # False

๐Ÿ“Œ You can use functions to implement logic and decision-making.


๐Ÿงญ Flowchart: How a Function Works

[Start]
   ↓
Define Function → [Call Function?] — No → [End]
                          ↓ Yes
                    Execute Code Block
                          ↓
                     Return (Optional)
                          ↓
                        [End]

See the flowchart in picture below:




๐ŸŽฅ Watch and Learn

Want to see it in action?
๐Ÿ‘‰ Check out the video below: “What is a Function in Python” – ideal for visual learners!



๐ŸŽฏ Final Tip

Functions help you write clean, modular, and testable code. The more you use them, the better your Python skills will become!


๐Ÿš€ Your Turn

Now that you know the basics of Python functions, try creating your own! Whether it’s a calculator or a greeting app, functions will help you build smarter and cleaner code.


Dictionaries in Python

← Back to Home

Python Dictionaries:



Dictionaries are python data structures which store the data in key-value pairs. These are like Maps in other similar programming languages.

Dictionaries are not ordered unlike strings, Lists and Tuples.

Keys uniquely define the items in a python dictionary. So duplicate keys are not allowed.

Keys are unique but values are not.

Keys must be of immutable types like strings, numbers and tuples.

Dictionary can contain any type of values.



Creating a Dictionary :

Each key is separated from its value by a colon(:)

The items are separated by commas

All the above paired items are enclosed in curly braces.


watch video below to demonstrate python dictionaries: 





Empty Dictionary:
       An empty dictionary without any item is created with just two curly braces.{}

Example:

              

Dictionary containing items: (create and display)




Accessing values from Dictionary:

Values can be accessed  using square brackets along with the key to obtain its value.

Example:



Both the print commands produces the corresponding values with keys "Name" and "Age".

If we attempt to access the data item which is not present in dictionary, we'll get error as





Updating Dictionary :

Dictionary can be updated by adding a new entry or a Key-Value pair, modifying an existing entry or deleting an existing entry :
Example:

In the above code the key 'Age' has the updated value from 25 to 16.
Also, there is a new entry where key is 'Department' with the value 'Finance'.(see Highlighted)


Deleting Dictionary Element

You can delete either an individual item or entire content of a dictionary.

Entire dictionary can also be deleted in a single operation.

Example 1:


If we now want to print the items, An exception is raised because after the command del dict, dictionary does not  exist.

Example 2:




 Properties of Dictionary Keys:

1. More than one entry per key is not allowed i.e duplicate keys are not allowed. When duplicate keys are assigned, only the last assigned (latest) key exists.

2. Keys must be immutable. i.e you can use strings, numbers and Tuples as dictionary keys . others are not allowed.



Built-in Dictionary functions:

1.  cmp : compares elements of both dict.

             cmp ( dict1 , dict2)

2.   len: Gives total length or the total number of elements in the dictionary.

             len(dict)

3.   str: produces a printable string representation of a dictionary.

            str(dict)

4.  type (variable) - returns the type of passed variable . If passed variable is dictionary, then it returns dictionary type.



Dictionary Methods:

Python uses following dictionary methods:

1.    dict.clear( )

2.    dict.copy( )

3.    dict.fromkeys( )

4.    dict.get(key, default = None)

5.    dict.has_key(key)

6.    dict.items( )

7.    dict.keys()

8.    dict.setdefault(key, default=None)

9.    dict.update(dict2)

10.  dict.values()


Featured Post

Extra Challenge: Using References Between Documents

  ๐ŸŽฏ ๐Ÿ’ก Extra Challenge: Using References Between Documents Here's an  Extra Challenge  designed to build on the original MongoDB mode...

Popular Posts