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 (
Nameandnameare 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:
- Arithmetic Operators (
+,-,*,/,%,//): Used to perform mathematical operations. - Comparison (Relational) Operators (
==,!=,>,>=,<,<=): Compare the values of two operands and return a boolean result. - Logical Operators (
and,or,not): Used to combine conditional statements. - Bitwise Operators (
&,|,^,~,<<,>>): Perform operations on binary representations of integers. - Assignment Operators (
=,+=,-=,*=,/=,%=,//=,**=,&=,|=,^=,<<=,>>=): Used to assign values to variables. - Identity Operators (
is,is not): Used to compare objects.isandis notcheck if two values are located on the same part of the memory (same object identity). - 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: ReturnsTrueif a value is present.not in: ReturnsTrueif a value is not present.
Example:
my_list = [1, 2, 3, 4]
print(2 in my_list) # True
print(5 not in my_list) # TrueDifference between == and is Operators
Operator | Description | Example |
| Compares values of two objects (Equality). |
|
| Compares identity (memory location) of two objects. |
|
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 |
| Integer numbers |
|
| Decimal numbers |
|
| Text data (strings) |
|
| Boolean values |
|
| Ordered, mutable collections |
|
| Ordered, immutable collections |
|
| Key-value pairs |
|
| Unordered, unique collections |
|
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.
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 += 1Types of Functions
Below are the different types of functions in Python:
- Built-in Functions: Predefined by Python.
Examples:
print(),len(),type(),input() - 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
yieldkeyword. - 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
- Default Constructor: A constructor that does not accept any arguments and assigns default values to the instance variables.
def __init__(self): # Default Constructor - 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 ( |
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 attributeInheritance
Inheritance allows a class (child) to inherit properties and methods from another class (parent).
- Single Inheritance: Allows only one parent class and one child class.
- Multiple Inheritance: Allows multiple parent classes and one child class.
- Multilevel Inheritance: A derived class inherits from another derived class, creating a chain of inheritance.
- Hierarchical Inheritance: A single base class is inherited by multiple derived classes.
- 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
- Simple and Easy to Learn
- Interpreted Language (no compilation needed)
- Dynamically Typed (no need to declare variable types explicitly)
- Object-Oriented
- Portable across platforms
- Open Source and Free
- Extensive Libraries (e.g., NumPy, Pandas, Django)
- 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:
- Syntax Errors: Occur when the code is not written correctly.
Example: Missing a colon in an
ifstatement.if x == 5 # Missing colon - 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 7Tkinter 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:
- Install PyMySQL:
pip install pymysql - Import Library and Connect:
import pymysql # Step 1: Connect to MySQL conn = pymysql.connect( host='localhost', user='root', password='yourpassword', database='testdb' ) - Create a Cursor:
cur = conn.cursor() - Execute SQL Query:
cur.execute("SELECT * FROM students") - Fetch and Display Results:
rows = cur.fetchall() for row in rows: print(row) - Close Connection:
conn.close()
Sample Output (if table has data):
(1, 'John', '10th')
(2, 'Alice', '9th')Python Installation Steps
- Download Python:
Go to https://www.python.org, click on Downloads, and choose the version for your OS (Windows, macOS, Linux).
- Run the Installer:
On Windows, run the
.exefile. Important: Check “Add Python to PATH” before clicking Install Now. - Verify Installation:
Open Command Prompt or Terminal and type:
python --versionYou should see something like:
Python 3.x.x - Start Coding:
Use IDLE (comes with Python) or install VS Code / PyCharm for a better experience.
