Python Study Guide
Python Study Guide
Topics Covered: File Modes | File Operations | Classes & Objects | Inheritance | Polymorphism | Tkinter GUI
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.
Read+Write Binary 'rb+' Opens for reading and writing in binary mode.
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.
Output:
Alice
Bob
Charlie
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.
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')
Output:
Line 1: Python
Line 2: Programming
Line 3: File Handling
Type: <class 'str'>
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
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))
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
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
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']
# Read back
with open('[Link]', 'r') as f:
print([Link]())
Output:
First Line
Second Line
Third Line
Output:
Alice
Bob
Charlie
Diana
Comparison Table
Method Takes Newline Added? Returns
Attribute Description
[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
Output:
Position after write: 11
Position after seek: 0
Content: Hello World
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
# 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
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]})'
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]()}')
# Accessing attributes
object_name.attribute
# Calling methods
object_name.method_name()
def display(self):
print(f'Name: {[Link]}, Age: {[Link]}, Grade: {[Link]}')
# 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+
def area(self):
return [Link] * [Link]
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.
def display(self):
print([Link], '- Language:', [Link])
Output:
Hello! - Language: English
def display(self):
print(f'Account: {self.account_no}, Holder: {[Link]}, Balance:
{[Link]}')
[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
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 show_tricks(self):
print(f'{[Link]} can do: {[Link]}')
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)
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.
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
class Rectangle(Shape):
def __init__(self, length, width, color='blue'): # Override constructor
super().__init__(color)
[Link] = length
[Link] = width
# 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
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
[Link]()
print('---')
[Link]()
Output:
Name: Alice, Salary: 50000
---
Name: Bob, Salary: 80000
Department: IT
class Parent(GrandParent):
pass
class Child(Parent):
pass
def move(self):
print(f'{[Link]} is moving at {[Link]} km/h')
def stop(self):
print(f'{[Link]} has stopped.')
def honk(self):
print(f'{[Link]} goes Beep Beep!')
def fuel_info(self):
print(f'Fuel: {self.fuel_type}')
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')
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.
class ClassB:
pass
class Swimmable:
def swim(self):
print(f'{[Link]} is swimming at {self.swim_speed} km/h')
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
class B(A):
def greet(self):
print('Hello from B')
class C(A):
def greet(self):
print('Hello from C')
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'>)
def breathe(self):
print(f'{[Link]} is breathing.')
def feed_milk(self):
print(f'{[Link]} feeds milk to young.')
def flap_wings(self):
print(f'{[Link]} flaps wings.')
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.
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.
Types of Polymorphism
Type Description
Method Overloading Same method name with different parameters (limited in Python)
Duck Typing Objects used based on their behavior, not their type
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)]
class Cat:
def speak(self): return 'Meow!'
class Parrot:
def speak(self): return 'Hello!'
Output:
Woof!
Meow!
Hello!
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)
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!')
# Testing
animals = [Animal('Generic'), Dog('Rex'), Cat('Kitty'), Lion('Simba')]
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!
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!')
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')
def on_click():
count[0] += 1
[Link](text=f'Clicked {count[0]} times!')
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]()
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!')
[Link]()
root = [Link]()
[Link]()
Widget Purpose
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]()
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]()
root = [Link]()
[Link]('Entry Widget Demo')
def submit():
u = [Link]()
p = [Link]()
[Link](text=f'Welcome, {u}!' if u else 'Enter username!')
# 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')
def show_values():
print(f'Age: {age_spin.get()}, Month: {month_spin.get()}')
[Link]()
root = [Link]()
[Link]('Text Widget Demo')
scrollbar = [Link](frame)
[Link](side=[Link], fill=tk.Y)
def get_content():
content = [Link]('1.0', [Link]) # get all text
print(content)
[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)
count = [0]
def update():
count[0] += 1
[Link](f'Dynamic: {count[0]}')
[Link]()
root = [Link]()
[Link]('Checkbutton Demo')
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 = [Link]()
[Link]('Radiobutton Demo')
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]()
import tkinter as tk
root = [Link]()
[Link]('pack() Demo')
[Link]('300x200')
[Link]()
import tkinter as tk
root = [Link]()
[Link]('grid() Demo - Login Form')
[Link]()
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)
[Link]()
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.
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')
frame = [Link](root)
[Link](padx=20, fill=tk.X)
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]
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]()