Python is Versatile

"Python is a versatile programming language that strongly supports Object-Oriented Programming (OOP). This paradigm models real-world entities as objects with attributes and methods, promoting code reusability, modularity, and maintainability. Key OOP concepts in Python include classes, objects, inheritance, polymorphism, and encapsulation."- Gemini 2025

Scripting

Python excels at automating repetitive tasks. If you're doing something tedious, consider writing a script. It'll save you time and reduce errors in the long run.

Scripts range from simple command sequences to complex programs with functions and external modules, offering flexibility for various automation needs.

Example: Python for Scripting
Organizing files into subdirectories based on their file extensions.

This script:

  1. Gets all files in the current directory.
  2. For each file, it determines the file extension.
  3. Creates a subdirectory for each unique extension if it doesn't already exist.
  4. Moves each file into its corresponding subdirectory based on its extension.

This helps organize cluttered directories by grouping files of the same type together, making it easier to manage and locate files.

Warning: Do not run this unless you actually want to organize the folder you are running it from
import os
import shutil

# Get the current directory
current_directory = os.getcwd()

# Get a list of all files in the directory
files = os.listdir(current_directory)

# Organize files into subdirectories based on their extensions
for file in files:

    # Skip directories
    if os.path.isdir(file):
        continue

    # Get the file extension
    _, extension = os.path.splitext(file)
    extension = extension[1:]  # Remove the dot

    if extension:
        # Create a directory for this extension if it doesn't exist
        if not os.path.exists(extension):
            os.makedirs(extension)

        # Move the file to the corresponding directory
        shutil.move(file, os.path.join(extension, file))
        print(f'Moved {file} to {extension} folder')
    else:
        print(f'Skipped {file} (no extension)')

print('File organization complete!')
What is main?

You may have seen a Python script with a main function. That's an optional convention used to structure code and control its execution when the script is run directly versus imported as a module.

In this script the main() function will execute when you run this script directly,
but not if you import it as a module in another script.
def greet(name):
    return f'Hello, {name}!'

def main():
    name = input('Enter your name: ')
    message = greet(name)
    print(message)

if __name__ == '__main__':
    main()
TIP: In some text editors, typing ifm followed by a tab automatically inserts the entire 'if-main' code snippet.
Object Oriented Programming (OOP)
Objects in OOP encapsulate data (state) and behavior (methods), allowing for modular, reusable code. While maintaining state across different instances is a key reason to create classes, it's not the only one. Classes are also useful for:
  1. Organizing related functionality
  2. Implementing inheritance and polymorphism
  3. Creating interfaces for complex systems
However, only create classes when these benefits outweigh the added complexity. For simpler tasks, functions or data structures often suffice.
Example: Python for OOP
This example showcases Python's OOP capabilities by creating a simple game. It defines a Character class with attributes for name and health (state) and a method for attacking (behavior). Objects player1 and player2 are created based on this class, and they interact by attacking each other and changes their opponent's state.
class Character:
    def __init__(self, name, health):
        self.name = name
        self.health = health
        print(f'{name} initialized with {health} health.')

    def attack(self, target):
        target.health -= 10
        print(f'{self.name} attacked {target.name}.')
        print(f'{target.name} now has {target.health} health.')

player1 = Character('Hero', 100)
player2 = Character('Villain', 80)

player1.attack(player2)
player2.attack(player1)
Running this script outputs:
Hero initialized with 100 health.
Villain initialized with 80 health.
Hero attacked Villain.
Villain now has 70 health.
Villain attacked Hero.
Hero now has 90 health.
A Deeper Dive

Object-Oriented Programming Concepts

Object-Oriented Programming (OOP) is a programming paradigm that organizes code around objects and classes rather than functions and logic. It provides a structured approach to software development through four fundamental principles that promote code reusability, maintainability, and scalability. Understanding these core concepts is essential for building robust and efficient applications.

Core OOP Concepts

Class

A blueprint or template that defines the structure and behavior of objects. A class specifies what attributes (data) and methods (functions) its objects will have, but doesn't contain actual data itself.

Object

An instance of a class that contains actual data and can perform actions defined by its class. Objects are the concrete entities that exist in memory and have specific values for their attributes.

Encapsulation

The practice of bundling data (attributes) and methods that operate on that data within a single unit (class), while restricting direct access to some components. This promotes data hiding and protects the internal state of objects.

Abstraction

The process of hiding complex implementation details while showing only the essential features of an object. It allows users to interact with objects through a simplified interface without needing to understand the underlying complexity.

Inheritance

A mechanism where one class (derived class, child class, subclass) acquires the properties and behaviors of another class (base class, parent class, superclass). This promotes code reusability and establishes hierarchical relationships between classes.

Polymorphism

The ability of objects of different classes to be treated as instances of the same base class, while maintaining their specific behaviors. This allows the same interface to be used for different underlying data types or classes.

Example: Python Class Inheritance and Polymorphism
# This is the parent class
class Animal:
    def __init__(self, name):
        self.name = name

    def make_sound(self):
        print('noise')

    def move(self):
        print('walk')

# This child class overrides both methods
class Dog(Animal):
    def make_sound(self):
        print('woof')

    def move(self):
        print('run')

# This child class overrides one method
class Cat(Animal):
    def make_sound(self):
        print('meow')

# This child class overrides one method
class Bird(Animal):
    def move(self):
        print('fly')

animals = [Dog("Snoopy"), Cat("Garfield"), Bird("Tweety")]

for animal in animals:
    # name is inherited from parent class
    name = animal.name
    print(f'\n{name}')

    # polymorphic methods
    animal.make_sound()
    animal.move()

Details:

→ This page was created with help from Gemini and Claude AI.