0% found this document useful (0 votes)
4 views39 pages

Python Study Guide

This comprehensive study guide covers Python programming topics including file handling, object-oriented programming (OOP) concepts, and GUI programming with Tkinter. It details file opening modes, reading/writing methods, class definitions, and object instantiation, providing examples for clarity. Key concepts such as constructors, attributes, and file attributes are also explained to enhance understanding of Python's capabilities.

Uploaded by

ananyaap378
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views39 pages

Python Study Guide

This comprehensive study guide covers Python programming topics including file handling, object-oriented programming (OOP) concepts, and GUI programming with Tkinter. It details file opening modes, reading/writing methods, class definitions, and object instantiation, providing examples for clarity. Key concepts such as constructors, attributes, and file attributes are also explained to enhance understanding of Python's capabilities.

Uploaded by

ananyaap378
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PYTHON PROGRAMMING

Comprehensive Study Guide


File Handling, OOP Concepts & GUI Programming

Topics Covered: File Modes | File Operations | Classes & Objects | Inheritance | Polymorphism | Tkinter GUI

1. File Opening Modes in Python


Python provides various modes to open files. These modes determine whether the file is opened for
reading, writing, or both, and whether the file is treated as text or binary.

Mode Symbol Description

Read (Text) 'r' Opens file for reading. Error if file doesn't exist. (Default)

Write (Text) 'w' Opens file for writing. Creates file if not exists. Truncates if exists.

Append (Text) 'a' Opens file for appending. Creates if not exists.
Read+Write 'r+' Opens for both reading and writing. File must exist.

Write+Read 'w+' Opens for both reading and writing. Truncates or creates.

Append+Read 'a+' Opens for reading and appending.

Read Binary 'rb' Opens file for reading in binary mode.

Write Binary 'wb' Opens file for writing in binary mode.

Append Binary 'ab' Opens file for appending in binary mode.

Read+Write Binary 'rb+' Opens for reading and writing in binary mode.

Exclusive Create 'x' Creates file. Fails if file already exists.

Examples of Each Mode


'r' - Read Mode
# 'r' mode - Read an existing file
file = open('[Link]', 'r')
content = [Link]()
print(content)
[Link]()

'w' - Write Mode


# 'w' mode - Write to file (creates or truncates)
file = open('[Link]', 'w')
[Link]('Hello, Python!\n')
[Link]('Learning file modes.')
[Link]()
# Creates '[Link]' and writes the content

'a' - Append Mode


# 'a' mode - Append to existing file
file = open('[Link]', 'a')
[Link]('\nThis line is appended.')
[Link]()

'r+' - Read and Write Mode


# 'r+' mode - Read and write without truncating
file = open('[Link]', 'r+')
print([Link]()) # Read existing content
[Link]('\nNew line') # Write at current position
[Link]()

'rb' - Read Binary Mode


# 'rb' mode - Read binary file (e.g., image)
file = open('[Link]', 'rb')
data = [Link]()
print(type(data)) # <class 'bytes'>
[Link]()

'x' - Exclusive Create Mode


# 'x' mode - Create file; fails if it already exists
try:
file = open('[Link]', 'x')
[Link]('Created for the first time!')
[Link]()
except FileExistsError:
print('File already exists!')

2. Using 'with' Statement for File Handling


The 'with' statement in Python is used for resource management. When used with file operations, it
automatically closes the file after the block is executed — even if an exception occurs. This eliminates
the need for explicit [Link]() calls.

Syntax
with open('filename', 'mode') as file_object:
# perform file operations
# file is automatically closed after this block

Advantages
• Automatically closes the file after use.
• Safer: handles exceptions without leaving files open.
• Cleaner and more Pythonic code.

Examples
Example 1: Writing to a File
# Writing using 'with' statement
with open('[Link]', 'w') as f:
[Link]('Alice\n')
[Link]('Bob\n')
[Link]('Charlie\n')
# File is automatically closed here
print('File written and closed successfully.')

Output:
File written and closed successfully.

Example 2: Reading from a File


# Reading using 'with' statement
with open('[Link]', 'r') as f:
content = [Link]()
print(content)
# File is automatically closed

Output:
Alice
Bob
Charlie

Example 3: Reading Line by Line


with open('[Link]', 'r') as f:
for line in f:
print([Link]())

Example 4: Opening Multiple Files


# Open two files at once using 'with'
with open('[Link]', 'r') as infile, open('[Link]', 'w') as outfile:
for line in infile:
[Link]([Link]())
print('Data copied in uppercase.')

Note: The 'with' statement uses Python's context manager protocol (__enter__ and __exit__
methods). When the block exits, __exit__ is called which closes the file.

3. Methods to Read Data from a File


Python provides three main methods to read data from a file:

Method 1: read()
Reads the entire content of the file as a single string.
# Creating sample file first
with open('[Link]', 'w') as f:
[Link]('Line 1: Python\n')
[Link]('Line 2: Programming\n')
[Link]('Line 3: File Handling')

# read() - reads entire file


with open('[Link]', 'r') as f:
content = [Link]()
print(content)
print('Type:', type(content))

Output:
Line 1: Python
Line 2: Programming
Line 3: File Handling
Type: <class 'str'>

You can also specify the number of characters to read:


with open('[Link]', 'r') as f:
partial = [Link](10) # reads first 10 characters
print(partial)

Output:
Line 1: Py

Method 2: readline()
Reads one line at a time from the file. Each call reads the next line.
with open('[Link]', 'r') as f:
line1 = [Link]() # reads first line
line2 = [Link]() # reads second line
print('First line:', line1)
print('Second line:', line2)

Output:
First line: Line 1: Python
Second line: Line 2: Programming

Using readline() in a loop:


with open('[Link]', 'r') as f:
line = [Link]()
while line:
print([Link]())
line = [Link]()

Output:
Line 1: Python
Line 2: Programming
Line 3: File Handling

Method 3: readlines()
Reads all lines and returns them as a list of strings. Each string includes the newline character.
with open('[Link]', 'r') as f:
lines = [Link]()
print(lines)
print('Number of lines:', len(lines))

# Iterating over the list


for i, line in enumerate(lines, 1):
print(f'Line {i}:', [Link]())

Output:
['Line 1: Python\n', 'Line 2: Programming\n', 'Line 3: File Handling']
Number of lines: 3
Line 1: Line 1: Python
Line 2: Line 2: Programming
Line 3: Line 3: File Handling

Comparison Table
Method Returns Best Used For

read() Single string (whole file) Small files, need full content at once

readline() One line at a time (string) Large files, line-by-line processing

readlines() List of all lines When you need all lines in a list
4. Methods to Write Data to a File
Python provides two main methods for writing data to files:

Method 1: write()
Writes a string to the file. It does NOT automatically add a newline character. Returns the number of
characters written.
# Using write() method
with open('[Link]', 'w') as f:
chars = [Link]('Hello, World!') # writes string
print('Characters written:', chars)
[Link]('\n') # manually add newline
[Link]('Python is awesome!\n')
[Link]('File writing is easy.')

Output:
Characters written: 13

Reading back the written content:


with open('[Link]', 'r') as f:
print([Link]())

Output:
Hello, World!
Python is awesome!
File writing is easy.

Method 2: writelines()
Writes a list (or any iterable) of strings to the file at once. Does NOT add newline characters
automatically.
# Using writelines() method
lines = ['First Line\n', 'Second Line\n', 'Third Line\n']

with open('[Link]', 'w') as f:


[Link](lines)

# Read back
with open('[Link]', 'r') as f:
print([Link]())

Output:
First Line
Second Line
Third Line

Example with a list of names:


students = ['Alice', 'Bob', 'Charlie', 'Diana']

# Write with newlines


with open('[Link]', 'w') as f:
[Link](name + '\n' for name in students)

with open('[Link]', 'r') as f:


for line in f:
print([Link]())

Output:
Alice
Bob
Charlie
Diana

Additional Writing Operations


Appending to a File
# Append mode - does not erase existing content
with open('[Link]', 'a') as f:
[Link]('Eve\n')
[Link]('Frank\n')
print('Students added successfully.')

Comparison Table
Method Takes Newline Added? Returns

write(str) A single string No Number of characters written

writelines(iterable) List/iterable of strings No None

5. File Attributes in Python


Once a file is opened, the file object provides several attributes that give information about the file's
state and properties.

Attribute Description

[Link] Returns the name/path of the file

[Link] Returns the mode in which the file was opened

[Link] Returns True if file is closed, False otherwise

[Link] Returns the encoding of the file (text mode only)

[Link]() Returns True if the file can be read

[Link]() Returns True if the file can be written


[Link]() Returns True if the file supports random access (seek)

Example: Demonstrating File Attributes


# Open a file and check its attributes
f = open('[Link]', 'w+')

print('File Name :', [Link]) # [Link]


print('File Mode :', [Link]) # w+
print('File Closed :', [Link]) # False
print('File Encoding:', [Link]) # utf-8
print('Readable :', [Link]()) # True
print('Writable :', [Link]()) # True
print('Seekable :', [Link]()) # True

[Link]()
print('After closing:')
print('File Closed :', [Link]) # True

Output:
File Name : [Link]
File Mode : w+
File Closed : False
File Encoding: utf-8
Readable : True
Writable : True
Seekable : True
After closing:
File Closed : True

Example: Using tell() and seek()


tell() returns current position; seek() moves to a position.
with open('[Link]', 'w+') as f:
[Link]('Hello World')
print('Position after write:', [Link]()) # 11
[Link](0) # move to start
print('Position after seek:', [Link]()) # 0
print('Content:', [Link]())

Output:
Position after write: 11
Position after seek: 0
Content: Hello World

6. What is a Class? Defining a Class in Python


A class is a blueprint or template for creating objects. It defines the properties (attributes) and behaviors
(methods) that the objects of that class will have. Classes are the foundation of Object-Oriented
Programming (OOP).
A class is like a blueprint for a house. The blueprint defines what the house looks like, but the actual
house is the object (instance) created from that blueprint.

Key Concepts
• Class: The blueprint/template
• Object: An instance created from the class
• Attribute: Variables that store data inside a class
• Method: Functions defined inside a class

Syntax for Defining a Class


class ClassName:
# Class variable (shared by all objects)
class_variable = value

# Constructor method
def __init__(self, parameter1, parameter2):
self.attribute1 = parameter1 # instance variable
self.attribute2 = parameter2 # instance variable

# Instance method
def method_name(self):
# method body
pass

Example: Defining a Student Class


class Student:
school = 'ABC High School' # class variable

def __init__(self, name, age, grade):


[Link] = name # instance variable
[Link] = age
[Link] = grade

def display(self):
print(f'Name: {[Link]}')
print(f'Age: {[Link]}')
print(f'Grade: {[Link]}')
print(f'School: {[Link]}')

def get_info(self):
return f'{[Link]} (Grade {[Link]})'

Example: Defining a Rectangle Class


class Rectangle:
def __init__(self, length, width):
[Link] = length
[Link] = width

def area(self):
return [Link] * [Link]

def perimeter(self):
return 2 * ([Link] + [Link])

def display(self):
print(f'Rectangle: {[Link]} x {[Link]}')
print(f'Area: {[Link]()}')
print(f'Perimeter: {[Link]()}')

7. Creating Objects in Python


An object is an instance of a class. Creating an object is called instantiation. When we create an object,
memory is allocated for it and the constructor (__init__) is called automatically.

Syntax for Creating Objects


# Syntax
object_name = ClassName(arguments)

# Accessing attributes
object_name.attribute

# Calling methods
object_name.method_name()

Example 1: Creating Student Objects


class Student:
school = 'ABC High School'

def __init__(self, name, age, grade):


[Link] = name
[Link] = age
[Link] = grade

def display(self):
print(f'Name: {[Link]}, Age: {[Link]}, Grade: {[Link]}')

# Creating objects (instances)


s1 = Student('Alice', 17, 'A')
s2 = Student('Bob', 16, 'B')
s3 = Student('Charlie', 18, 'A+')

# Accessing attributes
print([Link]) # Alice
print([Link]) # 16
print([Link]) # ABC High School

# Calling methods
[Link]()
[Link]()
[Link]()

Output:
Alice
16
ABC High School
Name: Alice, Age: 17, Grade: A
Name: Bob, Age: 16, Grade: B
Name: Charlie, Age: 18, Grade: A+

Example 2: Creating Rectangle Objects


class Rectangle:
def __init__(self, length, width):
[Link] = length
[Link] = width

def area(self):
return [Link] * [Link]

# Creating multiple objects


r1 = Rectangle(10, 5)
r2 = Rectangle(7, 3)

print(f'Rectangle 1 Area: {[Link]()}') # 50


print(f'Rectangle 2 Area: {[Link]()}') # 21

Output:
Rectangle 1 Area: 50
Rectangle 2 Area: 21

Each object has its own copy of instance variables. Changing [Link] does not affect [Link].
Class variables (like school) are shared by all objects.

8. What is a Constructor?
A constructor is a special method that is automatically called when an object is created (instantiated). In
Python, the constructor is defined using the special method __init__(). It is used to initialize the
attributes of an object.
Types of Constructors
• Default Constructor: Takes no parameters (except self).
• Parameterized Constructor: Takes parameters to initialize attributes.

Syntax
class ClassName:
def __init__(self, param1, param2, ...): # Constructor
self.attribute1 = param1
self.attribute2 = param2

'self' refers to the current instance of the class. It must be the first parameter of any method in a class.

Example 1: Default Constructor


class Greeting:
def __init__(self): # Default constructor
[Link] = 'Hello!'
[Link] = 'English'

def display(self):
print([Link], '- Language:', [Link])

obj = Greeting() # No arguments needed


[Link]()

Output:
Hello! - Language: English

Example 2: Parameterized Constructor


class BankAccount:
def __init__(self, holder, account_no, balance=0):
[Link] = holder
self.account_no = account_no
[Link] = balance
print(f'Account created for {[Link]}')

def deposit(self, amount):


[Link] += amount
print(f'Deposited {amount}. Balance: {[Link]}')

def withdraw(self, amount):


if amount <= [Link]:
[Link] -= amount
print(f'Withdrawn {amount}. Balance: {[Link]}')
else:
print('Insufficient funds!')

def display(self):
print(f'Account: {self.account_no}, Holder: {[Link]}, Balance:
{[Link]}')

# Create objects - constructor is called automatically


acc1 = BankAccount('Alice', 'ACC001', 5000)
acc2 = BankAccount('Bob', 'ACC002')

[Link](1000)
[Link](500)
[Link](2000)
[Link]()

Output:
Account created for Alice
Account created for Bob
Deposited 1000. Balance: 6000
Withdrawn 500. Balance: 5500
Deposited 2000. Balance: 2000
Account: ACC001, Holder: Alice, Balance: 5500

9. Inheritance in Python
Inheritance is an OOP concept that allows a class (child/derived class) to inherit properties and
methods from another class (parent/base class). It promotes code reuse and establishes an 'is-a'
relationship.

Syntax
class ParentClass:
# parent class body
pass

class ChildClass(ParentClass): # ChildClass inherits from ParentClass


# child class body
pass

Example: Animal Inheritance


class Animal: # Parent class
def __init__(self, name, sound):
[Link] = name
[Link] = sound

def speak(self):
print(f'{[Link]} says {[Link]}!')

def eat(self):
print(f'{[Link]} is eating.')
class Dog(Animal): # Child class inherits Animal
def __init__(self, name):
super().__init__(name, 'Woof')
[Link] = []

def learn_trick(self, trick):


[Link](trick)
print(f'{[Link]} learned: {trick}')

def show_tricks(self):
print(f'{[Link]} can do: {[Link]}')

class Cat(Animal): # Another child class


def __init__(self, name, indoor):
super().__init__(name, 'Meow')
[Link] = indoor

def info(self):
status = 'indoor' if [Link] else 'outdoor'
print(f'{[Link]} is an {status} cat.')

# Creating objects
dog = Dog('Buddy')
cat = Cat('Whiskers', True)

[Link]() # inherited from Animal


[Link]() # inherited from Animal
dog.learn_trick('Sit')
dog.learn_trick('Shake')
dog.show_tricks()

[Link]() # inherited from Animal


[Link]() # own method

Output:
Buddy says Woof!
Buddy is eating.
Buddy learned: Sit
Buddy learned: Shake
Buddy can do: ['Sit', 'Shake']
Whiskers says Meow!
Whiskers is an indoor cat.

Key Points
• Use super() to call the parent class constructor or methods.
• Child class inherits all public and protected attributes and methods.
• Child class can add its own attributes and methods.
• Child class can override parent methods.
• isinstance(obj, Class) checks if an object is an instance.
10. Overriding Superclass Constructor and Method
Method overriding occurs when a child class provides its own implementation of a method already
defined in the parent class. The child's version replaces the parent's version for that object.

Example 1: Overriding a Method


class Shape:
def __init__(self, color='black'):
[Link] = color

def area(self):
return 0

def display(self):
print(f'Shape: {self.__class__.__name__}, Color: {[Link]}')
print(f'Area: {[Link]()}')

class Circle(Shape):
def __init__(self, radius, color='red'): # Override constructor
super().__init__(color) # Call parent constructor
[Link] = radius

def area(self): # Override method


return 3.14159 * [Link] ** 2

class Rectangle(Shape):
def __init__(self, length, width, color='blue'): # Override constructor
super().__init__(color)
[Link] = length
[Link] = width

def area(self): # Override method


return [Link] * [Link]

# Testing
s = Shape()
c = Circle(7)
r = Rectangle(5, 3)

[Link]()
print('---')
[Link]()
print('---')
[Link]()

Output:
Shape: Shape, Color: black
Area: 0
---
Shape: Circle, Color: red
Area: 153.93791
---
Shape: Rectangle, Color: blue
Area: 15

Example 2: Calling Parent Method Using super()


class Employee:
def __init__(self, name, salary):
[Link] = name
[Link] = salary

def display(self):
print(f'Name: {[Link]}, Salary: {[Link]}')

class Manager(Employee):
def __init__(self, name, salary, department):
super().__init__(name, salary) # Call parent __init__
[Link] = department

def display(self): # Override display


super().display() # Call parent display first
print(f'Department: {[Link]}')

emp = Employee('Alice', 50000)


mgr = Manager('Bob', 80000, 'IT')

[Link]()
print('---')
[Link]()

Output:
Name: Alice, Salary: 50000
---
Name: Bob, Salary: 80000
Department: IT

11. Multi-level Inheritance


In multi-level inheritance, a class inherits from a class that itself inherits from another class, forming a
chain. This creates a hierarchy of three or more levels.
# Chain: GrandParent → Parent → Child
class GrandParent:
pass

class Parent(GrandParent):
pass
class Child(Parent):
pass

Example: Vehicle Hierarchy


class Vehicle: # Level 1 (Grandparent)
def __init__(self, brand, speed):
[Link] = brand
[Link] = speed

def move(self):
print(f'{[Link]} is moving at {[Link]} km/h')

def stop(self):
print(f'{[Link]} has stopped.')

class Car(Vehicle): # Level 2 (Parent)


def __init__(self, brand, speed, fuel_type):
super().__init__(brand, speed)
self.fuel_type = fuel_type

def honk(self):
print(f'{[Link]} goes Beep Beep!')

def fuel_info(self):
print(f'Fuel: {self.fuel_type}')

class ElectricCar(Car): # Level 3 (Child)


def __init__(self, brand, speed, battery_capacity):
super().__init__(brand, speed, 'Electric')
self.battery_capacity = battery_capacity

def charge(self):
print(f'{[Link]} is charging. Battery: {self.battery_capacity} kWh')

def display_all(self):
print(f'Brand: {[Link]}')
print(f'Speed: {[Link]} km/h')
self.fuel_info()
print(f'Battery: {self.battery_capacity} kWh')

# Create object of deepest level


tesla = ElectricCar('Tesla', 250, 100)

[Link]() # from Vehicle (level 1)


[Link]() # from Car (level 2)
[Link]() # own method (level 3)
[Link]() # from Vehicle (level 1)
tesla.display_all()

Output:
Tesla is moving at 250 km/h
Tesla goes Beep Beep!
Tesla is charging. Battery: 100 kWh
Tesla has stopped.
Brand: Tesla
Speed: 250 km/h
Fuel: Electric
Battery: 100 kWh

In multi-level inheritance, each child class can access ALL methods and attributes from ALL
ancestors in the chain. Python's MRO (Method Resolution Order) determines which method is used
when there's a conflict.

12. Multiple Inheritance in Python


Multiple inheritance allows a class to inherit from more than one parent class. The child class inherits all
attributes and methods from all parent classes.
class ClassA:
pass

class ClassB:
pass

class ClassC(ClassA, ClassB): # Inherits from both A and B


pass

Example: Multiple Inheritance


class Flyable:
def fly(self):
print(f'{[Link]} is flying at {self.fly_speed} km/h')

class Swimmable:
def swim(self):
print(f'{[Link]} is swimming at {self.swim_speed} km/h')

class Duck(Flyable, Swimmable): # Multiple inheritance


def __init__(self, name):
[Link] = name
self.fly_speed = 80
self.swim_speed = 10

def quack(self):
print(f'{[Link]} says Quack!')

donald = Duck('Donald')
[Link]() # from Flyable
[Link]() # from Swimmable
[Link]() # own method

# Check inheritance
print(isinstance(donald, Flyable)) # True
print(isinstance(donald, Swimmable)) # True

Output:
Donald is flying at 80 km/h
Donald is swimming at 10 km/h
Donald says Quack!
True
True

MRO - Method Resolution Order


When multiple parent classes have the same method, Python uses MRO (C3 Linearization) to
determine which method to call.
class A:
def greet(self):
print('Hello from A')

class B(A):
def greet(self):
print('Hello from B')

class C(A):
def greet(self):
print('Hello from C')

class D(B, C): # Multiple inheritance


pass

d = D()
[Link]() # Uses MRO
print(D.__mro__) # Shows resolution order

Output:
Hello from B
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class
'__main__.A'>, <class 'object'>)

13. Multipath Inheritance (Diamond Problem)


Multipath inheritance occurs when a class inherits from two classes that both inherit from the same
base class, creating a diamond-shaped inheritance structure.
A (Base)
/ \
B C
\ /
D (inherits from both B and C, which both inherit from A)

Example: Diamond Inheritance


class Animal: # Base class (A)
def __init__(self, name):
[Link] = name
print(f'Animal.__init__: {name}')

def breathe(self):
print(f'{[Link]} is breathing.')

class Mammal(Animal): # B inherits from A


def __init__(self, name):
super().__init__(name)
print(f'Mammal.__init__: {name}')

def feed_milk(self):
print(f'{[Link]} feeds milk to young.')

class WingedAnimal(Animal): # C inherits from A


def __init__(self, name):
super().__init__(name)
print(f'WingedAnimal.__init__: {name}')

def flap_wings(self):
print(f'{[Link]} flaps wings.')

class Bat(Mammal, WingedAnimal): # D inherits from both B and C


def __init__(self, name):
super().__init__(name) # MRO handles init chain
print(f'Bat.__init__: {name}')

bat = Bat('Bruce')
print()
[Link]() # from Animal
bat.feed_milk() # from Mammal
bat.flap_wings() # from WingedAnimal
print()
print('MRO:', [cls.__name__ for cls in Bat.__mro__])

Output:
Animal.__init__: Bruce
WingedAnimal.__init__: Bruce
Mammal.__init__: Bruce
Bat.__init__: Bruce

Bruce is breathing.
Bruce feeds milk to young.
Bruce flaps wings.

MRO: ['Bat', 'Mammal', 'WingedAnimal', 'Animal', 'object']

Python's super() with MRO ensures Animal.__init__ is called only ONCE even in the diamond
problem. Without super(), it could be called multiple times.

14. Polymorphism in Python


Polymorphism means 'many forms'. In OOP, it allows objects of different classes to be treated as
objects of a common type, and allows the same operation to behave differently on different objects.

Types of Polymorphism
Type Description

Method Overriding Child class redefines a method from parent class

Method Overloading Same method name with different parameters (limited in Python)

Duck Typing Objects used based on their behavior, not their type

Operator Overloading Operators like + work differently for different types

Example 1: Polymorphism via Method Overriding


class Shape:
def area(self):
return 0

def describe(self):
print(f'I am a {self.__class__.__name__} with area {[Link]():.2f}')

class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return 3.14 * self.r ** 2

class Rectangle(Shape):
def __init__(self, l, w): self.l, self.w = l, w
def area(self): return self.l * self.w

class Triangle(Shape):
def __init__(self, b, h): self.b, self.h = b, h
def area(self): return 0.5 * self.b * self.h

# Polymorphic behavior
shapes = [Circle(7), Rectangle(4, 5), Triangle(6, 8)]

for shape in shapes:


[Link]() # same method call, different behavior
Output:
I am a Circle with area 153.86
I am a Rectangle with area 20.00
I am a Triangle with area 24.00

Example 2: Duck Typing


class Dog:
def speak(self): return 'Woof!'

class Cat:
def speak(self): return 'Meow!'

class Parrot:
def speak(self): return 'Hello!'

# Same function works with any object that has .speak()


def make_noise(animal):
print([Link]())

animals = [Dog(), Cat(), Parrot()]


for a in animals:
make_noise(a) # polymorphic

Output:
Woof!
Meow!
Hello!

Example 3: Operator Overloading


class Point:
def __init__(self, x, y):
self.x, self.y = x, y

def __add__(self, other): # overload +


return Point(self.x + other.x, self.y + other.y)

def __str__(self):
return f'Point({self.x}, {self.y})'

p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3) # Point(4, 6)

Output:
Point(4, 6)

15. Method Overloading and Overriding


Method Overloading
Method overloading means defining multiple methods with the same name but different parameters.
Python does NOT support traditional method overloading like Java/C++. The last definition replaces
earlier ones. However, we can simulate it using default arguments or *args.
class Calculator:
# Simulating overloading with default arguments
def add(self, a, b=0, c=0):
return a + b + c

# Simulating overloading with *args


def multiply(self, *args):
result = 1
for num in args:
result *= num
return result

calc = Calculator()
print([Link](5)) # One argument: 5
print([Link](5, 3)) # Two arguments: 8
print([Link](5, 3, 2)) # Three arguments: 10
print([Link](2, 3)) # 6
print([Link](2, 3, 4)) # 24
print([Link](1, 2, 3, 4)) # 24

Output:
5
8
10
6
24
24

Method Overriding
Method overriding occurs when a child class defines a method with the same name as a method in the
parent class. The child's version overrides the parent's version.
class Animal:
def __init__(self, name):
[Link] = name

def sound(self):
print(f'{[Link]} makes a generic sound.')

def info(self):
print(f'Animal: {[Link]}')

class Dog(Animal):
def sound(self): # Override
print(f'{[Link]} says: Woof!')

class Cat(Animal):
def sound(self): # Override
print(f'{[Link]} says: Meow!')

class Lion(Animal):
def sound(self): # Override
print(f'{[Link]} says: ROAR!')

def info(self): # Override info too


super().info() # Call parent first
print('I am the king of the jungle!')

# Testing
animals = [Animal('Generic'), Dog('Rex'), Cat('Kitty'), Lion('Simba')]

for animal in animals:


[Link]()

print()
Lion('Simba').info()

Output:
Generic makes a generic sound.
Rex says: Woof!
Kitty says: Meow!
Simba says: ROAR!

Animal: Simba
I am the king of the jungle!

Feature Overloading Overriding

Definition Same name, different parameters Same name, same parameters

Where Within same class Between parent and child class

Python Support Simulated (not native) Fully supported

Purpose Handle different arg types/counts Customize inherited behavior

16. Creating a GUI Application in Python


Python uses the tkinter library (built-in) for creating GUI (Graphical User Interface) applications. Tkinter
provides widgets like buttons, labels, text fields, and more.

Steps to Create a GUI Application


• Step 1: Import the tkinter module
• Step 2: Create the main window (root)
• Step 3: Set window properties (title, size, etc.)
• Step 4: Create and configure widgets
• Step 5: Place widgets using layout managers (pack, grid, place)
• Step 6: Bind events/commands to widgets
• Step 7: Start the main event loop

Example: Simple Calculator GUI


import tkinter as tk
from tkinter import messagebox

# Step 1 & 2: Create main window


root = [Link]()

# Step 3: Set window properties


[Link]('Simple Calculator')
[Link]('300x200')
[Link](False, False)
[Link](bg='#f0f0f0')

# Step 4 & 6: Create widgets and bind events


[Link](root, text='Number 1:', bg='#f0f0f0').grid(row=0, column=0, padx=10,
pady=10)
entry1 = [Link](root)
[Link](row=0, column=1, padx=10)

[Link](root, text='Number 2:', bg='#f0f0f0').grid(row=1, column=0, padx=10,


pady=10)
entry2 = [Link](root)
[Link](row=1, column=1, padx=10)

result_var = [Link]()
[Link](root, text='Result:', bg='#f0f0f0').grid(row=2, column=0, padx=10)
[Link](root, textvariable=result_var, bg='white', width=15).grid(row=2, column=1,
padx=10)

def calculate(op):
try:
a = float([Link]())
b = float([Link]())
if op == '+': result_var.set(a + b)
elif op == '-': result_var.set(a - b)
elif op == '*': result_var.set(a * b)
elif op == '/':
if b == 0:
[Link]('Error', 'Cannot divide by zero!')
else:
result_var.set(a / b)
except ValueError:
[Link]('Error', 'Enter valid numbers!')

btn_frame = [Link](root, bg='#f0f0f0')


btn_frame.grid(row=3, column=0, columnspan=2, pady=10)

for op in ['+', '-', '*', '/']:


[Link](btn_frame, text=op, width=5, command=lambda o=op:
calculate(o)).pack(side=[Link], padx=5)

# Step 7: Start event loop


[Link]()
Note: [Link]() keeps the application running and listens for events like button clicks. It must
always be the last line.

17. Creating a Button Widget and Binding to Event Handler


A Button widget in tkinter is a clickable widget that triggers an action when pressed. Event handlers are
functions that are called when events (like a click) occur.

Button Syntax
button = [Link](parent, option=value, ...)

# Common options:
# text - label on the button
# command - function to call when clicked
# width - button width in characters
# height - button height in lines
# bg/fg - background/foreground color
# font - font settings
# state - NORMAL, DISABLED, ACTIVE
# relief - RAISED, SUNKEN, FLAT, GROOVE, RIDGE
# cursor - mouse cursor shape on hover
# padx/pady - internal padding
# bd - border width

Methods of Binding
Method 1: Using command parameter
import tkinter as tk

root = [Link]()
[Link]('Button Demo')

count = [0] # Using list for mutable counter

def on_click():
count[0] += 1
[Link](text=f'Clicked {count[0]} times!')

label = [Link](root, text='Click the button!', font=('Arial', 14))


[Link](pady=20)

btn = [Link](root,
text='Click Me',
command=on_click, # Bind event handler
bg='#4CAF50',
fg='white',
font=('Arial', 12, 'bold'),
padx=20, pady=10,
relief=[Link],
cursor='hand2')
[Link](pady=10)

[Link]()

Method 2: Using bind() for Mouse/Keyboard Events


import tkinter as tk

root = [Link]()
[Link]('Bind Example')

def left_click(event):
[Link](text='Left button clicked!')

def right_click(event):
[Link](text='Right button clicked!')

def double_click(event):
[Link](text='Double clicked!')

label = [Link](root, text='Click the button below', font=('Arial', 12))


[Link](pady=20)

btn = [Link](root, text='Try Me', width=15, height=2)


[Link](pady=10)

[Link]('<Button-1>', left_click) # Left click


[Link]('<Button-3>', right_click) # Right click
[Link]('<Double-Button-1>', double_click) # Double click

[Link]()

Method 3: Using lambda for Inline Commands


import tkinter as tk

root = [Link]()

for color in ['Red', 'Green', 'Blue']:


[Link](root,
text=color,
bg=[Link](),
fg='white',
command=lambda c=color: print(f'{c} clicked!') # lambda
).pack(side=[Link], padx=5, pady=10)

[Link]()

18. Widgets Used in Python (Tkinter)


Tkinter provides a rich set of widgets for building GUI applications. Here is a comprehensive list with
explanations and examples.

Widget Purpose

Label Display text or images (non-interactive)

Button Clickable widget that triggers actions

Entry Single-line text input field

Text Multi-line text area

Frame Container to group widgets

Canvas Drawing area for shapes, images, custom widgets

Checkbutton Toggle checkbox (on/off)

Radiobutton Select one option from a group


Listbox Scrollable list of selectable items

Scrollbar Scroll other widgets

Scale Slider for selecting numeric values

Spinbox Numeric input with up/down arrows

OptionMenu Drop-down selection menu

Menu Application menu bar

Menubutton Button that opens a menu

Message Multi-line label with word wrapping

LabelFrame Frame with a label/title

PanedWindow Resizable panes

Toplevel Additional top-level windows

PhotoImage Image display widget

Example: All Common Widgets Demonstrated


import tkinter as tk
from tkinter import ttk

root = [Link]()
[Link]('Widget Demo')
[Link]('400x600')

# 1. Label
lbl = [Link](root, text='Label Widget', font=('Arial', 12, 'bold'), fg='blue')
[Link](pady=5)

# 2. Entry
entry = [Link](root, width=30)
[Link](0, 'Type here...')
[Link](pady=5)

# 3. Button
btn = [Link](root, text='Click Me', bg='green', fg='white',
command=lambda: [Link](text=[Link]()))
[Link](pady=5)

# 4. Checkbutton
var = [Link]()
chk = [Link](root, text='Accept Terms', variable=var)
[Link](pady=5)

# 5. Radiobutton
radio_var = [Link](value='Python')
for lang in ['Python', 'Java', 'C++']:
[Link](root, text=lang, variable=radio_var, value=lang).pack()

# 6. Scale
scale = [Link](root, from_=0, to=100, orient=[Link], label='Volume')
[Link](pady=5)

# 7. Listbox
listbox = [Link](root, height=4)
for item in ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry']:
[Link]([Link], item)
[Link](pady=5)

# 8. Spinbox
spinbox = [Link](root, from_=1, to=10, width=10)
[Link](pady=5)

# 9. Text
text = [Link](root, height=4, width=40)
[Link]('1.0', 'Multi-line text area\nType here...')
[Link](pady=5)

# 10. OptionMenu
opt_var = [Link](value='Select Color')
option = [Link](root, opt_var, 'Red', 'Green', 'Blue', 'Yellow')
[Link](pady=5)

[Link]()

19. Specific Widgets Explained with Examples

i) Message Widget
The Message widget is similar to Label but displays multi-line text with automatic word wrapping. It's
useful for displaying longer messages.
import tkinter as tk

root = [Link]()
[Link]('Message Widget')

msg = [Link](root,
text='This is a Message widget. It automatically wraps long text '
'to fit within the specified width. It is useful for notices.',
width=250,
bg='lightyellow',
font=('Arial', 11),
relief=[Link],
padx=10, pady=10)
[Link](padx=20, pady=20)

[Link]()

ii) Entry Widget


The Entry widget provides a single-line text input field. It's used for user input like names, passwords,
search fields, etc.
import tkinter as tk

root = [Link]()
[Link]('Entry Widget Demo')

[Link](root, text='Username:').grid(row=0, column=0, padx=10, pady=10)


username = [Link](root, width=25)
[Link](row=0, column=1, pady=10)

[Link](root, text='Password:').grid(row=1, column=0, padx=10)


password = [Link](root, width=25, show='*') # show='*' for password
[Link](row=1, column=1)

result = [Link](root, text='')


[Link](row=3, column=0, columnspan=2)

def submit():
u = [Link]()
p = [Link]()
[Link](text=f'Welcome, {u}!' if u else 'Enter username!')

[Link](root, text='Login', command=submit).grid(row=2, column=0, columnspan=2,


pady=10)

# Entry methods:
# [Link]() - get text
# [Link](0, END) - clear text
# [Link](0, txt) - insert text

[Link]()
iii) Spinbox Widget
The Spinbox widget allows users to select a value from a range or list by clicking up/down arrows or
typing a value.
import tkinter as tk

root = [Link]()
[Link]('Spinbox Widget Demo')

# Numeric range spinbox


[Link](root, text='Age:').grid(row=0, column=0, padx=10, pady=10)
age_spin = [Link](root, from_=1, to=100, width=10, font=('Arial', 12))
age_spin.grid(row=0, column=1, pady=10)

# Values from a list


[Link](root, text='Month:').grid(row=1, column=0, padx=10)
months = ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')
month_spin = [Link](root, values=months, width=10, state='readonly')
month_spin.grid(row=1, column=1)

def show_values():
print(f'Age: {age_spin.get()}, Month: {month_spin.get()}')

[Link](root, text='Get Values', command=show_values).grid(row=2, column=0,


columnspan=2, pady=10)

[Link]()

iv) Text Widget (Textbox)


The Text widget provides a multi-line area for text input and display. It's much more powerful than Entry
and supports formatted text, tags, and images.
import tkinter as tk

root = [Link]()
[Link]('Text Widget Demo')

# Create Text widget with Scrollbar


frame = [Link](root)
[Link](padx=10, pady=10)

scrollbar = [Link](frame)
[Link](side=[Link], fill=tk.Y)

text = [Link](frame, width=40, height=10,


yscrollcommand=[Link],
font=('Courier New', 11))
[Link](side=[Link])
[Link](command=[Link])

# Insert initial content


[Link]('1.0', 'Welcome to Text Widget!\n')
[Link]([Link], 'You can type multiple lines here.\n')
# Tagging for color formatting
text.tag_configure('bold', font=('Arial', 11, 'bold'))
text.tag_configure('red', foreground='red')
[Link]([Link], 'This is bold and red.\n', ('bold', 'red'))

def get_content():
content = [Link]('1.0', [Link]) # get all text
print(content)

[Link](root, text='Get Content', command=get_content).pack(pady=5)

[Link]()

v) Label Widget
The Label widget displays text or images. It is static (non-interactive) and used for informational display.
import tkinter as tk

root = [Link]()
[Link]('Label Demo')

# Basic label
lbl1 = [Link](root, text='Simple Label')
[Link](pady=5)

# Styled label
lbl2 = [Link](root,
text='Styled Label',
font=('Arial', 14, 'bold'),
fg='white',
bg='#2196F3',
padx=20, pady=10,
relief=[Link],
bd=3)
[Link](pady=10)

# Dynamic label with StringVar


var = [Link](value='Dynamic: 0')
lbl3 = [Link](root, textvariable=var, font=('Arial', 12))
[Link](pady=5)

count = [0]
def update():
count[0] += 1
[Link](f'Dynamic: {count[0]}')

[Link](root, text='Update Label', command=update).pack(pady=5)

[Link]()

vi) Checkbutton (Checkbox) Widget


The Checkbutton widget creates a checkbox that can be toggled on or off. It is linked to a variable
(BooleanVar or IntVar) that holds its state.
import tkinter as tk

root = [Link]()
[Link]('Checkbutton Demo')

# Create variables for checkboxes


python_var = [Link]()
java_var = [Link]()
cpp_var = [Link]()

[Link](root, text='Select Languages:', font=('Arial', 12, 'bold')).pack(pady=10)

chk1 = [Link](root, text='Python', variable=python_var,


onvalue=True, offvalue=False)
[Link](anchor='w', padx=30)

chk2 = [Link](root, text='Java', variable=java_var)


[Link](anchor='w', padx=30)

chk3 = [Link](root, text='C++', variable=cpp_var)


[Link](anchor='w', padx=30)

result_lbl = [Link](root, text='')


result_lbl.pack(pady=10)

def show_selected():
selected = []
if python_var.get(): [Link]('Python')
if java_var.get(): [Link]('Java')
if cpp_var.get(): [Link]('C++')
result_lbl.config(text='Selected: ' + ', '.join(selected) if selected else
'None selected')

[Link](root, text='Show Selected', command=show_selected).pack(pady=10)

[Link]()

vii) Radiobutton Widget


The Radiobutton widget allows selecting exactly one option from a group. All radio buttons in a group
share the same variable.
import tkinter as tk

root = [Link]()
[Link]('Radiobutton Demo')

# Single variable for the group


gender_var = [Link](value='Male')

[Link](root, text='Select Gender:', font=('Arial', 12, 'bold')).pack(pady=10)


for gender in ['Male', 'Female', 'Other']:
rb = [Link](root,
text=gender,
variable=gender_var,
value=gender,
font=('Arial', 11))
[Link](anchor='w', padx=30)

# Size group (integer values)


size_var = [Link](value=2)
[Link](root, text='\nSelect Size:', font=('Arial', 12, 'bold')).pack()
sizes = [('Small', 1), ('Medium', 2), ('Large', 3)]
for text, value in sizes:
[Link](root, text=text, variable=size_var,
value=value).pack(anchor='w', padx=30)

result_lbl = [Link](root, text='')


result_lbl.pack(pady=10)

def show_selection():
size_names = {1: 'Small', 2: 'Medium', 3: 'Large'}
result_lbl.config(text=f'Gender: {gender_var.get()}, Size:
{size_names[size_var.get()]}')

[Link](root, text='Submit', command=show_selection).pack(pady=5)

[Link]()

20. Arranging Widgets Using Layout Managers


Layout managers in tkinter control how widgets are positioned and sized within a window or frame.
Python provides three layout managers: pack(), grid(), and place().

1. pack() Layout Manager


pack() arranges widgets in a block, packing them against a side (top, bottom, left, right).
# Pack options:
# side - TOP (default), BOTTOM, LEFT, RIGHT
# fill - NONE, X, Y, BOTH
# expand - True/False (expand to fill space)
# padx - horizontal outer padding
# pady - vertical outer padding
# ipadx - horizontal inner padding
# ipady - vertical inner padding
# anchor - N, S, E, W, NE, NW, SE, SW, CENTER

import tkinter as tk

root = [Link]()
[Link]('pack() Demo')
[Link]('300x200')

[Link](root, text='TOP', bg='red', fg='white').pack(side=[Link], fill=tk.X)


[Link](root, text='BOTTOM', bg='blue', fg='white').pack(side=[Link],
fill=tk.X)
[Link](root, text='LEFT', bg='green', fg='white').pack(side=[Link], fill=tk.Y)
[Link](root, text='RIGHT', bg='orange').pack(side=[Link], fill=tk.Y)
[Link](root, text='CENTER', bg='purple', fg='white').pack(expand=True)

[Link]()

2. grid() Layout Manager


grid() places widgets in a row-column table format. This is the most precise and commonly used
manager.
# Grid options:
# row - row number (0-indexed)
# column - column number (0-indexed)
# rowspan - span multiple rows
# columnspan - span multiple columns
# padx/pady - outer padding
# ipadx/ipady - inner padding
# sticky - N, S, E, W, NE, NW, SE, SW (anchoring)

import tkinter as tk

root = [Link]()
[Link]('grid() Demo - Login Form')

[Link](root, text='Login Form', font=('Arial', 14, 'bold')).grid(


row=0, column=0, columnspan=2, pady=15)

[Link](root, text='Username:').grid(row=1, column=0, padx=10, sticky='e')


[Link](root, width=20).grid(row=1, column=1, padx=10)

[Link](root, text='Password:').grid(row=2, column=0, padx=10, pady=10,


sticky='e')
[Link](root, width=20, show='*').grid(row=2, column=1, padx=10)

[Link](root, text='Login', bg='blue', fg='white', width=10).grid(


row=3, column=0, pady=10)
[Link](root, text='Cancel', width=10).grid(row=3, column=1)

[Link]()

3. place() Layout Manager


place() positions widgets using absolute or relative coordinates. Gives full control but is not responsive.
# Place options:
# x, y - absolute pixel coordinates
# relx, rely - relative (0.0 to 1.0)
# width, height - absolute size
# relwidth, relheight - relative size
# anchor - which part of widget is at (x,y)

import tkinter as tk

root = [Link]()
[Link]('place() Demo')
[Link]('300x200')

# Absolute positioning
[Link](root, text='Absolute Position', bg='yellow').place(x=50, y=30)
[Link](root, text='Btn1').place(x=50, y=60)

# Relative positioning (center of window)


[Link](root, text='Relative Center', bg='lightblue').place(
relx=0.5, rely=0.5, anchor=[Link])

[Link]()

Feature pack() grid() place()

Positioning Sequential (sides) Row/Column table Exact coordinates

Ease Easy Medium Precise but complex

Responsiven Good Good Poor (fixed coords)


ess

Best For Simple layouts Forms, structured Custom positions


UI

Mixing Don't mix with Don't mix with pack Can combine with
grid others

NEVER mix pack() and grid() in the same container (Frame/window). They conflict. place()
can be used alongside either.

21. Listbox Widget and selectmode Options


A Listbox widget displays a list of items that users can select. It supports scrolling, single or multiple
selections, and can be linked with a Scrollbar.

Creating a Listbox
# Syntax
listbox = [Link](parent, option=value, ...)

# Common options:
# height - number of visible lines
# width - width in characters
# selectmode - selection type
# bg/fg - colors
# font - font settings
# selectbackground - color of selected item
# activestyle - style of active item
# relief - border style
# yscrollcommand - link to scrollbar

selectmode Options
selectmode Description Behavior

SINGLE Select exactly one item Clicking selects one; previous selection cleared

BROWSE Select one with mouse drag Selection follows mouse drag

MULTIPLE Select many (click each) Click toggles selection; Ctrl not needed
EXTENDED Select range with Shift/Ctrl Supports Shift+click for range, Ctrl+click for multi

Complete Example
import tkinter as tk
from tkinter import messagebox

root = [Link]()
[Link]('Listbox Demo')
[Link]('400x450')

[Link](root, text='Listbox Widget Demo',


font=('Arial', 14, 'bold')).pack(pady=10)

# --- SINGLE selection ---


[Link](root, text='SINGLE select (pick one):',
font=('Arial', 10, 'bold')).pack(anchor='w', padx=20)

single_lb = [Link](root, height=4, selectmode=[Link],


bg='lightyellow', selectbackground='#2196F3',
selectforeground='white', font=('Arial', 11))
for fruit in ['Apple', 'Banana', 'Cherry', 'Date']:
single_lb.insert([Link], fruit)
single_lb.pack(padx=20, fill=tk.X)

# --- EXTENDED selection (with Scrollbar) ---


[Link](root, text='EXTENDED select (Shift/Ctrl+Click):',
font=('Arial', 10, 'bold')).pack(anchor='w', padx=20, pady=(10,0))

frame = [Link](root)
[Link](padx=20, fill=tk.X)

scrollbar = [Link](frame, orient=[Link])


[Link](side=[Link], fill=tk.Y)
ext_lb = [Link](frame, height=5, selectmode=[Link],
yscrollcommand=[Link],
bg='lightcyan', font=('Arial', 11))
cities = ['Mumbai', 'Delhi', 'Bangalore', 'Chennai', 'Kolkata',
'Hyderabad', 'Pune', 'Ahmedabad', 'Jaipur', 'Surat']
for city in cities:
ext_lb.insert([Link], city)
ext_lb.pack(side=[Link], fill=tk.X, expand=True)
[Link](command=ext_lb.yview)

result_lbl = [Link](root, text='', font=('Arial', 11), wraplength=350)


result_lbl.pack(pady=10)

def show_selection():
# Single Listbox
s_sel = single_lb.curselection()
s_item = single_lb.get(s_sel[0]) if s_sel else 'None'

# Extended Listbox
e_sel = ext_lb.curselection()
e_items = [ext_lb.get(i) for i in e_sel]

result_lbl.config(text=f'Fruit: {s_item}\nCities: {", ".join(e_items) or


"None"}')

def add_item():
ext_lb.insert([Link], 'New City')

def delete_item():
sel = ext_lb.curselection()
for i in reversed(sel): # delete in reverse to maintain indices
ext_lb.delete(i)

btn_frame = [Link](root)
btn_frame.pack(pady=5)

[Link](btn_frame, text='Show Selection', command=show_selection,


bg='green', fg='white').pack(side=[Link], padx=5)
[Link](btn_frame, text='Add Item', command=add_item,
bg='blue', fg='white').pack(side=[Link], padx=5)
[Link](btn_frame, text='Delete Selected', command=delete_item,
bg='red', fg='white').pack(side=[Link], padx=5)

[Link]()

Common Listbox Methods


Method Description

insert(index, item) Insert item at index (use END for last)

delete(first, last) Delete items from first to last

get(first, last) Get items in the range

curselection() Returns tuple of selected indices


size() Returns total number of items

see(index) Scrolls to make index visible

selection_set(first, last) Select items programmatically

selection_clear(first, last) Deselect items

You might also like