Python Programming: Core Concepts and Practical Examples

Python is a high-level, general-purpose programming language known for readable syntax, a large standard library, and a broad ecosystem of third-party packages. It is used in automation, web development, data analysis, machine learning, testing, education, and many other fields.

These notes use modern Python 3 syntax. Python 2 reached end of life and should not be used for new development.

1. Introduction to Python

Python was created by Guido van Rossum. Development began in the late 1980s, and the first public release appeared in 1991. Python emphasizes clarity and uses indentation to define blocks of code.

How Python runs code

Python is often described as interpreted. More precisely, the common CPython implementation compiles source code into bytecode and then executes that bytecode in a virtual machine. Other Python implementations may use different techniques.

print("Hello, World!")

Key Python features

  • Readable syntax with significant indentation.
  • Dynamic typing: names can refer to objects of different types at different times.
  • Multi-paradigm programming: procedural, object-oriented, and functional styles are all supported.
  • Cross-platform support on major operating systems.
  • A comprehensive standard library and a large package ecosystem.
  • Automatic memory management.
  • Optional type annotations that improve documentation and static analysis.
Indentation matters: Python uses indentation to define blocks after statements such as if, for, while, def, and class. Use consistent spaces; four spaces is the usual convention.

2. Data Types, Variables, and Operators

Core built-in data types

Common Python data types
Type Description Example
int Integer values of arbitrary precision. 5, -10
float Floating-point values. 3.14, -2.5
complex Complex numbers. 3 + 4j
str Immutable text sequence. "Python"
bool Boolean value. True, False
NoneType Represents the absence of a value. None
list Ordered mutable collection. [1, 2, 3]
tuple Ordered immutable collection. (1, 2, 3)
dict Mapping of unique keys to values. {"name": "Asha"}
set Mutable collection of unique values. {1, 2, 3}

Variables and naming rules

Python creates a name when a value is assigned. A variable name must begin with a letter or underscore, may contain letters, digits, and underscores, and is case-sensitive.

name = "Asha"
age = 20
height = 1.62
is_active = True

print(name)
print(type(age))

Python names refer to objects. Assignment does not copy an object automatically; it binds a name to an object. This distinction is especially important with mutable values such as lists and dictionaries.

Mutable and immutable values

Mutability in Python
Usually immutable Usually mutable
int, float, bool, str, tuple, frozenset list, dict, set, most user-defined objects

Operators

  • Arithmetic: + - * / // % **
  • Comparison: == != > < >= <=
  • Logical: and, or, not
  • Assignment: = += -= *= /= and related forms
  • Membership: in, not in
  • Identity: is, is not
x = 10
y = 3

print(x / y)   # 3.333...
print(x // y)  # 3
print(x % y)   # 1
print(x ** y)  # 1000
== versus is: == compares values, while is checks whether two names refer to the same object. Use is None when checking for None; do not generally use is to compare strings or numbers.
first = [1, 2]
second = [1, 2]
third = first

print(first == second)  # True: values are equal
print(first is second)  # False: separate list objects
print(first is third)   # True: both names refer to one object

3. Control Flow

Control-flow statements determine which code runs and how often it runs.

Conditional statements

marks = 85

if marks >= 90:
    grade = "A"
elif marks >= 75:
    grade = "B"
elif marks >= 50:
    grade = "C"
else:
    grade = "F"

print(grade)

Loops

for number in range(1, 4):
    print(number)

count = 0
while count < 3:
    print(count)
    count += 1
  • for iterates over an iterable such as a list, string, dictionary, set, or range.
  • while repeats while its condition remains true.
  • break exits the nearest loop.
  • continue skips to the next loop iteration.
  • pass is a placeholder statement that does nothing.

Python also supports a loop else block. It runs only when the loop finishes normally, not when the loop ends through break.

4. Functions and Arguments

A function groups reusable behavior under a name. Functions may accept parameters, return values, and include optional type annotations.

def add(first: int, second: int) -> int:
    return first + second

result = add(5, 3)
print(result)

Type annotations improve readability and can be checked by external tools, but Python does not automatically enforce them at runtime.

Argument types

  • Positional arguments: matched by position.
  • Keyword arguments: matched by parameter name.
  • Default arguments: use a default value when no argument is supplied.
  • *args: collects extra positional arguments into a tuple.
  • **kwargs: collects extra keyword arguments into a dictionary.
def student_info(name, age=18, *subjects, **details):
    print(f"Name: {name}")
    print(f"Age: {age}")
    print(f"Subjects: {subjects}")
    print(f"Details: {details}")

student_info(
    "Asha",
    20,
    "Mathematics",
    "Science",
    city="Delhi",
    grade="A",
)

Avoid mutable default arguments

Default values are evaluated once when a function is defined. Do not use a mutable object such as [] or {} as a default value when each function call should receive a new collection.

def add_item(item, items=None):
    if items is None:
        items = []

    items.append(item)
    return items

print(add_item("book"))
print(add_item("pen"))

5. Python Collections

List, tuple, dictionary, and set comparison
Collection Ordered Mutable Duplicates Typical use
list Yes Yes Allowed A sequence that will change over time
tuple Yes No Allowed Fixed records and unpacking
dict Preserves insertion order Yes Keys must be unique Mapping names or identifiers to values
set No guaranteed order Yes Not allowed Membership tests and set operations

List and tuple example

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")

coordinates = (10, 20)
x, y = coordinates

print(fruits)
print(x, y)

Dictionary and set example

student = {
    "name": "Asha",
    "age": 20,
    "grade": "A",
}

print(student["name"])
print(student.get("city", "Not provided"))

first_set = {1, 2, 3, 4}
second_set = {3, 4, 5, 6}

print(first_set | second_set)  # union
print(first_set & second_set)  # intersection
print(first_set - second_set)  # difference
Note: Do not rely on the display order of a set. Sets are designed for unique values and efficient membership checks, not ordered output.

6. Object-Oriented Programming in Python

Python supports classes, objects, inheritance, polymorphism, composition, and encapsulation. It follows conventions for access control rather than enforcing Java-style private fields.

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

    def describe(self):
        return f"{self.name} is {self.age} years old."


student = Student("Asha", 20)
print(student.describe())

Inheritance and method overriding

class Animal:
    def speak(self):
        return "Animal makes a sound"


class Dog(Animal):
    def speak(self):
        return "Dog barks"


animal = Dog()
print(animal.speak())

Encapsulation in Python

A leading underscore, such as _balance, is a convention meaning “internal use.” A double leading underscore, such as __balance, activates name mangling. It discourages accidental access but does not create absolute privacy.

class BankAccount:
    def __init__(self):
        self.__balance = 0

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive.")

        self.__balance += amount

    @property
    def balance(self):
        return self.__balance


account = BankAccount()
account.deposit(100)
print(account.balance)

Use properties and methods to validate changes rather than exposing every attribute for unrestricted modification.

7. Files and Exception Handling

File handling

Use with when opening a file. It closes the file automatically, including when an exception occurs. Specify an encoding when reading or writing text files.

from pathlib import Path

file_path = Path("example.txt")

file_path.write_text("Hello, Python!", encoding="utf-8")
content = file_path.read_text(encoding="utf-8")

print(content)
Common file modes used with open()
Mode Meaning
"r" Read text; raises an error if the file does not exist.
"w" Write text; creates a file or truncates an existing file.
"a" Append text; creates a file if it does not exist.
"x" Create a new file; raises an error if it already exists.
"b" Binary mode, combined with another mode such as "rb".
"+" Update mode, combined with another mode such as "r+".

Exception handling

from pathlib import Path

try:
    content = Path("data.txt").read_text(encoding="utf-8")
except FileNotFoundError:
    print("The file does not exist.")
except OSError as error:
    print(f"Could not read the file: {error}")
else:
    print(content)
finally:
    print("Read attempt finished.")
  • try contains code that may raise an exception.
  • except handles a specific expected exception.
  • else runs when the try block succeeds.
  • finally normally runs whether an exception occurs or not.
Good practice: catch specific exceptions that your program can handle. Avoid a broad except Exception block unless you can log, report, or recover from the problem appropriately.

8. Modules and Packages

A module is a Python file containing definitions and statements. A package organizes related modules using dotted names such as school.reports.

Using a module

# helpers.py
def greet(name):
    return f"Hello, {name}!"


# main.py
from helpers import greet

if __name__ == "__main__":
    print(greet("Asha"))

The if __name__ == "__main__" guard lets a module be both imported by other code and executed directly as a script.

Packages

A regular package is commonly a directory containing an __init__.py file and one or more modules. Python also supports namespace packages, which are more advanced and do not require the same directory structure.

Import tip: prefer explicit imports such as from helpers import greet. Avoid from module import * in production code because it makes names harder to trace and can create conflicts.

9. Python Standard Library and Ecosystem

Useful standard-library modules

Examples from Python's standard library
Module Typical use
pathlib Object-oriented file-system paths.
datetime Dates, times, and time intervals.
json Encoding and decoding JSON data.
math Mathematical functions and constants.
collections Specialized containers such as Counter and deque.
logging Structured application logging.
random Simulation, games, sampling, and non-security random behavior.
secrets Cryptographically secure tokens and security-sensitive random values.

Third-party ecosystem

Python has widely used third-party packages for numerical computing, data analysis, visualization, web applications, machine learning, testing, automation, and computer vision. Examples include NumPy, pandas, Matplotlib, Django, Flask, FastAPI, Requests, Pillow, and OpenCV.

  • Use a virtual environment to isolate a project's dependencies.
  • Read the official documentation for the exact version you install.
  • Install packages from trusted sources and keep dependencies updated.
  • Use secrets, not random, for passwords, session tokens, or other security-sensitive values.

10. Quick Revision and Practice Questions

Python quick-revision table
Topic Key point
IndentationDefines Python code blocks.
Dynamic typingNames can refer to objects of different types at different times.
==Compares values.
isChecks object identity.
ListOrdered, mutable collection that allows duplicates.
TupleOrdered, immutable collection.
DictionaryMaps unique keys to values.
SetStores unique values without guaranteed order.
withSafely manages resources such as files.
ModuleA Python file that can be imported.

Practice questions

  1. What is the difference between == and is?
    Answer: == compares values, while is checks whether two names refer to the same object.
  2. Why should mutable default arguments usually be avoided?
    Answer: The default object is created once and can be shared by later function calls unexpectedly.
  3. What is the difference between a list and a tuple?
    Answer: Both are ordered collections, but a list is mutable and a tuple is immutable.
  4. What does with open(...) help ensure?
    Answer: It helps ensure that a file is closed when the block finishes, including if an exception occurs.
  5. Which module should be used for security tokens: random or secrets?
    Answer: Use secrets.

Further Reading