Python Fundamentals: Core Concepts, OOP, and Practical Applications

Python Programming Fundamentals

History of Python

Python is a widely used, general-purpose, high-level programming language created by Guido van Rossum in 1989 in the Netherlands and developed by the Python Software Foundation.

The official date of birth is February 20, 1991.

Python is a dynamic, general-purpose, high-level, interpreted, freeware, and open-source programming language. Python supports both procedure-oriented programming and object-oriented programming.

Variables

A variable in Python is like a box where you can store information (such as numbers, words, or data) and use it later. You give the box a name, and then you can put something in it.

Six Rules for Naming Variables

  • Variable names must start with a letter (A–Z, a–z) or an underscore (_).
  • The rest of the variable name can contain letters, numbers, or underscores.
  • Variable names are case-sensitive (Name and name are different).
  • Reserved words (keywords) cannot be used as variable names.
  • Variable names should not contain spaces.
  • Use descriptive names (e.g., age, student_name) for clarity.

Operators in Python

In Python, operators are special symbols used to perform operations on variables and values. They are categorized based on the type of operation they perform:

  1. Arithmetic Operators (+, -, *, /, %, //): Used to perform mathematical operations.
  2. Comparison (Relational) Operators (==, !=, >, >=, <, <=): Compare the values of two operands and return a boolean result.
  3. Logical Operators (and, or, not): Used to combine conditional statements.
  4. Bitwise Operators (&, |, ^, ~, <<, >>): Perform operations on binary representations of integers.
  5. Assignment Operators (=, +=, -=, *=, /=, %=, //=, **=, &=, |=, ^=, <<=, >>=): Used to assign values to variables.
  6. Identity Operators (is, is not): Used to compare objects. is and is not check if two values are located on the same part of the memory (same object identity).
  7. Membership Operators (in, not in): Test for membership in a sequence.

Membership Operators Details

Membership operators are used to test if a sequence (like a string, list, tuple, etc.) contains a certain value.

  • in: Returns True if a value is present.
  • not in: Returns True if a value is not present.

Example:

my_list = [1, 2, 3, 4]
print(2 in my_list)      # True 
print(5 not in my_list)  # True

Difference between == and is Operators

Operator

Description

Example

==

Compares values of two objects (Equality).

a == b checks if values are equal.

is

Compares identity (memory location) of two objects.

a is b checks if they point to the same object.

Example:

a = [1, 2]
b = [1, 2]

print(a == b)  # True (same values)
print(a is b)  # False (different objects in memory)

Data Types and Structures

Data types represent the type of data present inside a variable.

Data Type

Description

Example

int

Integer numbers

10, -5, 0

float

Decimal numbers

3.14, -7.5

str

Text data (strings)

"Hello", 'Python'

bool

Boolean values

True, False

list

Ordered, mutable collections

[1, 2, 3], ['a', 'b']

tuple

Ordered, immutable collections

(1, 2, 3)

dict

Key-value pairs

{'key': 'value'}

set

Unordered, unique collections

{1, 2, 3}

Key Data Structures Comparison

  • ✅ List:
    • Ordered collection
    • Mutable (can change)
    • Allows duplicates
    • Syntax: []
    • Example: my_list = [1, 2, 3]
  • ✅ Tuple:
    • Ordered collection
    • Immutable (cannot change)
    • Allows duplicates
    • Syntax: ()
    • Example: my_tuple = (1, 2, 3)
  • ✅ Set:
    • Unordered collection
    • Mutable
    • No duplicates allowed
    • Syntax: {}
    • Example: my_set = {1, 2, 3}
  • ✅ Dictionary:
    • Unordered (ordered from Python 3.7+)
    • Stores key-value pairs
    • Keys must be unique
    • Syntax: {key: value}
    • Example: my_dict = {"name": "Alice", "age": 25}

Control Structures: Decisions and Looping

Control structures manage the flow of execution in a program.

AbzyN2hwx5McAAAAAElFTkSuQmCC

Conditional Statements and Loops

Conditional Statements control flow based on conditions:

if x > 0:
    print("Positive")
elif x == 0:
    print("Zero")
else:
    print("Negative")

Loops allow repeated execution:

For Loop:

for i in range(5):
    print(i)

While Loop:

count = 0
while count < 5:
    print(count)
    count += 1

Types of Functions

Below are the different types of functions in Python:

  1. Built-in Functions: Predefined by Python.

    Examples: print(), len(), type(), input()

  2. User-defined Functions: Functions created by the programmer based on specific requirements.

Generator and Iterator Definitions

Generator:
A function that yields values one at a time using the yield keyword.
Example:
def my_gen():
    yield 1
    yield 2
Iterator:
An object that can be looped over (implements __iter__() and __next__() methods).
Example:
my_iter = iter([1, 2, 3])
print(next(my_iter))  # 1

Object-Oriented Programming (OOP) Concepts

Classes and Objects

  • A class is a blueprint for creating objects.
  • An object is an instance of a class.

Example:

class Car:
    def __init__(self, brand):
        self.brand = brand

    def show(self):
        print("Car brand is", self.brand)

c1 = Car("Toyota")  # Object creation
c1.show()

▶️ Output: Car brand is Toyota

Constructors

A constructor in Python is a special method used to initialize objects. It is defined using __init__(self, ...) and is automatically called when an object is created.

📌 Example:

class Student:
    def __init__(self, name):
        self.name = name

s = Student("John")  # Constructor called
print(s.name)

▶️ Output: John

Types of Constructors

  1. Default Constructor: A constructor that does not accept any arguments and assigns default values to the instance variables.
    def __init__(self): # Default Constructor
  2. Parameterized Constructor: A constructor that accepts arguments and uses them to initialize the instance variables.
    def __init__(self, name): # Parameterized Constructor

Difference Between Class and Instance Attributes

Feature

Class Attribute

Instance Attribute

Definition

Shared among all instances

Unique to each object

Declaration

Defined inside the class, outside methods

Defined inside the constructor (__init__)

Memory

One copy shared by all instances

Each object has its own copy

Access

Accessed via class or object

Accessed via object only

Example:

class Student:
    school = "ABC School"  # Class attribute

    def __init__(self, name):
        self.name = name  # Instance attribute

Inheritance

Inheritance allows a class (child) to inherit properties and methods from another class (parent).

  1. Single Inheritance: Allows only one parent class and one child class.
  2. Multiple Inheritance: Allows multiple parent classes and one child class.
  3. Multilevel Inheritance: A derived class inherits from another derived class, creating a chain of inheritance.
  4. Hierarchical Inheritance: A single base class is inherited by multiple derived classes.
  5. Hybrid Inheritance: A combination of two or more types of inheritance (e.g., multiple and hierarchical inheritance).

Encapsulation

Definition: Encapsulation is the process of restricting direct access to some parts of an object and allowing them to be modified only through controlled methods (data hiding).

Python Lambda Function

Definition: A lambda function is a small anonymous function (a function without a name).

List Comprehensions

Definition: List comprehension is a short and simple way to create a new list from an existing list, range, or any iterable.

Python Features and Practical Applications

Key Features of Python

  1. Simple and Easy to Learn
  2. Interpreted Language (no compilation needed)
  3. Dynamically Typed (no need to declare variable types explicitly)
  4. Object-Oriented
  5. Portable across platforms
  6. Open Source and Free
  7. Extensive Libraries (e.g., NumPy, Pandas, Django)
  8. Supports Machine Learning and AI

Exception Handling and Errors

What are Errors?

Errors are problems in a program that cause it to stop or behave unexpectedly. Two main types exist:

  1. Syntax Errors: Occur when the code is not written correctly.

    Example: Missing a colon in an if statement.

    if x == 5  # Missing colon
  2. Runtime Errors (Exceptions): Occur while the program is running.

    Example: Attempting division by zero.

    print(10 / 0)  # ZeroDivisionError

What is Exception Handling?

Exception handling is used to catch and manage errors during program execution, so the program doesn’t crash.

Exception Handling Syntax

Use try-except to handle exceptions and prevent crashes.

try:
    x = int(input("Enter number: "))
    result = 10 / x
except ZeroDivisionError:
    print("Cannot divide by zero.")
except ValueError:
    print("Invalid input.")
else:
    print("Result:", result)
finally:
    print("Execution completed.")

Output Example (Input: 0):

Enter number: 0
Cannot divide by zero.
Execution completed.

Program Example: Check Divisibility by 7

This program checks whether a number entered by the user is divisible by 7.

num = int(input("Enter a number: "))

if num % 7 == 0:
    print(f"{num} is divisible by 7")
else:
    print(f"{num} is not divisible by 7")

Sample Output:

Enter a number: 21 
21 is divisible by 7

Tkinter Widgets: Label, Button, Pack, Place

Tkinter is Python’s standard GUI library.

Label:
Displays static text or images.
Example: Label(root, text="Welcome").pack()
Button:
Creates a clickable button.
Example: Button(root, text="Click Me", command=some_function).pack()
Pack():
Geometry manager that auto-places widgets vertically or horizontally.
Example: widget.pack()
Place():
Positions widgets using specific x, y coordinates.
Example: widget.place(x=50, y=100)

Django Framework Short Note

  • Django is a high-level web framework.
  • Follows MVT architecture (Model-View-Template).
  • Comes with a built-in admin panel and ORM (Object Relational Mapper).
  • Focuses on rapid development and clean code.
  • Helps build secure and scalable web applications.

Connecting Python with MySQL using PyMySQL

Step-by-step process to interact with a MySQL database:

  1. Install PyMySQL:
    pip install pymysql
  2. Import Library and Connect:
    import pymysql
    
    # Step 1: Connect to MySQL
    conn = pymysql.connect(
        host='localhost',
        user='root',
        password='yourpassword',
        database='testdb'
    )
  3. Create a Cursor:
    cur = conn.cursor()
  4. Execute SQL Query:
    cur.execute("SELECT * FROM students")
  5. Fetch and Display Results:
    rows = cur.fetchall()
    for row in rows:
        print(row)
  6. Close Connection:
    conn.close()

Sample Output (if table has data):

(1, 'John', '10th')
(2, 'Alice', '9th')

Python Installation Steps

  1. Download Python:

    Go to https://www.python.org, click on Downloads, and choose the version for your OS (Windows, macOS, Linux).

  2. Run the Installer:

    On Windows, run the .exe file. Important: Check “Add Python to PATH” before clicking Install Now.

  3. Verify Installation:

    Open Command Prompt or Terminal and type:

    python --version

    You should see something like: Python 3.x.x

  4. Start Coding:

    Use IDLE (comes with Python) or install VS Code / PyCharm for a better experience.