COMPUTER PROGRAMMING
PCC-EE 405
Nirmal Murmu
Department of Applied Physics
University of Calcutta
Course Outcomes
• At the end of this course, students will be able to learn about
• CO1: Identify fundamental programming concepts, data structures, and file
handling techniques used in software development.
• CO2: Explain the principles of object-oriented programming, event-driven
programming, and their applications in GUI and system programming.
• CO3: Develop basic to intermediate-level applications using programming
languages and libraries for file manipulation, data handling, and user interaction.
• CO4: Compare and evaluate different programming approaches, paradigms, and
tools for solving computational problems effectively.
• CO5: Assess the efficiency, scalability, and usability of developed applications,
optimizing code performance and debugging issues effectively.
•
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 2
UNIVERSITY OF CALCUTTA
Syllabus
• Module 1: Introduction to Visual basic (8 hour)
• Fundamentals of GUI development using [Link], Concepts of object, method and event in [Link],
Utilisation of various tools, Components and References, basic concept of event handling, I/O File
handling and data handling.
• Module 2: Visual basic Programming (10 hour)
• Learn to develop program in windows environment, simple display program, Key board and
mouse interactive program, Reading and writing I/O files, handling of other windows program -
like reading and writing Excel file, Excel plotting, interfacing of USB/COM ports, development of
net based application in client/server mode.
• Module 3: Introduction to Python libraries (10 hour)
• Python Types, Expressions, Strings, Lists, Tuples, Python memory model (names, mutable and
immutable values), List operations, Regular Expressions, Python Functions, Abstract Data types,
Classes and Objects in Python, Exception handling, Handling files, Python
Scientific/Statistical/Machine Learning Libraries.
• Module 4: Python programming (12 hour)
• Python Programming: Object based program using multi threading, I/O handling of files, Printing
and display using timer operation, program for handling of interfacing of cameras, program to
develop machine learning based applications.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 3
UNIVERSITY OF CALCUTTA
References
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 4
UNIVERSITY OF CALCUTTA
Lecture Plan
Lecture No. Topic Key Concepts
Variables, Data Types, and Python types, expressions,
1
Operators operators, type conversions
Lists, tuples, slicing, loops (for,
2 Arrays and Flow Control
while), conditional statements
Defining functions, arguments,
3 Methods and Functions
return values, recursion
Reading/writing files, handling CSV,
4 File Handling
JSON
Introduction to Scientific NumPy, Pandas, Matplotlib for data
5
Libraries processing
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 5
UNIVERSITY OF CALCUTTA
Lecture Plan
Lecture No. Topic Key Concepts
Object-Oriented Programming Classes, objects, inheritance,
1
(OOPs) in Python polymorphism
Multi-threading and Advanced File Threading basics, file operations,
2
Handling concurrent programming
Timers, Event Handling, and GUI Timer-based operations, GUI
3
Development programming using Tkinter/PyQt
Using OpenCV for image
Camera Interfacing and Data
4 processing, real-time data
Acquisition
acquisition
Machine Learning and AI Basics of Scikit-learn, TensorFlow,
5
Applications AI-driven applications
Final Project Discussion and Developing real-world
6
EVEN SEMESTER
Implementation DEPARTMENT OF APPLIED PHYSICS,
applications, project review 6
UNIVERSITY OF CALCUTTA
%s → String
Print Formatting Methods %d → Integer
① • Using % Operator %f → Floating-point
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
• Using .format()
⑪ print("My name is {} and I am {} years old.".format(name,
Alice.
age))
(25)
• Using f-strings
print(f"My name is {name} and I am {age} years old.")
pi = 3.1415926535
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 116
print(f"Rounded to 2 decimals: {pi:.2f}")
UNIVERSITY OF CALCUTTA
Using %% to Print a Literal %
placeholder
percentage = 85
⑨ 1)
print("Your score is %d%%." % percentage)
'format
"1070 " % in o/P specifier → lid/int)
1. s (Str)
(A1) Your score is 851.. → 1. f (twats
The advantage of using {) in place of
% is that dont have to specify the format
1. I am/ /years old".
name: my' → Print ( "My name is format (name, age"))
age: 21 DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 117
UNIVERSITY OF CALCUTTA
Format Specifiers for % Operator
Specifie
Data Type Example
r
"Hello %s" % "World" → "Hello
%s String
World"
"I am %d years old" % 25 → "I am
%d Integer
25 years old"
"Value: %f" % 3.1415 → "Value:
%f Floating-point
3.141500"
Float with n
%.nf "%.2f" % 3.1415 → "3.14" [2 places after.]
decimal places
%x Hexadecimal "Hex: %x" % 255 → "Hex: ff" (255),0→ (f) u
%o Octal "Oct: %o" %
DEPARTMENT OF APPLIED PHYSICS,
8 → "Oct: (10"
EVEN SEMESTER 118
UNIVERSITY OF CALCUTTA ↳ Binary, 910005
Floating-Point Formatting and %[Link]
• Formatting Floats with Precision
pi = 3.14159
print("Value of pi: %.2f" % pi) # Rounded to 2 decimal
places
3. 14
.2f → Prints 2 decimal places
%5.2f → Aligns output with minimum width 5
↓
minmwidth:S 314 → O/P=..-314
Width:b ↳ 1 space allote d during Ofp
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 119
UNIVERSITY OF CALCUTTA
Aligning Output and Debugging Errors
• Right-Aligned Numbers (%5.2f)
num1 = 1.2
num2 = 12.345
num3 = 123.4567
print("%5.2f" % num1) → ...1.20
print("%5.2f" % num2) → 1234
print("%5.2f" % num3) → 123.46
minm width can be more than 5.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 120
UNIVERSITY OF CALCUTTA
Debugging Exercise
• Find the Error:
x = 10
y = "5"
print(x + y) Int + string not possible.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 121
UNIVERSITY OF CALCUTTA
Hands-on Example
• Example 1: Simple Arithmetic Operations
• Objective: Perform basic arithmetic operations using user
input.
• Concepts Used: Variables, Data Types, Input Handling,
Operators
Algorithm:
Start
Prompt the user to enter two numbers.
Store the numbers in variables (num1, num2).
Compute the sum, product, and difference.
Display the results with two decimal places.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER
End 122
UNIVERSITY OF CALCUTTA
Hands-on Example
• Example 1: Simple Arithmetic Operations
# Get two numbers from the user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Perform basic arithmetic operations
sum_result = num1 + num2
product = num1 * num2
difference = num1 - num2
# Display results f string
print(f"Sum: {sum_result:.2f}") } all upto [Link]
print(f"Product: {product:.2f}")
print(f"Difference: {difference:.2f}")
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 123
UNIVERSITY OF CALCUTTA
Hands-on Example
• Example 2: Even or Odd Number Checker
• Objective: Determine if a given number is even or odd using
conditional statements.
• Algorithm:
[Link]
[Link] the user to enter a number.
[Link] the number in a variable (num).
[Link] modulus operator (%) to check divisibility by 2:
• If num % 2 == 0, print "Even number".
• Else, print "Odd number".
[Link]
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 124
UNIVERSITY OF CALCUTTA
Hands-on Example
• Example 2: Even or Odd Number Checker
• Objective: Determine if a given number is even or odd
using conditional statements.
# Get number input
num = int(input("Enter a number: "))
# Check if even or odd
if num % 2 == 0:
print(f"{num} is an even number.")
else:
print(f"{num} is an odd number.")
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 125
UNIVERSITY OF CALCUTTA
Topic Timeline
Topic Key Concepts Hands-on Activity
Defining, accessing elements, slicing, Create a list, perform slicing,
Lists & Tuples
appending, modifying append elements
List Methods & Practice list operations &
append(), remove(), sort(), index()
Operations debugging
if-elif-else, nested conditions, and/or Build a number classification
Conditional Statements
operators program (positive/negative/zero)
Print even numbers, reverse a list
For & While Loops range(), enumerate(), iteration over lists
using loops
Convert list of strings to uppercase
Loop Optimizations List comprehensions, zip(), map()
using comprehension
Error Handling in Loops & Try accessing an out-of-range
try-except, handling IndexError in lists
Lists index & handle exception
Nested Loops & Practical
Iterating over nested lists, pattern printing Print a right-angled triangle pattern
Use Cases
Debugging loops & conditionals, common Solve a logical bug in loop
Debugging & Q&A
mistakes execution
DEPARTMENT OF APPLIED PHYSICS, UNIVERSITY OF
EVEN SEMESTER CALCUTTA 126
Basic List Operations
• Objective: Perform operations on a list of numbers
• Concepts Used: Lists, Indexing, Append, Remove, Slicing
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 127
UNIVERSITY OF CALCUTTA
List Methods
Method Operation Syntax Example
index() returns the index of [Link](element, start, end) animals = ['cat', 'dog',
the specified 'rabbit', 'horse’]
element index = 71
[Link]('dog')
↳ d-index (value)
append() adds an item to the [Link](item) [Link](‘cow’)
end of the list
extend() adds all the [Link](iterable) [Link]([‘rat’,’lion
elements of an ’])
↳ Eat, dog, rabbit' horse, rat]
iterable (list, tuple, ' 'lion.
string etc.) to the
end of the list.
insert() inserts an element [Link](i, element) vowel = ['a', 'e', 'i', 'u]
to the list at the [Link](3, 'o')
specified index
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
UNIVERSITY OF CALCUTTA
↳ vowel: Eal.'es128'il.]
never giveadress
List Methods
Method Operation Syntax Example
remove() removes the first [Link](element) [Link]('rat')
matching element J-l:[a. b. c. 449]
(which is passed as 1- remove (c)
an argument) from
the list
e: ca, b, c, c, d]
count() returns the number [Link](element) numbers = [2, 3, 5, 2, 11,
of times the 2, 7]
Je: [Link], and]
specified element # check the count of 2
appears in the list.
l-count (c): 3. count = [Link](2) =3
✓
pop() removes the item at [Link](index) [Link](1)
the given index I: (a, b,c, c, d, e)
from the list and returned
returns the removed l-pop(4) →
item
l-[[Link]
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 129
UNIVERSITY OF CALCUTTA
List Methods
Method Operation Syntax Example
reverse() reverses the [Link]() integer=[1,2,3,4,5]
[Link]() ↳[5,4, 3,211]
elements of the list
sort() sorts the elements [Link](key=..., reverse=...) vowels = ['e', 'a', 'u', 'o',
unde 'i’]
of a given list in a [Link]()
rstand specific ascending sorted(iterable, /, *, print('Sorted list:', vowels)
once
or descending order key=None, reverse=False) [Link](reverse=True)
more. custom function print('Sorted list (in
using key Descending):', vowels)
copy() returns a shallow [Link]() prime_numbers = [2, 3, 5]
numbers = prime_numbers.copy()
copy of the list ↳ [213,5]
clear() removes all items [Link]() prime_numbers.clear()
from the list ↳ []
> del (list name)
print (list name)
↳ Name Emr.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 130
UNIVERSITY OF CALCUTTA
Example: Using .append(), .insert(),
and .remove()
• Objective: Show how to add and remove elements
dynamically in a list.
• Concepts Used: .append(), .insert(), .remove()
• Problem Statement:
• Create an empty list.
• Add three elements using .append().
• Insert an element at index 1 using .insert().
• Remove a specific element using .remove().
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 131
UNIVERSITY OF CALCUTTA
Example: Using .append(), .insert(),
and .remove()
# Step 1: Create an empty list
fruits = []
# Step 2: Append elements
[Link]("Apple")
[Link]("Banana")
[Link]("Cherry")
print("List after appending:", fruits)
→ ["apple"." banana"," cherry")
# Step 3: Insert "Mango" at index 1
[Link](1, "Mango")
print("List after inserting Mango at index 1:", fruits)
Umango" " banana"," cherry")
# Step 4: Remove "Banana"
→ ["apple",
[Link]("Banana") a. mango" ." cherry")
print("List after removing DEPARTMENT
Banana:",OFfruits) → ["apple".
APPLIED PHYSICS,
EVEN SEMESTER 132
UNIVERSITY OF CALCUTTA
Example : Using .sort(), .reverse(), and
.count()
• Problem Statement:
• Create a list of random numbers.
• Sort the list in ascending order using .sort().
• Reverse the list using .reverse().
• Count the occurrences of a specific number.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 133
UNIVERSITY OF CALCUTTA
Example : Using .sort(), .reverse(), and
.count()
# Step 1: Create a list of numbers
numbers = [3,
- 7, 2,- 9, 7, 1,
- 7, 5]
print("Original list:", numbers)
# Step 2: Sort the list
[Link]()
print("Sorted list:", numbers)→ [1,213,517,719]
# Step 3: Reverse the sorted list
[Link]()
print("Reversed list:", numbers) → [9. 7. 7,5, 3,211]
# Step 4: Count occurrences of 7
count_7 = [Link](7)
print("Number of times 7 appears:", count_7) → 2
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 134
UNIVERSITY OF CALCUTTA
Example: Sort the list using key
* * Very Imp
# take second element for sort
def takeSecond(elem):
return elem[1]
# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# sort list with key
[Link](key=takeSecond)
# print list
print('Sorted list:', random)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 135
UNIVERSITY OF CALCUTTA
Example: extend() vs append()
a1 = [1, 2]
a2 = [1, 2]
b = (3, 4)
# a1 = [1, 2, 3, 4]
[Link](b)
print(a1) → ☐ i 2,314, 314)
# a2 = [1, 2, (3, 4)]
[Link](b)-
- → [1.2, (3.4)]
print(a2)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 136
UNIVERSITY OF CALCUTTA
Nested List
• Support arbitrary nesting
• Immediate application of this feature is to represent matrixes, or
“multidimensional arrays”
• List in a list >>> M = [[1, 2, 3], # A 3 × 3 matrix, as nested lists
• E.g., [4, 5, 6], # Code can span lines if bracketed
[7, 8, 9]]
• >>> s = [1,2,3] >>> M
• >>> t = [‘begin’, s, ‘end’][[1, 2, 3], [4, 5, 6], [7, 8, 9]]
• >>> t >>> M[1] # Get row 2
[4, 5, 6]
• [‘begin’, [1, 2, 3], ‘end’] >>> M[1][2] # Get row 2, then get item 3 within the
• >>> t[1][1] row
• 2 6
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 137
UNIVERSITY OF CALCUTTA
List Comprehensions
• Way to build a new list by running an expression on each
item in a sequence, one at a time, from left to right
• Are coded in square brackets
• Are composed of an expression and a looping construct
that share a variable name
new_list = [expression for item in iterable if condition]
The operation or
transformation Each element from The sequence
applied to each item. the iterable (e.g., A filter to include
of elements to
list, range, tuple). only specific
iterate
DEPARTMENT OF APPLIED over.
PHYSICS,
EVEN SEMESTER
UNIVERSITY OF CALCUTTA elements. 138
List Comprehensions
• Way to build a new list by running an expression on each
item in a sequence, one at a time, from left to right
• Are coded in square brackets
• Are composed of an expression and a looping construct
that share a variable name
>>> L = []
>>> for n in range(1,11):
[Link](n)
>>> L = [n for n in range(1,101)]
List
Comprehensions
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 139
UNIVERSITY OF CALCUTTA
List Comprehensions
squares = []
for num in range(1, 6): Interchangable
[Link](num ** 2) List COMPOE
called as hen81' ons
print(squares)
squares = [num ** 2 for num in
range(1, 6)]
print(squares)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 140
UNIVERSITY OF CALCUTTA
List Comprehensions
• Way to process structures like matrix
>>> M = [[1, 2, 3], # A 3 × 3 matrix, as nested lists
[4, 5, 6], # Code can span lines if bracketed
[7, 8, 9]]
>>> col2 = [row[1] for row in M] # Collect the items in column 2
>>> col2
[2, 5, 8]
>>> M # The matrix is unchanged
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Give me row[1] for each row in
matrix M, in a new list
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 141
UNIVERSITY OF CALCUTTA
List Comprehensions
• Way to process structures like matrix
>>> M = [[1, 2, 3], # A 3 × 3 matrix, as nested lists
[4, 5, 6], # Code can span lines if bracketed
[7, 8, 9]]
>>> [row[1] + 1 for row in M] # Add 1 to each item in column 2
[3, 6, 9]
>>> [row[1] for row in M if row[1] % 2 == 0] # Filter out odd
items
[2, 8]
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 142
UNIVERSITY OF CALCUTTA
List Comprehensions
• Way to process structures like matrix
>>> M = [[1, 2, 3], # A 3 × 3 matrix, as nested lists
[4, 5, 6], # Code can span lines if bracketed
[7, 8, 9]]
>>> diag = [M[i][i] for i in [0, 1, 2]] # Collect a diagonal from matrix
>>> diag
[1, 5, 9]
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 143
UNIVERSITY OF CALCUTTA
List Comprehensions
• Way to process structures like matrix
y >>> 3 in [1, 2, 3] # Membership
True
>>> for x in [1, 2, 3]:
... print(x, end=' ') # Iteration
...
1 2 3
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 144
UNIVERSITY OF CALCUTTA
List Comprehensions
• Way to process structures like matrix
>>> res = [c * 4 for c in 'SPAM'] # List comprehensions
>>> res
['SSSS', 'PPPP', 'AAAA', 'MMMM']
>>> res = []
>>> for c in 'SPAM': # List comprehension equivalent
... [Link](c * 4)
...
>>> res
['SSSS', 'PPPP', 'AAAA', 'MMMM']
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 145
UNIVERSITY OF CALCUTTA
Example : Creating a List of Squares
squares = [] squares = [num ** 2 for num in
for num in range(1, 6): range(1, 6)]
[Link](num ** 2) print("Squares:", squares)
print("Squares:", squares)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 146
UNIVERSITY OF CALCUTTA
Example : Filtering Even Numbers
from a List
numbers = [1, 2, 3, 4, 5, 6, 7, even_numbers = [num for num in
8] numbers if num % 2 == 0]
even_numbers = [] print("Even numbers:",
even_numbers)
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print("Even numbers:",
even_numbers)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 147
UNIVERSITY OF CALCUTTA
Quick Quiz
• Name two ways to build a list containing five integer zeros.
zeros_list = [0] * 5 zeros_list = [0 for _ in range(5)]
print(zeros_list) print(zeros_list)
• Name four operations that change a list object in place.
nums = [1, 2, 3]
[Link](4)
[Link]([4, 5])
[Link](1, 2)
[Link](2)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 148
UNIVERSITY OF CALCUTTA
Tuples
• What is a tuple?
•A tuple is an ordered collection which cannot
be modified once it has been created.
• In other words, it's a special array, a read-only array.
• How to make a tuple? In round brackets
• E.g.,
>>> t = ()
>>> t = (1, 2, 3)
>>> t = (1, )
>>> t = 1,
>>> a = (1, 2, 3, 4, 5)
>>> print a[1] # 2
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 149
UNIVERSITY OF CALCUTTA
Tuples: Identify Difference
♂ If one element
>>> t = (1, ) >>> t = (1)
>>> type (t) >>> type (t)
<class 'tuple’> <class 'int'>
t = 0, 'Ni', 1.2, 3
>>> type (t)
<class 'tuple’>
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 150
UNIVERSITY OF CALCUTTA
Tuple Methods
• Python has two built-in methods that you can use on tuples
Method Operation Syntax E.g
count() returns the number of times a [Link](value) thistuple = (1, 3, 7,
specified value appears in the 8, 7, 5, 4, 6, 8, 5)
tuple
x = [Link](5)
index() finds the first occurrence of the [Link](value) x = [Link](8)
specified value and raises an
exception if the value is not
found
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 151
UNIVERSITY OF CALCUTTA
Operations in Tuple
• Indexing e.g., T[i]
• Slicing e.g., T[1:5]
• Concatenation e.g., T + T
• Repetition e.g., T * 5
• Membership test e.g., ‘a’ in T
• Length e.g., len(T)
• Concatenate, repeat e.g., T1 + T2, T * 3
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 152
UNIVERSITY OF CALCUTTA
Tuple Operations
>>> T = ('cc', 'aa', 'dd', 'bb') >>> T = tuple(tmp) # Make a
>>> tmp = list(T) # Make a list tuple from the list's items
from a tuple's items >>> T
>>> [Link]() # Sort the list ('aa', 'bb', 'cc', 'dd')
>>> tmp >>> sorted(T) # Or use the
['aa', 'bb', 'cc', 'dd'] sorted built-in, and save two
steps
['aa', 'bb', 'cc', 'dd']
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 153
UNIVERSITY OF CALCUTTA
List can be changed
Tuple Operations
>>> T = (1, [2, 3], 4) >>> T[1][0] = 'spam' # This
>>> T[1] = 'spam' # This fails: works: can change mutables
can't change tuple itself inside
TypeError: object doesn't >>> T
support item assignment (1, ['spam', 3], 4)
Elements of tuple fixed
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 154
UNIVERSITY OF CALCUTTA
Example : Tuple
• Define a Tuple for a Student Record
• student = (101, "Alice", 20, "Computer Science")
• print("Student Record:", student)
• Accessing Tuple Elements
• print("Student Name:", student[1])
• print("Student Course:", student[3])
• Tuple Unpacking ** Revise
• roll, name, age, course = student
• print(f"Roll: {roll}, Name: {name}, Age: {age}, Course: {course}")
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 155
UNIVERSITY OF CALCUTTA
List vs. Tuple
• What are common characteristics?
• Both store arbitrary data objects
• Both are of sequence data type
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 156
UNIVERSITY OF CALCUTTA
List vs. Tuple
• What are differences?
• Tuple doesn’t allow modification
• Tuple supports format strings
• Tuple supports variable length parameter in function call.
• Tuples slightly faster
• Tuple’s size is fixed, it can be stored more compactly than lists which need
to over-allocate
• Tuple is stored in a single block of memory but list requires two block of
memory, (fixed size and variable size)
• The user is aware of what is inserted in the tuple
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 157
UNIVERSITY OF CALCUTTA
List vs. Tuple
Feature List Tuple
Mutability Can be modified Cannot be modified
Performance Slower (more overhead) Faster (less overhead)
Memory Usage Takes more memory Takes less memory
Dynamic data (e.g., user input, Fixed data (e.g., database
Use Cases
logs) records, config settings)
Memory Usage Takes more memory Uses less memory
Iteration Speed Slower due to mutability Faster since it’s fixed
Requires dynamic memory
Extra Processing Stored in a single block
allocation
Modification No need to track
Keeps track of changes
Overhead modifications
Caching (Interning) Not cached Small tuples are cached
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 158
UNIVERSITY OF CALCUTTA
Example: List vs Tuple
# Creating a list # Creating a tuple
fruits_list = ["Apple", "Banana", fruits_tuple = ("Apple", "Banana",
"Cherry"] "Cherry")
print("Original List:", fruits_list)
print("Original Tuple:",
fruits_tuple)
# Modifying the list
fruits_list[1] = "Mango" # Modifying the tuple
print("Modified List:", fruits_list) fruits_tuple[1] = "Mango" ✗ Error
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 159
UNIVERSITY OF CALCUTTA
Example: List vs Tuple
import sys import timeit
list_data = [1, 2, 3, 4, 5] list_time = [Link](stmt="[x
tuple_data = (1, 2, 3, 4, 5) for x in range(100000)]",
number=100)
print("List size:", tuple_time =
[Link](list_data), "bytes") [Link](stmt="(x for x in
range(100000))", number=100)
print("Tuple size:",
[Link](tuple_data), "bytes")
print("List execution time:",
list_time)
print("Tuple execution time:",
tuple_time)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 160
UNIVERSITY OF CALCUTTA
Quick Quiz
• How can you determine how large a tuple is?
my_tuple = (4, 5, 6, 7, 8)
size = len(my_tuple)
print("Tuple size:", size)
~5
• Write an expression that changes the first item in a tuple. (4, 5, 6)
should become (1, 5, 6) in the process
old_tuple = (4, 5, 6)
~ (516) → (1) + (516)
new_tuple = (1,) + old_tuple[1:]
print(new_tuple) ⇒ (1,5, 6)
• What do you think is happening to X and Y when you type this
sequence?
>>> X = 'spam' ✗ = eggs.
>>> Y = 'eggs' = spam
>>> X, Y = Y, X
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 161
UNIVERSITY OF CALCUTTA
Dictionaries
• Known as mappings
• Collections of other objects, but they store objects by key instead of by relative
position
• Don’t maintain any reliable left-to-right order
• May be changed in-place and can grow and shrink on demand
• What is dictionary?
• Refer value through key; “associative arrays”
• Like an array indexed by a string
• An unordered set of key: value pairs
• Values of any type; keys of almost any type
• {"name":"Guido", "age":43, ("hello","world"):1,
42:"yes", "flag": ["red","white","blue"]}
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 162
UNIVERSITY OF CALCUTTA
Dictionaries
• Contrast with list,
• dictionaries as unordered collections
• items are stored and fetched by key, instead of by positional offset
• Accessed by key, not offset: referred to values
• Unordered collections of arbitrary objects
• Variable-length, heterogeneous, and arbitrarily nestable: can
grow and shrink, support nesting to any depth
• Of the category “mutable mapping”: operations that depend on
a fixed positional order (e.g., concatenation, slicing) don’t make sense
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 163
UNIVERSITY OF CALCUTTA
Dictionaries
• Dictionaries: curly brackets
d = { "foo" : 1, "bar" : 2 }
print d["bar"] # 2
some_dict = {}
some_dict["foo"] = "yow!"
print some_dict.keys() # ["foo"]
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 164
UNIVERSITY OF CALCUTTA
Dictionary details
• Keys must be immutable:
• numbers, strings, tuples of immutables
• these cannot be changed after creation
• reason is hashing (fast lookup technique)
• not lists or other dictionaries
• these types of objects can be changed "in place"
• no restrictions on values
• Keys will be listed in arbitrary order
• again, because of hashing
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 165
UNIVERSITY OF CALCUTTA
Dictionary Operations
Operation Interpretation
D = {} Empty dictionary
D = {'spam': 2, 'eggs': 3} Two-item dictionary
D = {'food': {'ham': 1, 'egg': 2}} Nesting
D = dict(name='Bob', age=40) Alternative construction techniques:
D['eggs'] Indexing by key
'eggs' in D Membership: key present test
len(D) Length: number of stored entries
list([Link]()) Dictionary views (Python 3.0)
del D[key] Deleting entries by key
D = {x: x*2 for x in range(10)} Dictionary comprehensions (Python 3.0)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 166
UNIVERSITY OF CALCUTTA
Dictionary Methods
• Python has two built-in methods that you can use on
dictionary
Method Operation Syntax Example
clear() removes all the elements from a [Link]() car = {
"brand": "Ford",
dictionary "model": "Mustang",
"year": 1964
}
[Link]()
copy() returns a copy of the specified [Link]() x = [Link]()
dictionary.
fromkeys() returns a dictionary with the [Link](keys, # vowels keys
keys = {'a', 'e', 'i', 'o',
specified keys and the specified value) 'u' }
value value = 'vowel'
vowels = [Link](keys,
value)
DEPARTMENT OF APPLIED PHYSICS, print(vowels)
EVEN SEMESTER 167
UNIVERSITY OF CALCUTTA
Dictionary Methods
Method Operation Syntax Example
get() returns the value for the specified [Link](keyname, marks = {'Physics':67,
key if the key is in the dictionary value) 'Maths':87}
print([Link]('Physics
’))
print([Link](‘Chemist
ry’))
print([Link](‘Chemist
ry’, 55))
items() method returns a view object that [Link]() marks = {'Physics':67,
displays a list of dictionary's (key, 'Maths':87}
value) tuple pairs print([Link]())
keys() method returns a view object that [Link]() person = {'name':
displays a list of all the keys in the 'Phill', 'age': 22, }
dictionary keys = [Link]()
print(keys)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 168
UNIVERSITY OF CALCUTTA
Dictionary Methods
Method Operation Syntax Example
pop() removes the specified item [Link](key[, car = {
from the dictionary default]) "brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]("model")
print(x)
popitems() removes and returns the last [Link]() person = {'name':
element (key, value) pair 'Phill', 'age': 22,
inserted into the dictionary. 'salary': 3500.0}
result =
[Link]()
print(result)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 169
UNIVERSITY OF CALCUTTA
Dictionary Methods
Method Operation Syntax Example
values() returns a view object that [Link]() sales = { 'apple': 2,
'orange': 3, 'grapes': 4 }
displays a list of all the values print([Link]())
in the dictionary
setdefault() returns the value of a key (if [Link](k person = {'name': 'Phill'}
# key is not in the dictionary
the key is in dictionary). If not, eyname, value) salary =
it inserts key with a value to [Link]('salary')
print('person = ',person)
the dictionary print('salary = ',salary)
# key is not in the dictionary
# default_value is provided
age = [Link]('age',
22)
print('person = ',person)
print('age = ',age)
update() updates the dictionary with [Link](iter d = {1: "one", 2: "three"}
d1 = {2: "two"}
the elements from another able) # updates the value of key 2
dictionary object or from an [Link](d1)
print(d)
iterable of key/value pairs
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 170
UNIVERSITY OF CALCUTTA
Dictionary
• Sequence operations don’t work
• Dictionaries are mappings, not sequences
• Assigning to new indexes adds entries
• Keys need not always be strings
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 171
UNIVERSITY OF CALCUTTA
Dictionary Comprehensions
• Another way to construct dictionary by zip together its keys
and values and pass the result to the dict call
>>> list(zip(['a', 'b', 'c'], [1, 2, 3])) # Zip together keys and
values
[('a', 1), ('b', 2), ('c', 3)]
D = dict(zip(['a', 'b', 'c'], [1, 2, 3])) # Make a dict from zip
result
>>> D
{'a': 1, 'c': 3, 'b': 2}
• Can be done using dictionary comprehension
>>> D = {k: v for (k, v) in zip(['a', 'b', 'c'], [1, 2, 3])}
>>> D = {x: x ** 2 for x in [1, 2, 3, 4]} # Or: range(1, 5)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 172
UNIVERSITY OF CALCUTTA
Example: Storing Student Grades
• Start
• Create a dictionary with student
names as keys and grades as
values.
• Access a student's grade using
their name.
• Modify a student's grade.
• Add a new student to the
dictionary.
• Iterate through the dictionary
and print all students with their
grades.
• End
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 173
UNIVERSITY OF CALCUTTA
Example
>>> table = {'1975': 'Holy • >>> for year in table:
Grail', '1979': 'Life of Brian’, print(year + '\t' +
'1983': 'The Meaning of Life'} table[year])
>>> year = '1983'
>>> movie = table[year]
>>> movie
'The Meaning of Life
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 174
UNIVERSITY OF CALCUTTA
Quick Quiz
• Name two ways to build a dictionary with two keys, 'a' and 'b',
each having an associated value of 0.
dict1 = {'a': 0, 'b': 0}
dict2 = dict(a=0, b=0)
• Name four operations that change a dictionary object in place.
student = {'name': 'Amit', 'age': 20}
[Link]({'age': 21, 'grade': 'A’})
[Link]('age’)
[Link]()
[Link]('age', 20)
• Make a dictionary that maps keys to more than one value
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 175
UNIVERSITY OF CALCUTTA
Data Type Wrap Up
• Integers: 2323, 3234L
• Floating Point: 32.3, 3.1E2
• Complex: 3 + 2j, 1j
• Lists: l = [ 1,2,3]
• Tuples: t = (1,2,3)
• Dictionaries: d = {‘hello’ : ‘there’, 2 : 15}
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 176
UNIVERSITY OF CALCUTTA
Data Type Wrap Up
• Lists, Tuples, and Dictionaries can store any type (including
other lists, tuples, and dictionaries!)
• Only lists and dictionaries are mutable
• All variables are references
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 177
UNIVERSITY OF CALCUTTA
Example: Set
#Create a set
num_set = set([0, 1, 2, 3, 4, 5])
for n in num_set:
print(n, end=‘ ‘)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 178
UNIVERSITY OF CALCUTTA
Example: Dictionary
d = {'Red': 1, 'Green': 2, 'Blue': 3}
for color_key, value in [Link]():
print(color_key, 'corresponds to ', d[color_key])
my_dict = {'data1':100,'data2':-54,'data3':247}
result=1
for key in my_dict:
result=result * my_dict[key] print(result)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 179
UNIVERSITY OF CALCUTTA
Example: Tuple
Find the repeated items of a tuple.
#create a tuple
tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7
print(tuplex)
#return the number of times it appears
in the tuple.
count = [Link](4)
print(count)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 180
UNIVERSITY OF CALCUTTA
Example:
# languages list
languages = ['French’]
# languages tuple
languages_tuple = ('Spanish', 'Portuguese’)
# languages set
languages_set = {'Chinese', 'Japanese’}
# appending language_tuple elements to language
[Link](languages_tuple)
print('New Language List:', languages)
# appending language_set elements to language
[Link](languages_set)
print('Newer Languages List:', languages)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 181
UNIVERSITY OF CALCUTTA
Sorting using Custom Key
# sorting using custom key # sort by name (Ascending order)
employees = [ [Link](key=get_name)
{'Name': 'Alan Turing', 'age': 25, 'salary': 10000}, print(employees, end='\n\n')
{'Name': 'Sharon Lin', 'age': 30, 'salary': 8000},
{'Name': 'John Hopkins', 'age': 18, 'salary': 1000}, # sort by Age (Ascending order)
{'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000}, [Link](key=get_age)
] print(employees, end='\n\n')
# custom functions to get employee info # sort by salary (Descending order)
def get_name(employee): [Link](key=get_salary,
return [Link]('Name') reverse=True)
print(employees, end='\n\n')
def get_age(employee):
return [Link]('age')
def get_salary(employee):
return [Link]('salary')
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 182
UNIVERSITY OF CALCUTTA
COMPUTER PROGRAMMING
PCC-EE 405
Nirmal Murmu
Department of Applied Physics
University of Calcutta
Course Outcomes
• At the end of this course, students will be able to learn about
• CO1: Identify fundamental programming concepts, data structures, and file
handling techniques used in software development.
• CO2: Explain the principles of object-oriented programming, event-driven
programming, and their applications in GUI and system programming.
• CO3: Develop basic to intermediate-level applications using programming
languages and libraries for file manipulation, data handling, and user interaction.
• CO4: Compare and evaluate different programming approaches, paradigms, and
tools for solving computational problems effectively.
• CO5: Assess the efficiency, scalability, and usability of developed applications,
optimizing code performance and debugging issues effectively.
•
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 2
UNIVERSITY OF CALCUTTA
Syllabus
• Module 1: Introduction to Visual basic (8 hour)
• Fundamentals of GUI development using [Link], Concepts of object, method and event in [Link],
Utilisation of various tools, Components and References, basic concept of event handling, I/O File
handling and data handling.
• Module 2: Visual basic Programming (10 hour)
• Learn to develop program in windows environment, simple display program, Key board and
mouse interactive program, Reading and writing I/O files, handling of other windows program -
like reading and writing Excel file, Excel plotting, interfacing of USB/COM ports, development of
net based application in client/server mode.
• Module 3: Introduction to Python libraries (10 hour)
• Python Types, Expressions, Strings, Lists, Tuples, Python memory model (names, mutable and
immutable values), List operations, Regular Expressions, Python Functions, Abstract Data types,
Classes and Objects in Python, Exception handling, Handling files, Python
Scientific/Statistical/Machine Learning Libraries.
• Module 4: Python programming (12 hour)
• Python Programming: Object based program using multi threading, I/O handling of files, Printing
and display using timer operation, program for handling of interfacing of cameras, program to
develop machine learning based applications.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 3
UNIVERSITY OF CALCUTTA
References
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 4
UNIVERSITY OF CALCUTTA
Lecture Plan
Lecture No. Topic Key Concepts
Variables, Data Types, and Python types, expressions,
1
Operators operators, type conversions
Lists, tuples, slicing, loops (for,
2 Arrays and Flow Control
while), conditional statements
Defining functions, arguments,
3 Methods and Functions
return values, recursion
Reading/writing files, handling CSV,
4 File Handling
JSON
Introduction to Scientific NumPy, Pandas, Matplotlib for data
5
Libraries processing
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 5
UNIVERSITY OF CALCUTTA
Lecture Plan
Lecture No. Topic Key Concepts
Object-Oriented Programming Classes, objects, inheritance,
1
(OOPs) in Python polymorphism
Multi-threading and Advanced File Threading basics, file operations,
2
Handling concurrent programming
Timers, Event Handling, and GUI Timer-based operations, GUI
3
Development programming using Tkinter/PyQt
Using OpenCV for image
Camera Interfacing and Data
4 processing, real-time data
Acquisition
acquisition
Machine Learning and AI Basics of Scikit-learn, TensorFlow,
5
Applications AI-driven applications
Final Project Discussion and Developing real-world
6
EVEN SEMESTER
Implementation DEPARTMENT OF APPLIED PHYSICS,
applications, project review 6
UNIVERSITY OF CALCUTTA
Topic Timeline
Topic Key Concepts Hands-on Activity
Defining, accessing elements, slicing, Create a list, perform slicing,
Lists & Tuples
appending, modifying append elements
List Methods & Practice list operations &
append(), remove(), sort(), index()
Operations debugging
if-elif-else, nested conditions, and/or Build a number classification
Conditional Statements
operators program (positive/negative/zero)
Print even numbers, reverse a list
For & While Loops range(), enumerate(), iteration over lists
using loops
Convert list of strings to
Loop Optimizations List comprehensions, zip(), map()
uppercase using comprehension
Error Handling in Loops Try accessing an out-of-range
try-except, handling IndexError in lists
& Lists index & handle exception
Nested Loops & Iterating over nested lists, pattern Print a right-angled triangle
Practical Use Cases printing pattern
Debugging loops & conditionals, Solve a logical bug in loop
Debugging & Q&A
common mistakes
DEPARTMENT OF APPLIED PHYSICS, UNIVERSITY OF
execution
EVEN SEMESTER CALCUTTA 183
Quick Recap
isis:
• What is the difference between / and // operators in Python?
• What does the modulus operator (%) do? → remainder, file format
• How do you check if a number is even or odd using an operator?
• What will be the result of the following expression? ↳ 902220, 1. 2!: 0
print(2 + 3 * 4 / 2 - 1) → 7.0
• Write a list comprehension to generate a list of squares from 1
to 5. S: [2×+2 for m in range (1,6)].
• What will be the output of the following code?
my_tuple = (1, 2, 3)
my_tuple[1] = 5 Immutable.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 184
UNIVERSITY OF CALCUTTA
Quick Recap
• What method is used to retrieve all keys from a dictionary?
• How can you update a value in a dictionary?
• How can you format floating-point numbers?
↳ x = 62.3678
-
print ("% un
4.37 "%)
62-367
print ("1. [Link]"-1.2)
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
UNIVERSITY OF CALCUTTA
462-3 185
Python: Basics
• Variables
• Data types
• Operators
• Arrays
• Flow Control
• Methods
• File Handling
• OOPS
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 186
UNIVERSITY OF CALCUTTA
Python Modules
• A Python module is a file containing Python definitions and
statements.
• Can define functions, classes, and variables
• Can also include runnable code
• Grouping related code into a module makes the code easier
to understand and use. fibonacci Series
• Helps the code logically organized. N-int (input ( "Upto what"))
N-0
y-1
2=0 while (2<=2):
DEPARTMENT OF APPLIED PHYSICS, print (2)
EVEN SEMESTER 187
UNIVERSITY OF CALCUTTA
n-∅ y:X 2:10 P N = Y
O Y = Z
Z = NtY
Define Python Module ¼
I/
⅔ 2 0 1 2 3 4 5
Imp 3 0
5
I 2 3 5
# Fibonacci numbers module import fibo
print([Link](2))
1
def fib(n): # write Fibonacci series up to n from fibo import fib
a, b = 0, 1 a-0, b: 1
0, 1,1, 2,3, 5....
while a < n:
print(a, end=' ')
from fibo import fib
a, b = b, a+b → a:b
print() b-ath
from fibo import *
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while a < n: Import all names
[Link](a)
a, b = b, a+b import sys
return result [Link](0,
'G:/Library/Project/Python/Jupyter_
if __name__ == "__main__": demo')
print('Running the fibo module')
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS, Import188
from
UNIVERSITY OF CALCUTTA
different path
Array
• A data structure which can hold more than one value at a
time.
• Collection or ordered series of elements of the same type
Variable: a
Value 1 2 3 … 99
Indexing a[0] a[1] a[2] … a[100]
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 189
UNIVERSITY OF CALCUTTA
Array and List
Array List
• Can have only one type of • Can have different types of
data data
• Operation can be • If different data types are
performed based on data stored, operation can not be
types performed
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 190
UNIVERSITY OF CALCUTTA
Create an Array
Import numpyas up
• First, import the array module
• Without alias: import array N: np-array
• Using alias: import array as arr
• Using * : from array import *
type → Only signed It
import array import array as arr from array import *
a = [Link](‘i’,[1,2,3,4]) a = [Link](‘i’,[1,2,3,4]) a = array(‘i’,[1,2,3,4])
array('i', [1, 2, 3, 4]) array('i', [1, 2, 3, 4]) array('i', [1, 2, 3, 4])
Array
Name of constructor
the module
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 191
UNIVERSITY OF CALCUTTA
Array Operation
• Accessing array elements:
Forward indexing a[0] a[1] … a[99]
Values 1 2 … 100
Backward indexing a[-100] a[-99] … a[-1]
• Determine length: import array
a = [Link](‘i’,[1,2,3,4])
len(a)
l l
l .
4 ✓
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 192
UNIVERSITY OF CALCUTTA
Array Operation
Single element
• Add elements to an array:
✓
Set of item index element
[Link](5) ✓ [Link]([6, 7]) [Link]([2, 8])
array('i', [1, 2, 3, 4, 5]) array('i', [1, 2, 3, 4, 5, 6, 7]) array('i', [1, 2, 8, 3, 4, 5, 6,
7])
• Removing elements:
• pop(): remove an element and return it
• remove(): remove an element with a specific value without return
it
import array Popping last element 3.7 pop is return
.
a = [Link](‘d’,[1.1,2.2,3.8, 3.1, 3.7]) Popping 4th element 3.1
print(“Popping last element”, [Link]())
→ 3.1 array(‘d’, [2.2, 3.8]) type fnc
print(“Popping 4th element”, [Link](3))
[Link](1.1) 3'/
print(a) [2. 2,3-8)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 193
UNIVERSITY OF CALCUTTA
Array Operation
• Concatenation: Joining array using the + symbol
import array
a = [Link](‘d’,[1.1,2.2,3.8])
b = [Link](‘d’,[3.1, 3.7]) array(‘d’,[1.1,2.2,3.8, 3.1, 3.7])
c = [Link](‘d’)
c = a + b double.
print(c)
• Slicing
import array
a = [Link](‘d’,[1.1,2.2,3.8]) array(‘d’,[1.1,2.2,3.8])
print(a[0:3])
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 194
UNIVERSITY OF CALCUTTA
Example: Storing and Manipulating
import array # Step 2: Import array
Student Marks module
marks = [Link]('i', [85, 90, 78,
88, 76]) # 'i' indicates an integer
• Start array
• Import the array module. print("First student's marks:",
• Create an array to store five student marks[0])
[95, 90,78, 88,76]
marks. • = 95
marks[1]
↑
• Access an element using an index. print("Updated Marks:", marks)
print("\nAll Student Marks:")
• Modify an element at a given index.
for mark in marks: 95 88
• Iterate through the array and print all 90 76
print(mark)
values. 78
[Link](89)
• Append a new value to the array.
print("After Appending:", marks)
↳ [95. 90,78, 88,1
• Remove an element from the array. [Link](78) 7.6189
-
• End print("After Removing 78:", marks)
DEPARTMENT OF APPLIED PHYSICS, ↳ [95,50, 88,76-89
EVEN SEMESTER 195
UNIVERSITY OF CALCUTTA
Python: Basics
• Variables
• Data types
• Operators
• Arrays
• Flow Control
• Methods
• File Handling
• OOPS
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 196
UNIVERSITY OF CALCUTTA
Python’s Statements
• Statements are the things to tell Python what your
programs should do
• Python Program Structure
• Programs are composed of modules.
• Modules contain statements.
• Statements contain expressions.
• Expressions create and process objects.
• Python syntax is composed of statements and expressions
• Semicolon can be used as statement separators
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 197
UNIVERSITY OF CALCUTTA
Python’s Statements
• Expressions process objects and are embedded in
statements
• Statements code the larger logic of a program’s operation
• Statements always exist in modules
Statement Role Example Statement Role Example Statement Role Example
Assignment Creating references a, *b = 'good', 'bad', 'ugly
Calls and other
Running functions [Link]("spam, ham")
expressions
print calls Printing objects print('The Killer', joke)
if "python" in text:
if/elif/else Selecting actions
print(text)
for x in mylist:
for/else Sequence iteration
print(x)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 198
UNIVERSITY OF CALCUTTA
Python’s Statements
Statement Role Example Statement Role Example Statement Role Example
while X > Y:
while/else General loops
print('hello')
while True:
pass Empty place holder
pass
while True:
break Loop exit
if exittest(): break
while True:
continue Loop continue
if skiptest(): continue
def f(a, b, c=1, *d):
def Functions and method
print(a+b+c+d[0])
def f(a, b, c=1, *d):
return Functions results
return a+b+c+d[0]
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 199
UNIVERSITY OF CALCUTTA
Python’s Statements
Statement Role Example Statement Role Example Statement Role Example
def gen(n):
yield Generator functions
for i in n: yield i*2
x = 'old'
global Namespaces def function():
global x, y; x = 'new'
def outer():
x = 'old'
nonlocal Namespaces (3.0+)
def function():
nonlocal x; x = 'new'
import Module access import sys
from Attribute access from sys import stdin
class Subclass(Superclass):
class Building objects staticData = []
def method(self): pass
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 200
UNIVERSITY OF CALCUTTA
Python’s Statements
Statement Role Example Statement Role Example Statement Role Example
try:
action()
try/except/ finally Catching exceptions
except:
print('action error')
raise Triggering exceptions raise EndSearch(location)
assert Debugging checks assert X > Y, 'X too small'
with open('data') as myfile:
with/as Context managers (2.6+)
process(myfile)
del data[k]
del Deleting references del data[i:j]
del [Link]
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 201
UNIVERSITY OF CALCUTTA
Flow Control
• Till now, understanding of python programming a series of
statements
• Python faithfully executes them in the same order
• What if you wanted to change the flow of how it works?
• Three flow control statements in Python - if, for and while
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 202
UNIVERSITY OF CALCUTTA
The if Statement
• The if statement is used to check a condition and if the
condition is true,
• Run a block of statements (called the if-block), else process
another block of statements (called the else-block)
• The else clause is optional
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 203
UNIVERSITY OF CALCUTTA
General Form of The if Statement
• The reserved word if begins a if statement.
• The condition is a Boolean expression that
determines whether or not the body will be
executed.
• A colon (:) must follow the condition.
• The block is a block of one or more
statements to be executed if the condition is
true.
• The statements within the block must all be
indented the same number of spaces from the
left.
• If the block contains just one statement, will
place it on the same line as the if
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 204
UNIVERSITY OF CALCUTTA
if Statement and Indentation
if x < 10: if x < 10: y = x
y = x
• How many spaces should you indent?
• Python requires at least one,
• Some programmers consistently use two, four (the most popular
number), but some prefer a more dramatic display and use eight
• A four space indentation for a block is the recommended Python style.
• In most programming editors you can set the Tab key to insert spaces
• Must use the same distance consistently throughout a Python program
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 205
UNIVERSITY OF CALCUTTA
if Statement
C, C++, Java, JavaScript, or Perl Python language
if (x > y) { if x > y:
x = 1; x = 1
y = 2; y = 2
}
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 206
UNIVERSITY OF CALCUTTA
Example: if Statement
Division of Two Numbers with Zero Check
Start
Prompt the user to enter the dividend
(numerator).
✓ # Get two integers from the user
dividend = int(input('Please enter the number
to divide: '))
Store the input in dividend.
divisor = int(input('Please enter dividend:
Prompt the user to enter the divisor '))
(denominator).
Store the input in divisor. # If possible, divide them and report the
result
Check if the divisor is not zero:
If divisor != 0, proceed with division: if divisor != 0:
Compute quotient = dividend / quotient = dividend/divisor
divisor print(dividend, '/', divisor, "=", quotient)
Display the result. print('Program finished')
Print "Program finished".
End
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 207
UNIVERSITY OF CALCUTTA
Example: if Statement (understand)
# Request input from the user # Extract and print hundreds-place digit
num = int(input("Please enter an integer in the range 0...9999: ")) digit = num//100 # Determine the hundreds-place digit
# Attenuate the number if necessary print(digit, end="") # Print the hundreds-place digit
if num < 0: # Make sure number is not too small num %= 100 # Discard hundreds-place digit
num = 0 # Extract and print tens-place digit
if num > 9999: # Make sure number is not too big digit = num//10 # Determine the tens-place digit
num = 9999 print(digit, end="") # Print the tens-place digit
print(end="[") # Print left brace num %= 10 # Discard tens-place digit
# Extract and print thousands-place digit # Remainder is the one-place digit
--
digit = num//1000 # Determine the thousands-place digit
print(digit, end="") # Print the thousands-place digit
print(num, end="") # Print the ones-place digit
print("]") # Print right brace
num %= 1000 # Discard thousands-place digit
Please enter an integer in the range 0...9999: 38
[0038]
Please enter an integer in the range 0...9999: -450
[0000]
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 208
UNIVERSITY OF CALCUTTA
If Else
• The reserved word if begins the if/else statement.
• The condition is a Boolean expression, determines whether or not the
if block or the else block will be executed.
• A colon (:) must follow the condition.
• The if-block is a block of one or more statements to be executed if the
condition is true.
• The if-block is a block of one or more statements to be executed if the
condition is true.
• it must be indented one level deeper than the if line: sometimes called the body
of the if.
• The reserved word else begins the second part of the if/else
statement. A colon (:) must follow the else.
• The else-block is a block of one or more statements to be executed if the
condition is false. It must be indented one level deeper than the
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 209
UNIVERSITY OF CALCUTTA
If Else
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 210
UNIVERSITY OF CALCUTTA
Example: if Statement
# Get two integers from the user
dividend = int(input('Please enter the number to divide:
'))
divisor = int(input('Please enter dividend: '))
# If possible, divide them and report the result
if divisor != 0:
print(dividend, '/', divisor, "=", dividend/divisor)
else:
print('Division by zero is not allowed')
Please enter the number to divide: 32
Please enter dividend: 0
Division by zero is not allowed
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 211
UNIVERSITY OF CALCUTTA
If Else
• Fundamental building block of software
Conditional
statement
Executed if answer is True
Executed if answer is
False
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 212
UNIVERSITY OF CALCUTTA
If Else example
Try running the example below.
What do you get?
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 213
UNIVERSITY OF CALCUTTA
Indentation matters!
• Code is grouped by its indentation
• Indentation is the number of whitespace or tab characters
before the code.
• If you put code in the wrong block then you will get
unexpected behavior
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 214
UNIVERSITY OF CALCUTTA
Extending if-else blocks
• We can add infinitely more if statements using elif
• elif = else + if which means that the previous statements
must be false for the current one to evaluate to true
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 215
UNIVERSITY OF CALCUTTA
Compound Boolean Expressions
• Any nonzero number or nonempty object is true.
• Zero numbers, empty objects, and the special object None are
considered false.
• A combination of two or more Boolean expressions using logical
operators is called a compound Boolean expression.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 216
UNIVERSITY OF CALCUTTA
Compound Boolean Expressions
• Logical operators and, or (left associative), and not
• Suppose e1 and e2 are two Boolean expressions
• e1 and e2 is true only if e1 and e2 are both true;
• if either one is false or both are false, the compound expression is false.
• Boolean expressions e1 and e2,
• e1 or e2 is false only if e1 and e2 are both false;
• if either one is true or both are true, the compound expression is true.
• If e is a true Boolean expression, not e is false; if e is false, not e is
true
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 217
UNIVERSITY OF CALCUTTA
Compound Boolean Expressions
x <= y and x <= z (x <= y) and (x <= z) x <= y<= z
x = 10
y = 20
b = (x == 10) # assigns True to b
if x == y == z: b = (x != 10) # assigns False to b
print('They are all the same') b = (x == 10 and y == 20) # assigns True to b
b = (x != 10 and y == 20) # assigns False to b
b = (x == 10 and y != 20) # assigns False to b
b = (x != 10 and y != 20) # assigns False to b
b = (x == 10 or y == 20) # assigns True to b
b = (x != 10 or y == 20) # assigns True to b
b = (x == 10 or y != 20) # assigns True to b
b = (x != 10 or y != 20) # assigns False to b
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 218
UNIVERSITY OF CALCUTTA
Compound Boolean Expressions
• The and operator evaluates left to right, this means that if
e1 is false, there is no need to evaluate e2.
• If it finds the expression to be false, it does not bother to
check the right expression. This approach is called short-
circuit evaluation.
• The order of the subexpressions can affect performance
if x < 10 and input("Print value (y/n)?") == 'y':
print(x)
expensive
• To prevent run-time errors expression
(x != 0) and (z/x > 1)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 219
UNIVERSITY OF CALCUTTA
Quick quiz
• What would happen if both conditions are True?
C
Only the first True condition executes in an if-elif-else block.
If both conditions are True, the first one in order executes, and others are skipped.
Solution: Rearrange conditions from most specific to least specific to ensure correct
behavior.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 220
UNIVERSITY OF CALCUTTA
If Statements
var1 = 100 (True)
if var1:
print ("1 - Got a true expression value")
print (var1)↳ 100
var2 = 0 (false)
if var2:
print ("2 - Got a true expression value")
print (var2)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 221
UNIVERSITY OF CALCUTTA
If Statements: A Few Special Cases
if a == b and c == d and \
d == e and f == g:
print('olde') # Backslashes allow continuations...
if (a == b and c == d and
d == e and e == f):
print('new') # But parentheses usually do too
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 222
UNIVERSITY OF CALCUTTA
If-Else Statements
var1 = 100
if var1:
print ("1 - Got a true expression value")
print (var1)
else:
print ("1 - Got a false expression value")
print (var1)
var2 = 0
f
if var2:
print ("2 - Got a true expression value")
print (var2)
else:
print ("2 - Got a false expression value")
EVEN SEMESTER
print
DEPARTMENT OF (var2)
APPLIED PHYSICS,
223
UNIVERSITY OF CALCUTTA
Example: Checking Even or Odd
Number
• Start
• Take an integer input from
the user.
• Use the modulus operator
(%) to check divisibility by 2:
• If num % 2 == 0, print "Even
Number".
• Otherwise, print "Odd
Number".
• End
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 224
UNIVERSITY OF CALCUTTA
Example: Checking User Login
Credentials
• Start
• Store predefined username
and password.
• Take username and password
input from the user.
• Compare the input with
stored credentials:
• If both match, print "Login
Successful".
• Otherwise, print "Invalid
Credentials".
• End
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 225
UNIVERSITY OF CALCUTTA
do nothing eat fivestar
The pass Statement
• In a code fragment the programmer wishes to do nothing if the
condition is not satisfied
if x < 0:
# Do nothing (This will not work!) not legal Python
else:
print(x)
if x < 0:
pass # Do nothing do nothing
else:
print(x)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 226
UNIVERSITY OF CALCUTTA
Nested Conditionals
• The statements in the block of the if or the else may be any Python
statements, including other if/else statements.
value = int(input("Please enter an integer value in the range 0...10: ")
if value >= 0: # First check
if value <= 10: # Second check
print("In range")
print("Done")
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 227
UNIVERSITY OF CALCUTTA
1 The if/else Ternary Expression
• Which sets A to either Y or Z, based on the truth value of X:
X = 1 A = Y if X else Z
Y = 2 print(A)
Z = 3
if X:
A = Y short-circuits
else:
A = Z
print(A)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 228
UNIVERSITY OF CALCUTTA
Example : if/else
• Display the discounted product price in store
• The discount structure in different slabs of discount −
• 20% on amount exceeding 10000,
• 10% for amount between 5000-10000,
• 5% if it is between 1000 to 5000.
• no discount if amount<1000
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 229
UNIVERSITY OF CALCUTTA
P: int (input (" Enter price"D
Example : if/else if P 710,000:
d: P # (002)
Print (d)
elif P) 5000:
d: P * (0.1)
Print (d)
esif. P > 1000 :
d =p * 10.05)
Print (d)
else:
d:O
Print ("No discounty
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 230
UNIVERSITY OF CALCUTTA
Example : if/else
• For instance consider a function to convert a numerical
grade to a letter grade, ’A’, ’B’, ’C’, ’D’ or ’F’, where the
cutoffs for ’A’, ’B’, ’C’, and ’D’ are 90, 80, 70, and 60
respectively. N = int(input( "Enter no."D
if 1790
Print( "Grade A")
ell/ A 780 and n Lgo
Print ("Grad eBM
ell f m 770 and M (680
Print( "Grade ea)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 231
UNIVERSITY OF CALCUTTA
Example : if/else
def letterGrade(score):
def letterGrade(score):
if score >= 90: if score >= 90:
letter = 'A' letter = 'A'
else: # grade must be B, C, D or F elif score >= 80:
if score >= 80: letter = 'B'
letter = 'B'
else: # grade must be C, D or F elif score >= 70:
if score >= 70: letter = 'C'
letter = 'C' elif score >= 60:
else: # grade must D or F letter = 'D'
if score >= 60:
else:
letter = 'D'
else: letter = 'F'
letter = 'F' return letter
return letter
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 232
UNIVERSITY OF CALCUTTA
Short-circuit Evaluation
• The act of avoiding executing parts of a Boolean expression
that have no effect on the final result.
• When Python detects that there is nothing to be gained by
evaluating the rest of a logical expression, it stops its
evaluation and does not do the computations in the rest of
the logical expression.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 233
UNIVERSITY OF CALCUTTA
Short-circuit Evaluation
• or: (Shortckt only if first term: True) print(1 or cdef check():
return "geeks"
• It checks the first statement
• If it’s true, Python returns that value
without checking the second statement print(1 and check()) # Output: geeks
• The second statement is only evaluated check()) # Output: 1
if the first one is false. print(0 or check() or 1) # Output:
geeks
• and: (short cut only if the first term = false")
print(0 or check() and 1) # Output: 1
• If the first statement is false, the entire
expression must be false,
An expression containing and or
• Only if the first value is true does it stops execution when the truth value
check the second statement and return of expression has been achieved.
the value.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 234
UNIVERSITY OF CALCUTTA
Short-circuit Evaluation
• all() returns True if all elements in def check(i):
a sequence are true. It stops print("geeks")
return i
evaluating when a False value is
encountered.
print(all(check(i) for i in [1, 1, 0, 0,
• any() returns True if at least one 3])) # Output: False
element in a sequence is true. It print(any(check(i) for i in [0, 0, 0, 1,
3])) # Output: True
stops evaluating when a True
value is found.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 235
UNIVERSITY OF CALCUTTA
Short-circuit Evaluation
• Do not evaluate the second operand of binary short-circuit
logical operator if the result can be deduced from the first
operand
• Also applies to nested logical operators
true false false true
not( (2>5) and (3/0 > 1) ) or (4/0 < 2)
Evaluates to true
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 236
UNIVERSITY OF CALCUTTA
Class Quiz 0-100000000005
• What is the output of the following program:
y = 0.1*3
if y != 0.3:
✓
print ('Launch a Missile')
else:
print ("Let's have peace")
Launch a Missile
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 238
UNIVERSITY OF CALCUTTA
Class Quiz
• What is the output of the following program:
import math
y = 0.1 * 3
if not [Link](y, 0.3, rel_tol=1e-9): # Allowing small rounding errors
print("Launch a Missile")
else:
print("Let's have peace")
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 239
UNIVERSITY OF CALCUTTA
Caution about Using Floats
• Representation of real numbers in a computer can not be
exact
• Computers have limited memory to store data
• Between any two distinct real numbers, there are infinitely many
real numbers.
• On a typical machine running Python, there are 53 bits of
precision available for a Python float
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 240
UNIVERSITY OF CALCUTTA
Caution about Using Floats
• The value stored internally for the decimal number 0.1 is
the binary fraction
0.00011001100110011001100110011001100110011001100110011010
• Equivalent to decimal value
0.1000000000000000055511151231257827021181583404541015625
• Approximation is similar to decimal approximation 1/3 =
0.333333333...
• No matter how many digits you use, you have an
approximation
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 241
UNIVERSITY OF CALCUTTA
Comparing Floats
• Because of the approximations, comparison of floats is not
exact.
• Solution?
• Instead of
x == y
use
abs(x-y) <= epsilon
where epsilon is a suitably chosen small value
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 242
UNIVERSITY OF CALCUTTA
Using if-elif-else for a Simple Menu
System
print("Select Operation:") elif choice == '3':
print("1. Addition") print("Result:", num1 * num2)
print("2. Subtraction") else:
print("3. Multiplication")
print("Result:", num1 / num2)
print("4. Division")
else:
choice = input("Enter choice (1/2/3/4): ")
print("Invalid input! Please select a
if choice in ('1', '2', '3', '4'): valid option.")
num1 = float(input("Enter first number:
"))
num2 = float(input("Enter second number:
"))
if choice == '1':
print("Result:", num1 + num2)
elif choice == '2':
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER
print("Result:", num1 - num2) 243
UNIVERSITY OF CALCUTTA
COMPUTER PROGRAMMING
PCC-EE 405
Nirmal Murmu
Department of Applied Physics
University of Calcutta
Course Outcomes
• At the end of this course, students will be able to learn about
• CO1: Identify fundamental programming concepts, data structures, and file
handling techniques used in software development.
• CO2: Explain the principles of object-oriented programming, event-driven
programming, and their applications in GUI and system programming.
• CO3: Develop basic to intermediate-level applications using programming
languages and libraries for file manipulation, data handling, and user interaction.
• CO4: Compare and evaluate different programming approaches, paradigms, and
tools for solving computational problems effectively.
• CO5: Assess the efficiency, scalability, and usability of developed applications,
optimizing code performance and debugging issues effectively.
•
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 2
UNIVERSITY OF CALCUTTA
Syllabus
• Module 1: Introduction to Visual basic (8 hour)
• Fundamentals of GUI development using [Link], Concepts of object, method and event in [Link],
Utilisation of various tools, Components and References, basic concept of event handling, I/O File
handling and data handling.
• Module 2: Visual basic Programming (10 hour)
• Learn to develop program in windows environment, simple display program, Key board and
mouse interactive program, Reading and writing I/O files, handling of other windows program -
like reading and writing Excel file, Excel plotting, interfacing of USB/COM ports, development of
net based application in client/server mode.
• Module 3: Introduction to Python libraries (10 hour)
• Python Types, Expressions, Strings, Lists, Tuples, Python memory model (names, mutable and
immutable values), List operations, Regular Expressions, Python Functions, Abstract Data types,
Classes and Objects in Python, Exception handling, Handling files, Python
Scientific/Statistical/Machine Learning Libraries.
• Module 4: Python programming (12 hour)
• Python Programming: Object based program using multi threading, I/O handling of files, Printing
and display using timer operation, program for handling of interfacing of cameras, program to
develop machine learning based applications.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 3
UNIVERSITY OF CALCUTTA
References
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 4
UNIVERSITY OF CALCUTTA
Lecture Plan
Lecture No. Topic Key Concepts
Variables, Data Types, and Python types, expressions,
1
Operators operators, type conversions
Lists, tuples, slicing, loops (for,
2 Arrays and Flow Control
while), conditional statements
Defining functions, arguments,
3 Methods and Functions
return values, recursion
Reading/writing files, handling CSV,
4 File Handling
JSON
Introduction to Scientific NumPy, Pandas, Matplotlib for data
5
Libraries processing
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 5
UNIVERSITY OF CALCUTTA
Lecture Plan
Lecture No. Topic Key Concepts
Object-Oriented Programming Classes, objects, inheritance,
1
(OOPs) in Python polymorphism
Multi-threading and Advanced File Threading basics, file operations,
2
Handling concurrent programming
Timers, Event Handling, and GUI Timer-based operations, GUI
3
Development programming using Tkinter/PyQt
Using OpenCV for image
Camera Interfacing and Data
4 processing, real-time data
Acquisition
acquisition
Machine Learning and AI Basics of Scikit-learn, TensorFlow,
5
Applications AI-driven applications
Final Project Discussion and Developing real-world
6
EVEN SEMESTER
Implementation DEPARTMENT OF APPLIED PHYSICS,
applications, project review 6
UNIVERSITY OF CALCUTTA
Timeline
Topic Activity
- Why do we use loops?
Introduction to Loops
- Difference between while loop and for loop
- Example 1: Printing numbers 1 to 10
Basic while Loop Example
- Example 2: while with a counter (Hands-on practice for students)
- Example 3: User login system (keep asking for correct password)
Practical while Loop Examples
- Example 4: Sum of first N numbers using while (Live coding and discussion)
- Conduct Quick Quiz (MCQs + coding questions)
Break and Quick Quiz on while Loops
- Discuss answers and common mistakes
- Difference between for and while loops
Introduction to for Loop
- When to use for loops instead of while loops
- Example 5: Printing numbers 1 to 10
Basic for Loop Example
- Example 6: Iterating through a list (Hands-on practice)
- Example 7: Iterating through a dictionary (student marks example)
Advanced for Loop Examples
- Example 8: Word frequency counter (Live coding and discussion)
- Explain break and continue
Control Statements (break, continue) - Example: Using break inside while to exit on condition
- Example: Using continue inside for loop to skip specific iterations
- Assign students a real-world problem using loops (e.g., Find Prime Factors using
Practical Hands-on Challenge while, Sum of Even/Odd numbers using for)
- Encourage students to solve it and discuss their approach
- Recap
D E P A key
R T M Etakeaways
N T O F A P P L I Efrom while
D PHYS and
ICS, UN I V E Rfor
S I T Yloops
OF
Recap and
EVENQ&A
SEMESTER CALCUTTA 244
- Answer any questions from students
While loop
• A while loop doesn't run for a predefined number of
iterations. Instead, it stops as soon as a given condition
becomes true/false.
3
4
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 245
UNIVERSITY OF CALCUTTA
WHILE loop
• The reserved word while begins the while statement.
• The condition determines whether the body will be (or will
continue to be) executed.
• A colon (:) must follow the condition
• block is a block of one or more statements to be executed
as long as the condition is true.
• block must be indented one level deeper than the line that begins
the while statement
• The block technically is part of the while statement.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 246
UNIVERSITY OF CALCUTTA
Example: WHILE loop
count = 1 # Initialize counter
while count <= 5: # Should we continue?
print(count) # Display counter, then
count += 1 # Increment counter
1
2
3
4
5
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 247
UNIVERSITY OF CALCUTTA
Example: WHILE loop
• Printing Numbers from 1 to 10 = N"
using while Loop While n ≤ 10:
• Algorithm Print (n)
Start rent /
Initialize a variable num = 1
Use a while loop with the condition num <= 10
Inside the loop:
Print num num = 1 # Step 2: Initialize variable
Increment num by 1
End while num <= 10: # Step 3: Condition check
print(num) # Step 4: Print number
num += 1 # Step 4: Increment number
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 248
UNIVERSITY OF CALCUTTA
Example: WHILE loop
# Program to add natural
Add natural n integer numbers: # numbers up to
Algorithm: # sum = 1+2+3+...+n
# To take input from the user,
Start # n = int (input ("Enter n: "))
Initialize a counter variable n = 10
# initialize sum and counter
num = 1 sum = 0 :
While num <= 10, do the following: i = 1
- .
while i <= n:
Increment num by 1 (num += 1)
sum = sum + i
Print num i = i+1 # update counter
# print the sum
End
print ("The sum is", sum)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 249
UNIVERSITY OF CALCUTTA
Example: while Loop with a Counter
• Algorithm
Start
Initialize a variable count = 2
Use a while loop with condition count <= 20
Inside the loop:
Print count
Increment count by 2
End count = 2 # Step 2: Initialize counter
while count <= 20: # Step 3: Condition check
print(count) # Step 4: Print even number
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 250
count += 2 # Step 4: Increment by 2
UNIVERSITY OF CALCUTTA
Example: while Loop with a Counter
• Modify the code to print only the first 10 multiples of
5 using a while loop! M: 1
While n ≤ 10:
Print (5ᵗʰ):
N: NH
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 251
UNIVERSITY OF CALCUTTA
Example: WHILE loop Doubt
Print a list of integer number # print a list of integer number
var='0'
while [Link]()==True:
var=input('enter a number..')
if [Link]()==True:
print ("Your input", var)
print ("End of while loop")
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 252
UNIVERSITY OF CALCUTTA
Example: WHILE loop
# Counts up from zero. The user continues the count by entering
# 'Y'. The user discontinues the count by entering 'N'.
count = 0 # The current count
entry = 'Y' # Count to begin with
while entry != 'N' and entry != 'n':
# Print the current value of count
print(count)
entry = input('Please enter "Y" to continue or "N" to quit: ')
if entry == 'Y' or entry == 'y’:
count += 1 # Keep counting
# Check for "bad" entry
elif entry != 'N' and entry != 'n’:
print('"' + entry + '" is not a valid choice')
# else must be 'N' or 'n'
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 253
UNIVERSITY OF CALCUTTA
Example: while Loop
• User Login System (Keep Asking for Correct Password)
• Algorithm
Start
Set correct_password = "Python123"
Ask the user to enter a password.
While the entered password is not correct:
Print "Incorrect password. Try again."
Ask for the password again.
When the correct password is entered, print "Access Granted!"
End
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 254
UNIVERSITY OF CALCUTTA
Example: while Loop Login System
correct_password = “Python123“ # Step 2: Set the correct
password
password = input("Enter password: ") # Step 3: Ask for user
input
# Step 4: Keep asking until the correct password is entered
while password != correct_password:
print("Incorrect password. Try again.")
password = input("Enter password: ")
print("Access Granted!") # Step 5: Successful login message
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 255
UNIVERSITY OF CALCUTTA
Example: WHILE loop
x = 'spam'
while x: # While x is not empty } IMP
print(x, end=' ')
x = x[1:] # Strip first character off x
spam pam am On
m After m string is empty
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 256
UNIVERSITY OF CALCUTTA
Definite Loops vs. Indefinite Loops
n = 1 n = 1
while n <= 10: stop = int(input())
print(n) while n <= stop:
n += 1 print(n)
n += 1
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 257
UNIVERSITY OF CALCUTTA
Abnormal WHILE Loop
n = 1
a = 1
while a==1:
print(n)
n += 1
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 258
UNIVERSITY OF CALCUTTA
Abnormal Loop Termination
• A while statement executes until its condition becomes false
• A running program checks this condition first to determine if it should
execute the statements in the loop’s body.
• It then re-checks this condition only after executing all the statements
in the loop’s body.
• Ordinarily a while loop will not immediately exit its body if its
condition becomes false before completing all the statements in its
body
x = 10
while x == 10:
print('First print statement in the while loop’)
x = 5 # Condition no longer true; do we exit immediately?
top-exit print('Second print statement in the while loop')
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 259
UNIVERSITY OF CALCUTTA
Example: Practical Example – User
Login System
• Algorithm
Start
Set correct_password = "Python123“
Ask the user to enter a password.
While the entered password is not correct:
Print "Incorrect password.
Try again."Ask for the password again.
When the correct password is entered:
Print "Access Granted!“
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 260
End UNIVERSITY OF CALCUTTA
Example: Practical Example – User
Login System
• Algorithm
correct_password = "Python123" # Step 2
Start password = input("Enter password: ") # Step 3
Set correct_password = "Python123“
Ask the user towhile
enter apassword
password.!= correct_password: # Step 4:
Condition
While the entered check
password is not correct:
print("Incorrect password. Try again.")
Print "Incorrect password.
password
Try again."Ask for = input("Enter
the password again. password: ") # Ask again
When the correct password is entered:
print("Access Granted!") # Step 5: Successful login
Print "Access Granted!“
End
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
261
UNIVERSITY OF CALCUTTA
Quick Quiz
How many times are we going to execute the while loop?
i
4
5
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 262
UNIVERSITY OF CALCUTTA
Quick Quiz
How many times are we going to execute the while loop?
while True:
❤
print('Inside while loop')
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 263
UNIVERSITY OF CALCUTTA
Quick Quiz
What will happen if the following code runs?
x = 5 5
while x > 0: 5
print(x) 5
5
5:
I
do times
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 264
UNIVERSITY OF CALCUTTA
Iterables
• Iterable means an object can be used in iteration
• The few datatypes are iterable
• Open files in Python are iterable
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 265
UNIVERSITY OF CALCUTTA
Iterators (doubt)
built-in Python
function
• If an object is iterable, it can be passed to the iter()
Returns iterator
• The few datatypes are iterable object
iterable containers
iter('apple') # String
iter(['apple', 'banana', 'cherry’]) # List
iter(('apple', 'banana', 'cherry’)) # Tuple
iter({'apple', 'banana', 'cherry’}) # Set
iter({'apple ': 1, 'banana ': 2, 'cherry ': 3}) # Dict
iter(42) # Integer
iter(3.1) # Float
iter(len) # Built-in function
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 266
UNIVERSITY OF CALCUTTA
Create an Iterator
• Iterator is a value producer that yields successive values
from its associated iterable object
• To create an object/class as an iterator: __iter__()
and __next__() to the object
• __iter__(): create iterator
• __next__(): obtain the next value from in iterator
a = ['Dog', 'Cow', 'Cat’]
itr = iter(a)
print(next(itr)) Traceback (most recent call last):
print(next(itr)) File "<string>", line 9, in <module>
print(next(itr)) StopIteration
print(next(itr))
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 267
UNIVERSITY OF CALCUTTA
Python Iterators
• Iterator retains its state internally, reset with each execution
• Doesn’t generate all the items
• Obtain values from an iterator in one direction
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 268
UNIVERSITY OF CALCUTTA
FOR loop
• Iterate over a sequence or an "iterable" object
• Allows us to iterate over a set amount of variables within a
data structure. During that we can manipulate each item
however we want
• Again, indentation is important here!
• Sequences and containers are iterable.
• Examples: tuples, lists, strings, dictionaries.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 269
UNIVERSITY OF CALCUTTA
Example
• Say we want to go over a list and print each item along with its
index
Already Index
(532T OVTLE
• What if we have much more than 4 items in the list, say, 1000?
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 270
UNIVERSITY OF CALCUTTA
Example: FOR Statement
> for m in list:
• Now with a for loop Print ("The fruit is'Ini'indek,list. index (al)
• Saves us writing more lines
• Doesn't limit us in term of size
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 271
UNIVERSITY OF CALCUTTA
Example: FOR Loop
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val 48
print ("The sum is", sum)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 272
UNIVERSITY OF CALCUTTA
Example: FOR Loop
# Iterate from i = 0 to i = 3 # Print list of item
for i in range(4): languages = ['Swift',
print(i) 'Python', 'Go']
O
for language in languages:
print(language)
2
3 Swift
Python
go.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 273
UNIVERSITY OF CALCUTTA
FOR loop with range()
End value
sum = 0 # Initialize sum • range(10) -> 0;1;2;3;4;5;6;7;8;9
for i in range(1, 100): • range(1, 10) -> 1;2;3;4;5;6;7;8;9
sum += i • range(1, 10, 2) -> 1;3;5;7;9
print(sum) • range(10, 0, -1) -> 10;9;8;7;6;5;4;3;2;1
• range(10, 0, -2) -> 10;8;6;4;2
• range(2, 11, 2) -> 2;4;6;8;10
• range(-5, 5) -> -5;-4;-3;-2;-1;0;1;2;3;4
Begin value • range(1, 2) -> 1
• range(1, 1) -> (empty)
• range(1, -1) -> (empty)
• range(1, -1, -1) -> 1;0 7 -101
• range(0) -> (empty)
Step value
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 274
UNIVERSITY OF CALCUTTA
Numerical FOR Loop
• Calculate square of n numbers
N: int (input(" Enterrange"D
for i in range (i, nti):
Print (" Square of i is:" i'*2)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 275
UNIVERSITY OF CALCUTTA
Iterating Through a Dictionary
} Hold, do
after dictionary
a = {'apple ': 1, 'banana ': 2, 'cherry ': 3}
# loop variable is assigned to the dictionary’s keys
for k in a:
print(k)
# To access the dictionary values within the loop
for k in a:
print(a[k])
# To access the dictionary values within the loop
for v in [Link]():
print(v)
# To access the dictionary both the keys and values within the loop
print([Link]())
for k, v in [Link]():
print('k =', k, ', v =', v)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 276
UNIVERSITY OF CALCUTTA
DEPARTMENT OF APPLIED PHYSICS, UNIVERSITY
• Algorithm
Start
OF CALCUTTA
Take a sentence input from the user.
Convert the sentence to lowercase and split it
Example: into a list of words.
Create an empty dictionary to store word
Word counts.
Use a for loop to iterate through each word:
Frequency If the word is already in the dictionary,
increment its count.
Counter
Otherwise, add the word with an initial
count of 1.
Sort the dictionary based on word occurrences
in descending order.
Print the top N occurring words.
End
EVEN SEMESTER 277
# Step 2: Take input from user
sentence = input("Enter a sentence: ").lower()
# Step 3: Split the sentence into words
words = [Link]()
# Step 4: Create an empty dictionary to store word frequency
word_count = {}
# Step 5: Iterate through the word list using a for loop
for word in words:
if word in word_count:
word_count[word] += 1 # Increment count if word exists
else:
word_count[word] = 1 # Add word with count 1
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 278
UNIVERSITY OF CALCUTTA
# Step 6: Sort the dictionary based on word frequency (descending
order)
sorted_word_count = sorted(word_count.items(), key=lambda x: x[1],
reverse=True)
# Step 7: Print top occurring words
print("\nWord Frequency Count:")
for word, count in sorted_word_count:
print(f"{word}: {count}")
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 279
UNIVERSITY OF CALCUTTA
Control Statement & Description
• break statement m- s
• Terminates the loop statement and transfers execution to the
statement immediately following the loop.
• continue statement
N = -S
3
• Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
• pass statement
• The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to
execute.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 280
UNIVERSITY OF CALCUTTA
Break statement
• Allows us to go(break) out of a loop preliminary.
• Adds a bit of controllability to a while loop.
• Usually used with an if.
• Can also be used in a for loop. sum = 0 # Initialize sum
entry = 0 # Ensure the loop is entered
# Request input from the user
print("Enter numbers to sum, negative number ends list:")
while True: # Loop forever? Not really
entry = int(input()) # Get the value
if entry < 0: # Is number negative number?
break # If so, exit the loop
sum += entry # Add entry to running sum
print("Sum =", sum) # Display the sum
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 281
UNIVERSITY OF CALCUTTA
Break statement
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 282
UNIVERSITY OF CALCUTTA
Example: Break Statement
i = 1 # Demonstrating Use of
Python break Statement
while i < 6:
print(i) 1 for letter in 'Python':
if letter == 'h':
if i == 3: 2 break
break print ('Current Letter
i += 1 3 :', letter)
P
y
t
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 283
UNIVERSITY OF CALCUTTA
Example: Break Statement
fruits = ["apple", # Checking for a Number in
"banana", "cherry"] List
no=int(input('any number: '))
for x in fruits:
numbers=[11,33,55,39,55,75,37
print(x) ,21,23,41,13]
if x == "banana": for num in numbers:
if num==no:
break
print ('number found
apple in list')
break
banana else:
print ('number not found
in list')
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 284
UNIVERSITY OF CALCUTTA
The CONTINUE Statement
• break statement inside a loop, it skips the rest of the body
of the loop and exits the loop
• continue statement skips the rest of the body of the loop for
current iteration and immediately checks the loop’s
condition
• If the loop’s condition remains true, the loop’s execution
resumes at the top of the loop
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 285
UNIVERSITY OF CALCUTTA
Example: The CONTINUE Statement
i = 0 # Iterate over a
while i < 6: 1 sequence but skipping a
i += 1 particular item
if i == 3:
2 for letter in 'Python':
continue 4 if letter == 'h':
print(i) continue
5 print ('Current
Letter:', letter)
6
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 286
UNIVERSITY OF CALCUTTA
Example: The CONTINUE Statement
# Checking Prime Factors # Checking Prime Factors
1. Accept input from user (n) num = 60
2. Set divisor (d) to 2 print ("Prime factors
3. Perform following till n>1 for: ", num)
4. Check if given number (n) is divisible d=2
by divisor (d).
while num > 1:
5. If n%d==0
a. Print d as a factor
if num%d==0:
b. Set new value of n as n/d print (d)
c. Repeat from 4 num=num/d
6. If not continue
a. Increment d by 1 d=d+1
b. Repeat from 3
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 287
UNIVERSITY OF CALCUTTA
Example: The CONTINUE Statement
Calculate the sum of the 𝑛 numbers
sum = 0
done = False
while not done:
val = int(input("Enter positive integer (999 quits):"))
if val < 0:
print("Negative value", val, "ignored")
continue # Skip rest of body for this iteration
if val != 999:
print("Tallying", val)
sum += val
else:
done = (val == 999) # 999 entry exits loop
print("sum =", sum)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 288
UNIVERSITY OF CALCUTTA
The continue Statement
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 289
UNIVERSITY OF CALCUTTA
The PASS Statement
• Used when a statement is required syntactically but do not
want any command or code to execute
while True:
pass # Busy-wait for keyboard interrupt (Ctrl+C)
• Used is as a place-holder for a function or conditional
bodyto keep thinking at a more abstract level.
• The pass is silently ignored:
def initlog(*args):
pass # Remember to implement this!
def initlog(*args):
EVEN SEMESTER
... DEPARTMENT OF APPLIED PHYSICS,
290
UNIVERSITY OF CALCUTTA
Example: PASS Statement
for letter in 'Python':
l p
if letter == 'h':
y
pass
print ('This is pass block') +
print ('Current Letter :', letter) b
print ("Good bye!") O
n
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 291
UNIVERSITY OF CALCUTTA
WHILE/ELSE
• Python loops support an optional else block
• The else block in the context of a loop provides code to
execute when the loop exits normally else block does not
execute
• If the loop terminates due to a break statement
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 292
UNIVERSITY OF CALCUTTA
Example: WHILE/ELSE
# Add five nonnegative numbers supplied by the user
count = sum = 0
print('Please provide five nonnegative numbers when prompted')
while count < 5:
[ .
# Get value from the user - .
val = float(input('Enter number: '))
-
if val < 0:
print('Negative numbers not acceptable! Terminating')
break
count += 1
sum += val
else:
print('Average =', sum/count)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 293
UNIVERSITY OF CALCUTTA
FOR/ELSE
• Else-block will be executed when the loop is finished
O S
so 651
for x in range(6):
print(x) n-5
else:
print("Finally finished!")
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 294
UNIVERSITY OF CALCUTTA
Example: FOR/ELSE
# Vowel count
word = input('Enter text (no X\'s, please): ')
vowel_count = O0
- out
for vc in word:
if c == 'A' or c == 'a' or c == 'E' or c == 'e' \
or c == 'I' or c == 'i' or c == 'O' or c == 'o':
∅
print(c, ', ', sep='', end='') # Print the vowel
vowel_count += 1 # Count the vowel
# elif c == 'X' or c =='x': I '
• 9"
j
# print('X not allowed')
# break
else:
print(' (', vowel_count, ' vowels)', sep='')
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 295
UNIVERSITY OF CALCUTTA
Example: Loop with Function
# Checking for Even Numbers
def contains_even_number(lst):
for ele in lst:
if ele % 2 == 0:
print("The list contains an even number")
break # Terminate the loop
else:
print("The list does not contain an even number")
# Example usage:
print("For List 1:")
contains_even_number([1, 9, 8])
print("\nFor List 2:")
contains_even_number([1, 3, 5])
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 296
UNIVERSITY OF CALCUTTA
Quiz
• What will be the output of the following program
✓
# print all odd numbers < 10
i = 1
while i <= 10:
if i%2==0: # even 7
continue
print (i, end=‘ ‘)
i = i+1
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 297
UNIVERSITY OF CALCUTTA
Continue and Update Expr But ache
✓
• Make sure continue does not bypass update-expression for
while loops
# print all odd numbers < 10
i = 1 i is not incremented
while i <= 10: when even number
if i%2==0: # even encountered.
continue Infinite loop!!
print (i, end=‘ ‘)
i = i+1
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 298
UNIVERSITY OF CALCUTTA
Problem
• Problem 1: Find Prime Factors of a Number (Using while loop,
modulus operator %, integer division //, prime factorization.)
• Algorithm
Start
Take an integer N from the user.
Start with a divisor d = 2 (smallest prime number).
While N is greater than 1:
If N is divisible by d:
Print d
Divide N by d (N = N // d)
Else, increase d by 1.
End
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 299
UNIVERSITY OF CALCUTTA
Problem
• Problem 2: Sum of Even and Odd Numbers (Using for
Loop)
• Algorithm
Start
Take an integer N from the user.
Initialize sum_even = 0 and sum_odd = 0.
Use a for loop from 1 to N:
If the number is even, add it to sum_even.
Else, add it to sum_odd.
Print both sums.
End
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 301
UNIVERSITY OF CALCUTTA
COMPUTER PROGRAMMING
PCC-EE 405
Nirmal Murmu
Department of Applied Physics
University of Calcutta
Course Outcomes
• At the end of this course, students will be able to learn about
• CO1: Identify fundamental programming concepts, data structures, and file
handling techniques used in software development.
• CO2: Explain the principles of object-oriented programming, event-driven
programming, and their applications in GUI and system programming.
• CO3: Develop basic to intermediate-level applications using programming
languages and libraries for file manipulation, data handling, and user interaction.
• CO4: Compare and evaluate different programming approaches, paradigms, and
tools for solving computational problems effectively.
• CO5: Assess the efficiency, scalability, and usability of developed applications,
optimizing code performance and debugging issues effectively.
•
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 2
UNIVERSITY OF CALCUTTA
Syllabus
• Module 1: Introduction to Visual basic (8 hour)
• Fundamentals of GUI development using [Link], Concepts of object, method and event in [Link],
Utilisation of various tools, Components and References, basic concept of event handling, I/O File
handling and data handling.
• Module 2: Visual basic Programming (10 hour)
• Learn to develop program in windows environment, simple display program, Key board and
mouse interactive program, Reading and writing I/O files, handling of other windows program -
like reading and writing Excel file, Excel plotting, interfacing of USB/COM ports, development of
net based application in client/server mode.
• Module 3: Introduction to Python libraries (10 hour)
• Python Types, Expressions, Strings, Lists, Tuples, Python memory model (names, mutable and
immutable values), List operations, Regular Expressions, Python Functions, Abstract Data types,
Classes and Objects in Python, Exception handling, Handling files, Python
Scientific/Statistical/Machine Learning Libraries.
• Module 4: Python programming (12 hour)
• Python Programming: Object based program using multi threading, I/O handling of files, Printing
and display using timer operation, program for handling of interfacing of cameras, program to
develop machine learning based applications.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 3
UNIVERSITY OF CALCUTTA
References
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 4
UNIVERSITY OF CALCUTTA
Lecture Plan
Lecture No. Topic Key Concepts
Variables, Data Types, and Python types, expressions,
1
Operators operators, type conversions
Lists, tuples, slicing, loops (for,
2 Arrays and Flow Control
while), conditional statements
Defining functions, arguments,
3 Methods and Functions
return values, recursion
Reading/writing files, handling CSV,
4 File Handling
JSON
Introduction to Scientific NumPy, Pandas, Matplotlib for data
5
Libraries processing
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 5
UNIVERSITY OF CALCUTTA
Lecture Plan
Lecture No. Topic Key Concepts
Object-Oriented Programming Classes, objects, inheritance,
1
(OOPs) in Python polymorphism
Multi-threading and Advanced File Threading basics, file operations,
2
Handling concurrent programming
Timers, Event Handling, and GUI Timer-based operations, GUI
3
Development programming using Tkinter/PyQt
Using OpenCV for image
Camera Interfacing and Data
4 processing, real-time data
Acquisition
acquisition
Machine Learning and AI Basics of Scikit-learn, TensorFlow,
5
Applications AI-driven applications
Final Project Discussion and Developing real-world
6
EVEN SEMESTER
Implementation DEPARTMENT OF APPLIED PHYSICS,
applications, project review 6
UNIVERSITY OF CALCUTTA
Python: Basics
• Variables
• Data types
• Operators
• Arrays
• Flow Control
• Methods ✓
• File Handling
• OOPS
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 303
UNIVERSITY OF CALCUTTA
Timeline
Time Slot Topic Activity
Explain built-in methods with
0 - 10 min Introduction to Methods
examples
10 - 30 min List, String, Dictionary Methods Hands-on practice
Explain return, arguments,
30 - 45 min Defining User-Defined Methods
default values -
Live coding with lambda,
45 - 60 min Lambda & Scope of Variables L
global variables
60 - 70 min Introduction to File Handling Why file handling is needed?
Hands-on practice with text
70 - 90 min Reading & Writing Files
files
90 - 110 min Working with CSV & JSON Files Example programs
110 - 120 min Exception Handling in File I/O Live demo, Q&A
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 304
UNIVERSITY OF CALCUTTA
Functions
• Some programs are repeatedly used in other Python script
for performing some operation
• A function is a block of reusable code which only runs when
it is called.
• For example compute square root of a number
• Can be computed by writing a code in the Python script
Y • Use that piece of code where require (copy-paste)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 305
UNIVERSITY OF CALCUTTA
doubt
Example: Calculation of Square Root
# File [Link]
# Get value from the user
val = float(input('Enter number: '))
# Compute a provisional square root
root = 1.0
# How far off is our provisional root?
diff = root*root - val
# Loop until the provisional root
# is close enough to the actual root
while diff > 0.00000001 or diff < -0.00000001:
print(root, 'squared is', root*root) # Report how we
are doing
root = (root + val/root) / 2 # Compute new
provisional root
# How bad is our current approximation?
diff = root*root - val
# Report approximate square root
print('Square root of', val, '=', root)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 306
UNIVERSITY OF CALCUTTA
Standard Functions in Python
• One way to make code more reusable is by packaging it in
functions
• A function is a unit of reusable code
• Some of the functions available in the Python standard library.
• Python provides a collection of standard functions stored in
O
libraries called modules.
• These functions include print, input, int, float, str, and type.
• The Python standard library includes many other functions
useful for common programming tasks.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 308
UNIVERSITY OF CALCUTTA
Function-related Tools
Statement Examples
Calls myfunc('spam', 'eggs', meat=ham)
def, def adder(a, b=1, *c):
return return a + b + c[0]
global def changer():
global x; x = 'new'
nonlocal def changer():
nonlocal x; x = 'new'
yield def squares(x):
for i in range(x): yield i ** 2
lambda funcs = [lambda x: x**2, lambda x: x*3]
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 309
UNIVERSITY OF CALCUTTA
w
Function-related Tools def fu ( c
"1
• def is executable code
• function does not exist until Python reaches and runs the def
• it’s legal to nest def statements inside if statements, while loops,
and even other defs
• def creates an object and assigns it to a name
• generates a new function object and assigns it to the function’s
name
• attributes attached to them to record data
• lambda creates an object but returns it as a result
• return sends a result object back to the caller
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 310
UNIVERSITY OF CALCUTTA
Function-related Tools
• yield sends a result object back to the caller, but remembers
where it left off
• global declares module-level variables that are to be
assigned
• nonlocal declares enclosing function variables that are to
be assigned
• Allows enclosing functions to serve as a place to retain state
• Arguments are passed by assignment
• Arguments, return values, and variables are not declared
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 311
UNIVERSITY OF CALCUTTA
Python Function g ###in.. "b
a i..
• In Python, a function is a named block of code that
performs a specific task
• Python function works similar to mathematical function
#Syntax of Python function #Syntax of Python function
def function_name(parameters): def <name>(arg1, arg2,... argN):
"""docstring""" """docstring"""
#statement(s) <statements>
defreturn
add (Rigy
my >→ add-lambe bda may: Nty
Point (add/5,31) Pr int (ad ida↳(51n3o)need for return
8 ↳ faster response.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER - .
add (5, 3) UNIVERSITY OF CALCUTTA
312
5, 3
Nested Python Function
• Do not need to be fully defined before the program runs
• defs are not evaluated until they are reached and run
if test:
def func(): # Define func this way
...
else:
def func(): # Or else this way
...
...
func() # Call the version selected and built
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 313
UNIVERSITY OF CALCUTTA
Why Use Functions?
• Maximizing code reuse and minimizing redundancy
• allow us to code an operation in a single place and use it
in many places
• Procedural decomposition
• one function for each subtask in the process
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 314
UNIVERSITY OF CALCUTTA
OOPS ept where a
sing . can behave differently
Polymorphism bas , data its interacting
r
• The meaning of an operation depends on the objects being
operated upon
da5M
def times(x, y): # Create and assign function
return x * y # Body executed when called
print(times(2, 4))
print(times('Ni', 4))
→8 Ni Ni Ni Ni Function
-
[0] * y
= [oooo] 3- f
p of
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 315
UNIVERSITY OF CALCUTTA
Example: Calculation of Square Root
Function # File [Link]
# Get value from the user
val = float(input('Enter number: '))
def Srout (n): def squareroot(val):
return (NAAS)
"""
This function calculates square root
of the value passed in as parameter.
Newton ✗
N-int (input ("Entera")) """
# Compute a provisional square root Raphson Babif
root = 1.0
Print (snot (a)
lion
# How far off is our provisional root?
diff = root*root - val
# Loop until the provisional root
# is close enough to the actual root
while diff > 0.00000001 or diff < -0.00000001:
print(root, 'squared is', root*root) # Report how we are doing
root = (root + val/root) / 2 # Compute new provisional root
# How bad is our current approximation?
diff = root*root - val
return root
r * O)
# Report approximate square root
n root =squareroot(val)
print(root)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 316
UNIVERSITY OF CALCUTTA
Example: Calculation of Square Root
Function
• All functions are not automatically invoked by interpreter ->
import
• Module: collection of functions
Client code or
Importing sqrt function
calling code
from math module
from math import sqrt
def sroot (M
# Get value from the user
import math num = float(input("Enter number: "))
return (math-sort (n) # Compute the square root Function invocation or
root = sqrt(num) function call
N = int (input ("enter")
# Report result
Print (sroot (x)) print("Square root of", num, "=", root)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 317
UNIVERSITY OF CALCUTTA
M
Functions and Modules
• A Python module is simply a file that contains Python code.
• The name of the file dictates the name of the module;
• for example, a file named [Link] contains the functions available
from the standard math module
• The Python standard library contains thousands of
functions distributed throughout more than 230 modules.
• One of the modules, known as the built-ins module (actual
name __builtins__), In modules
• contains print, input, etc.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 318
UNIVERSITY OF CALCUTTA
import math *
Functions and Modules
amath. squt
how
• Programmers must use one or more import statements
within a program or within the interactive interpreter
• The Python distribution for a given platform stores these
standard modules somewhere on the computer’s hard
drive.
• The interpreter knows where to locate these standard
modules when an executing program needs to import
them. import module
Module-funch
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 319
UNIVERSITY OF CALCUTTA
Functions and Modules
• Python provides a number of ways to import functions from
a module
• from math import sqrt, log10, cos
• from math import sqrt
• Can import the entire module, as shown here:
• import math
import math
y = [Link](x)
print(math.log10(100)) qualified name: (module-
[Link]-name)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 320
UNIVERSITY OF CALCUTTA
Python Functions
sart
Sgt 1
• There are broadly two types,
• Built-in functions
• User defined functions
=
• The Python standard library, comes with installation,
includes,
• built-in functions
• text processing services
• numeric and mathematical modules
• math, number, random, statistics, etc.
• concurrent execution
• threading, multiprocessing, etc.
Ref: [Link]
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 321
UNIVERSITY OF CALCUTTA
The Built-in Functions
No import s. ment needed abs
• These functions include print, input, int, float, str, and type
• The __builtins__ module is special because its components
are automatically available to any Python program with—
no import statement is required
• The full name of the print function is __builtins__.print
>>> print('Hi’)
Hi
print >>> __builtins__.print('Hi’)
Hi
- builtins. print >>> id(__builtins__.print)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 322
UNIVERSITY OF CALCUTTA
The Built-in Functions
• The dir is another built-in function, to check directory
• dir(__builtins__): reveals all the components that a module has to
offer
• The parameter passed by the caller is known as the actual
parameter. or argument. value put in c e fnc inside prog
• The parameter specified by the function is called the formal
parameter. given -Sno defin
• During a function call the first actual parameter is assigned
to the first formal parameter, the second actual parameter
is assigned to the second formal parameter, etc.
• call [Link](10,2) computes 102 = 100
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 323
UNIVERSITY OF CALCUTTA
Python __builtins__ Functions
Python Built-in Functions
'abs' 'classmethod' 'enumerate' 'hash' 'locals' 'property' 'str'
'all' 'compile' 'eval' 'help' 'map' 'range' 'sum'
'any' 'complex' 'exec' 'hex' 'max' 'repr' 'super'
'ascii' 'copyright' 'execfile' 'id' 'memoryview' 'reversed' 'tuple'
'bin' 'credits' 'filter' 'input' 'min' 'round' 'type'
'bool' 'debugcell' 'float' 'int' 'next' 'runcell' 'vars'
'breakpoint' 'debugfile' 'format' 'isinstance' 'object' 'runfile' 'zip'
'bytearray' 'delattr' 'frozenset' 'issubclass' 'oct' 'set'
'bytes' 'dict' 'get_ipython' 'iter' 'open' 'setattr'
'callable' 'dir' 'getattr' 'len' 'ord 'slice'
'cell_count' 'display' 'globals' 'license' 'pow' 'sorted'
'chr' 'divmod' 'hasattr' 'list' 'print' 'staticmethod'
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 324
UNIVERSITY OF CALCUTTA
Python Standard Library: math
# List the prime numbers for the range 𝑛
✗
from math import sqrt
max_value = int(input('Display primes up to what value? '))
value = 2 # Smallest prime number
while value <= max_value:
# See if value is prime
is_prime = True # Provisionally, value is prime
# Try all possible factors from 2 to value - 1
trial_factor = 2
root = sqrt(value) # Compute the square root of value
while trial_factor <= root:
if value % trial_factor == 0:
is_prime = False # Found a factor
break # No need to continue; it is NOT prime
trial_factor += 1 # Try the next potential factor
if is_prime:
print(value, end= ' ') # Display the prime number
value += 1 # Try the next potential prime number
print() # Move cursor down to next line
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 325
UNIVERSITY OF CALCUTTA
time Function
• The time module contains a number of functions that relate
to time.
• The time is represented as the number of seconds since
January 1, 1970.
• This is the point at which UNIX time starts, also called the
“epoch.”.
time
Randon
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 326
UNIVERSITY OF CALCUTTA
time Function
Start
• time.perf_counter:
• measure elapsed time
• take difference between the first call to time.perf_counter and the
second call to time.perf_counter represents an elapsed time in
seconds;
• [Link]. The [Link] function suspends the program’s
execution for a specified number of seconds.
from time import perf_counter from time import sleep
print("Enter your name: ", end="") for count in range(10, -1, -1): # Range
start_time = perf_counter() 10, 9, 8, ..., 0 10
print(count) # Display the count
name = input()
sleep(1) 9
elapsed = perf_counter() - start_time
print(name, "it took you", elapsed, "seconds
to respond")
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 327
UNIVERSITY OF CALCUTTA
time Function
• [Link](): returns the number of seconds passed since
epoch → 1ˢᵗ Jan 1970
• [Link](): takes seconds passed since epoch as an
argument and returns a string representing local time
Day Mont Date Hour Min Second
Year
only retur
import time selon import time Sun Jan 5 11: 32: 2 3 2022
seconds = [Link]()
print("Seconds since epoch =", # seconds passed since epoch
seconds) seconds = 1654428743.6917613
local_time = [Link](seconds)
print("Local time:", local_time)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 328
UNIVERSITY OF CALCUTTA
time Function
• [Link](): accepts an epoch time and returns
a struct_time object
import time
result = [Link](0)
print("result:", result)
print("\nyear:", result.tm_year)
print("month:", result.tm_mon)
print("day of the month:", result.tm_mday)
print("tm_hour:", result.tm_hour)
print("minute of the hour:", result.tm_min)
print("second of the minute:", result.tm_sec)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 329
UNIVERSITY OF CALCUTTA
Random Numbers
• Some applications require behavior that appears random.
• All algorithmic random number generators actually
produce pseudorandom numbers, not true random
numbers.
• If the generator is used long enough, the pattern of
numbers produced repeats itself exactly.
• A sequence of true random numbers would not contain
such a repeating subsequence.
• Python standard library has a very good pseudorandom
number generator based the Mersenne Twister algorithm.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 330
UNIVERSITY OF CALCUTTA
Random Numbers • 1001
"
• Some applications require behavior that appears random.
• All algorithmic random number generators actually
produce pseudorandom numbers, not true random
numbers.
• If the generator is used long enough, the pattern of
numbers produced repeats itself exactly.
• A sequence of true random numbersfrom random would not seed
import randrange, contain
such a repeating subsequence. seed(23) # Set random number seed
• Python standard library has a veryprint(randrange(1,
good pseudorandom
for i in range(0, 100): # Print 100 random numbers
✓
1001), end=' ') # Range
number generator based the Mersenne Twister algorithm.
1...1,000, inclusive
print()
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 331
UNIVERSITY OF CALCUTTA
Random Numbers
• The [Link] function establishes the initial value
[Link] returns the next value in the sequence of
pseudorandom values
• The program begins its pseudorandom number generation with
a seed value, 23
• E.g.:“take a number x, add 900 +x, then subtract 52.”
• If [Link] function is omitted, the program derives its
initial value in the sequence from the time kept by the operating
system from random import randrange, seed
Ifthe seed seed(23) # Set random number seed
for i in range(0, 100): # Print 100 random numbers
value is changed print(randrange(1, 1001), end=' ') # Range
1...1,000, inclusive
We get diff print()
olp each time
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 332
UNIVERSITY OF CALCUTTA
Random Numbers: The Rolling of a
Die
from random import randrange elif value == 4:
# Roll the die three times print("| * * |")
for i in range(0, 3): print("| |")
# Generate random number in the range 1...7 print("| * * |")
value = randrange(1, 7) elif value == 5:
# Show the die print("| * * |")
print("+-------+") print("| * |")
if value == 1: print("| * * |")
print("| |") elif value == 6:
print("| * |") print("| * * * |")
print("| |") print("| |")
elif value == 2: print("| * * * |")
print("| * |") else:
print("| |") print(" *** Error: illegal die value ***")
print("| * |") print("+-------+")
elif value == 3:
print("| * |")
print("| * |")
print("| * |")
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 333
UNIVERSITY OF CALCUTTA
System-specific Functions
• The sys module provides a number of functions and
variables that give programmers access to system
specific information.
import sys
sum = 0
while True:
x = int(input('Enter a number (999 ends):’))
if x == 999:
[Link](0) → stop
sum += x
print('Sum is', sum)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 334
UNIVERSITY OF CALCUTTA
stringas expression
The eval and exec Functions
• eval() allows you to evaluate arbitrary Python expressions
from a string-based or compiled-code-based input.
• eval is a built-ins function named that evaluate a string in the
same way that the interactive shell would evaluate it
eval("2 ** 8") x1 = eval(input('Entry x1? ‘))
code = compile("5 + 4", "<string>", print('x1 =', x1, ' type:', type(x1))
"eval") # compiled-code-based x2 = eval(input('Entry x2? ‘))
eval(code) print('x2 =', x2, ' type:', type(x2))
print(eval(input())) x3 = eval(input('Entry x3? ‘))
print('x3 =', x3, ' type:', type(x3))
Print "2*8") → 298 x4 = eval(input('Entry x4? ‘))
print('x4 =', x4, ' type:', type(x4))
Prontleval ("2*81- 16/ x5 = eval(input('Entry x5? ‘))
print('x5 =', x5, ' type:', type(x5))
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 335
UNIVERSITY OF CALCUTTA
execs executes all
The eval and exec Functions lines as code in
string
code:"
for i in range e)
Parse expression
print (i)
n
Compile it to bytecode
exec (Code)
Evaluate it as a Python expression
Return the result of the evaluation
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 336
UNIVERSITY OF CALCUTTA
Python Function
Aspect Method Function Module Library
A file containing
A function associated A block of A collection of modules
Definition Python definitions
with an object reusable code packaged together
and functions
How it's called [Link]() function() [Link]() [Link]()
Used Imported using
Used with data types Imported using import
Where it’s used independently or import
like strings, lists, dicts library_name
within code blocks module_name
import math import numpy
Example "abc".upper() print("Hello")
[Link](4) [Link]([1, 2, 3])
Bound to a Independent or Framework or collection of
Type .py file
class/object user-defined modules
Only operates on Any logic or Functions, classes, Modules, tools, datasets,
Can contain...
object’s data computation variables sub-libraries
DEPARTMENT OF APPLIED PHYSICS, UNIVERSITY OF
EVEN SEMESTER CALCUTTA 337
Python Function
# Function
def square(x):
return x * x
# Method
s = "python"
print([Link]())
# Module
import math
print([Link](16))
# Library
import numpy as np
a = [Link]([1, 2, 3])
print(a)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 338
UNIVERSITY OF CALCUTTA
Python Method
• String Methods
Method Description Example
lower() Converts to lowercase "Python".lower() → 'python'
upper() Converts to uppercase "hello".upper() → 'HELLO'
strip() Removes leading/trailing spaces " text ".strip() → 'text'
"apple".replace("a", "A") →
replace() Replaces part of string
'Apple'
find() Finds substring index "hello".find("e") → 1
Splits by whitespace or
split() "a,b,c".split(',') → ['a', 'b', 'c']
separator
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 339
UNIVERSITY OF CALCUTTA
Python Method
• List Methods
• Dictionary Methods
• Tuple Methods
• Set Methods
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 340
UNIVERSITY OF CALCUTTA
User Defined Function
• So far, the code has been placed within a single block of code
• That single block may have contained sub-blocks for the bodies
of structured statements like if and while,
• The program’s execution begins with the first statement in the
block and ends when the last statement in that block is finished.
• A single block of code (like in all our programs to this point) that
does all the work itself is called monolithic code.
• Monolithic code that is long and complex is undesirable for
several reasons:
• It is difficult to write correctly.
• It is difficult to debug.
• It is difficult to extend
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 341
UNIVERSITY OF CALCUTTA
Function Basics
• There are two aspects to every Python function:
• Function definition: The definition of a function contains the code that determines the
function’s behavior
• Function invocation: A function is used within a program via a function invocation.
• Every function contains four parts
• def—The def keyword introduces a function definition.
• Name—The name is an identifier
• The name chosen for a function should accurately portray its intended purpose or describe its
functionality.
• Parameters—every function definition specifies the parameters that it accepts from callers.
• The parameters appear in a parenthesized comma-separated list.
• A colon follows the parameter list.
• Body—every function definition has a block of indented statements that constitute the
function’s body.
• The body contains the code to execute when callers invoke the function.
• The code within the body is responsible for producing the result, if any, to return to the caller.
• An optional return statement to return a value from the function.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 342
UNIVERSITY OF CALCUTTA
Python Function Explore
#Function with No Parameters and No Return
def greet():
print("Hello, welcome to Python!")
greet()
# Function with Parameters and Return Value
def add(a, b):
return a + b
result = add(5, 3)
print("Sum:", result)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 343
UNIVERSITY OF CALCUTTA
Python Function Explore
#Function with Default Parameter
def greet(name="Guest"):
↳ print("Hello,", name) name great/ -)
-
✓
greet() ✓ # Output: Hello, Guest
greet("Amit") # Output: Hello, Amit
# Function with Variable-Length Arguments
def total_sum(*numbers): I + 2+3+4
return sum(numbers)
= 10
print("Total:", total_sum(1, 2, 3, 4))
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 344
UNIVERSITY OF CALCUTTA
Test Knowledge
• Practice 1: Greet the User
• Write a method that takes a user’s name and prints a
greeting.
• Expected Output:
Enter your name: Riya
Hello, Riya! Welcome to Python Programming.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 345
UNIVERSITY OF CALCUTTA
Function - Name Resolution: The LEGB
Rule ✗0
&
In $⅓
• With a def statement:
• Name assignments create or change local names by
default.
• Name references search at most four scopes: local, then
enclosing functions (if any), then global, then built-in.
• Names declared in global and nonlocal statements map
assigned names to enclosing module and function
scopes, respectively
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 346
UNIVERSITY OF CALCUTTA
Function - Name Resolution: The LEGB
Rule
y, z = 1, 2 # Global variables in
module
def all_global():
global x # Declare globals assigned
x = y + z # No need to declare y, z:
LEGB rule
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 347
UNIVERSITY OF CALCUTTA
Function: The Built-in Scope
• built-in scope is just a built-in module called builtins
def hider():
open = 'spam' # Local variable, hides built-in here
...
open('[Link]') # Error: this no longer opens a file in this
scope!
hide the built-in
function called
open
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 348
UNIVERSITY OF CALCUTTA
Function: Cross File Variability
# [Link]
X = 99 # This code doesn't know about [Link]
C'
# [Link]
import first
print(first.X) # OK: references a name in another file
first.X = 88 # But changing it can be too subtle and implicit
# [Link]
X = 99
def setX(new): # Accessor make external changes explit
global X # And can manage access in a single place
X = new
# [Link]
import first
[Link](88) # Call the function instead of changing directly
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 349
UNIVERSITY OF CALCUTTA
Arguments and Shared References
• Arguments are passed by automatically assigning objects
to local variable names
• Assigning to argument names inside a function does not
affect the caller
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 350
UNIVERSITY OF CALCUTTA
Function Basics: The return Statement
• Used to exit a function and return to the caller
• Contain an expression that gets evaluated and the value is
returned
• If no return statement, then will return none object
>>> def f(a): # a is assigned to (references) the passed object
a = 99 # Changes local variable a only
>>> b = 88
>>> f(b) # a and b both reference same 88 initially
⇔
>>> print(b) # b is not changed
88
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 351
UNIVERSITY OF CALCUTTA
Function Basics: The return Statement
• Used to exit a function and return to the caller
• Contain an expression that gets evaluated and the value is
returned
• If no return statement, then will return none object
>>> def changer(a, b): # Arguments assigned references to objects
a = 2 # Changes local name's value only
- b[0] = 'spam' # Changes shared object in place
>>> X = 16- [ "2) co]-'R'→ [n,z)
>>> L = [1, 2] # Caller:
>>> changer(X, L) # Pass immutable and mutable objects
>>> X, L # X is unchanged, L is different!
(1, ['spam', 2])
r
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 352
UNIVERSITY OF CALCUTTA
Argument Matching Syntax
Syntax Location Interpretation
func(value) Caller Normal argument: matched by position
func(name=value) Caller Keyword argument: matched by name
func(*iterable) Caller Pass all objects in iterable as individual positional arguments
Pass all key/value pairs in dict as individual keyword
func(**dict) Caller
arguments
In a function call,
simple values are matched by position,
the name=value form tells Python to match by name to arguments instead; these are
called keyword arguments
Using a *iterable or **dict in a call allows us to package up arbitrarily many positional
or keyword objects in sequences (and other iterables) and dictionaries, respectively,
and unpack them as separate, individual arguments when they are passed to the
function.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 353
UNIVERSITY OF CALCUTTA
Argument Matching Syntax
Syntax Location Interpretation
Normal argument: matches any passed value by position
def func(name) Function
or name
Matches and collects remaining positional arguments in a
def func(*name) Function
tuple
In a function header,
a simple name is matched by position or name depending on how the caller passes it,
the name=value form specifies a default value
the *name form collects any extra unmatched positional arguments in a tuple,
the **name form collects extra keyword arguments in a dictionary.
In Python 3.X, any normal or defaulted argument names following a *name or a bare *
are keyword-only arguments and must be passed by keyword in calls.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 354
UNIVERSITY OF CALCUTTA
Argument Matching Syntax
Syntax Location Interpretation
Matches and collects remaining positional arguments in a
def func(*name) Function
tuple
Arguments that must be passed by keyword only in calls
def func(*other, name) Function
(3.X)
Arguments that must be passed by keyword only in calls
def func(*, name=value) Function
(3.X)
In a function header,
a simple name is matched by position or name depending on how the caller passes it,
the name=value form specifies a default value
the *name form collects any extra unmatched positional arguments in a tuple,
the **name form collects extra keyword arguments in a dictionary.
In Python 3.X, any normal or defaulted argument names following a *name or a bare *
are keyword-only arguments and must be passed by keyword in calls.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 355
UNIVERSITY OF CALCUTTA
Argument Matching Syntax
23 err
>>> def f(a, b, c): print(a, b, c) fla, b. c)
>>> f(1, 2, 3)
Or (3. 2,'
--
>>> f(c=3, b=2, a=1)
Or
>>> f(1, c=3, b=2) # a gets 1 by position, b and c passed by name
>>> def f(a, b=2, c=3): print(a, b, c) # a required, b and c optional
>>> f(1) # Use defaults
>>> f(a=1)
>>> f(1, 4) # Override defaults f/a-1, 2. C-3)
1 4 3
>>> f(1, 4, 5)
1 4 5
>>> f(1, c=6) # Choose defaults
1 2 6 DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 356
UNIVERSITY OF CALCUTTA
Argument Matching Syntax
✓
def func(spam, eggs, toast=0, ham=0): # First 2 required
print((spam, eggs, toast, ham))
func(1, 2) # Output: (1, 2, 0, 0) ✓
func(1, ham=1, eggs=0) # Output: (1, 0, 0, 1)
func(spam=1, eggs=0) # Output: (1, 0, 0, 0)
func(toast=1, eggs=2, spam=3) # Output: (3, 2, 1, 0)
func(1, 2, 3, 4) # Output: (1, 2, 3, 4)
Python matches by
name, not by position
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 357
UNIVERSITY OF CALCUTTA
Argument Matching Syntax
• * and **, are designed to support functions that take any
number of arguments
• * collects unmatched positional arguments into a tuple
*
>>> def f(*args): print(args) 4- (1,2, 3.4)
>>> f() ↳ variable
length arguments.
() > def fl. (2, 2, 3,4)
>>> f(1) retto
(1,)
>>> f(1, 2, 3, 4) Multiaelrlowedprint (fl[ . ilp allowed f((1,2, 3,4))
(1, 2, 3, 4) 1,2,3,6
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 358
UNIVERSITY OF CALCUTTA
Argument Matching Syntax
• ** works for keyword arguments—it collects them into a
new dictionary, which can then be processed with normal
dictionary tools
>>> def f(**args): print(args)
>>> f() variable lengt , word
{}
.
✓ ✓
>>> f(a=1, b=2)
{'a': 1, 'b': 2}
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 359
UNIVERSITY OF CALCUTTA
Argument Matching Syntax
• * unpacks a collection of arguments, rather than building a
collection of arguments
>>> def func(a, b, c, d): print(a, b, c, d)
>>> args = (1, 2)
→ Concaditation
>>> args += (3, 4)
>>> func(*args) # Same as func(1, 2, 3, 4)
1 2 3 4 ↳ The ☆ in fric call ≤ ent
unpacks the tuple
func (arg) missing} argume,
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 360
UNIVERSITY OF CALCUTTA
Argument Matching Syntax
• ** syntax in a function call unpacks a dictionary of
key/value pairs into separate keyword arguments:
>>> def func(a, b, c, d): print(a, b, c, d)
>>> args = {'a': 1, 'b': 2, 'c': 3}
>>> args['d'] = 4
>>> func(**args) # Same as func(a=1, b=2, c=3, d=4)
1 2 3 4
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 361
UNIVERSITY OF CALCUTTA
Keyword-Only
post argument
Arguments
# Does not accept a variable-length argument list, but expects all
arguments following the * as keywords
def kwonly(a, *, b, c):
After ☆ ' nd argument
print(a, b, c)
kwonly(1, c=3, b=2) ✓
kwonly(c=3, b=2, a=1) ✓
kwonly(1, 2,3) v
TypeError: kwonly() takes
1 positional argument
but 3 were given
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 362
UNIVERSITY OF CALCUTTA
Ordering Rules
• keyword-only arguments must be specified after a single
star
• named arguments cannot appear after the **args arbitrary
keywords form
or default
>>> def f(a, *b, c=6, **d): print(a, b, c, d) # Collect args in header
>>> f(1, 2, 3, x=4, y=5) # Default used
1 (2, 3) 6 {'y': 5, 'x': 4} ✓
>>> f(1, 2, 3, x=4, y=5, c=7) # Override default
1 (2, 3) 7 {'y': 5, 'x': 4}
>>> f(1, 2, 3, c=7, x=4, y=5) # Anywhere in keywords
1 (2, 3) 7 {'y': 5, 'x': 4}
>>> def f(a, c=6, *b, **d): print(a, b, c, d) # c is not keyword-only here!
>>> f(1, 2, 3, x=4)
DEPARTMENT OF APPLIED PHYSICS,
1 SEMESTER
EVEN (3,) 2 {'x': 4} UNIVERSITY OF CALCUTTA
363
Ordering Rules
• keyword-only arguments must appear before a **args
form in function call
>>> def f(a, *b, c=6, **d): print(a, b, c, d) # KW-only between * and **
>>> f(1, *(2, 3), **dict(x=4, y=5)) # Unpack args at call
1 (2, 3) 6 {'y': 5, 'x': 4}
>>> f(1, *(2, 3), **dict(x=4, y=5), c=7) # Keywords before **args!
SyntaxError: invalid syntax
>>> f(1, *(2, 3), c=7, **dict(x=4, y=5)) # Override default
1 (2, 3) 7 {'y': 5, 'x': 4}
>>> f(1, c=7, *(2, 3), **dict(x=4, y=5)) # After or before *
1 (2, 3) 7 {'y': 5, 'x': 4}
>>> f(1, *(2, 3), **dict(x=4, y=5, c=7)) # Keyword-only in **
1 (2, 3) 7 {'y': 5, 'x': 4}
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 364
UNIVERSITY OF CALCUTTA
Explore: Keyword-Only Argument
def book_ticket(name, *, seat="Window", meal="Veg"):
print(f"Passenger: {name}")
print(f"Seat Preference: {seat}")
print(f"Meal Preference: {meal}")
book_ticket("Amit", seat="Aisle", meal="Non-Veg")
• Class Practice to create a function should print all
information posh
def register_student(name, *, branch, year):
# Should print all information
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 365
UNIVERSITY OF CALCUTTA
Explore: Argument Matching Syntax
⑨ It has to be nly
def demo(a, b=10, *args, d, **kwargs):
print("a =", a) ↳ multi iterabe ↳ ament
print("b =", b)
print("args =", args)
print("d =", d) Kwargs' 2:/00, 7:20}
print("kwargs =", kwargs)
(3. 4,5)
demo(1, 2, 3, 4, 5, d=6, x=100, y=200) ,
• Class Practice to create a function should print all
information
def pizza_order(name, size="medium", *toppings, extra_cheese=False,
**extras):
# Print all arguments in order
pizza_order("Rohit", "large", "mushrooms", "corn", extra_cheese=True,
DEPARTMENT OF APPLIED PHYSICS,
sauce="BBQ")
EVEN SEMESTER
UNIVERSITY OF CALCUTTA
366
Explore: Argument Matching Syntax
def greet(a, /, b, *, c):
print(a, b, c)
greet(1, b=2, c=3)
• a is positional-only
• b can be positional or keyword
• c is keyword-only
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 367
UNIVERSITY OF CALCUTTA
Function Basics: The return Statement
# calculation of square list of number
def square(list1):
newList = list()
for i in list1:
[Link](i * i)
return newList
input_list = [1, 2, 3, 4, 5, 6]
print("input list is:", input_list)
output = square(input_list)
1114,9, 16,28, 363
print("Output list is:", output)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 368
UNIVERSITY OF CALCUTTA
Function Basics: The yield Statement
• Used in a function to return values to the caller function
• It returns a generator object to the caller
• Executed from the last state from where the function get
paused
• Generator object can be accessed using the next() function
• Python generators are a simple way of creating iterators
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 369
UNIVERSITY OF CALCUTTA
Function Basics: The yield Statement
• Using the next() function
def square(list1):
newList = list()
for i in list1:
[Link](i * i)
yield newList
input_list = [1, 2, 3, 4, 5, 6]
print("input list is:", input_list)
output = square(input_list)
print("Output from the generator is:", output)
print("Elements in the generator are:",next(output))
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 370
UNIVERSITY OF CALCUTTA
Function Basics: The yield Statement
Using the for loop
def square(list1):
yield list1[0]**2
yield list1[1] ** 2
yield list1[2] ** 2
yield list1[3] ** 2
yield list1[4] ** 2
yield list1[5] ** 2
input_list = [1, 2, 3, 4, 5, 6]
print("input list is:", input_list)
output = square(input_list)
print("Output from the generator is:", output)
print("Elements in the generator are:")
for i in output:
print(i)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 371
UNIVERSITY OF CALCUTTA
Function Design Concepts
• Coupling: use arguments for inputs and return for outputs
• The best ways to isolate external dependencies to a small number
• Coupling: use global variables only when truly necessary
• can create dependencies and timing issues that make programs
difficult to debug, change, and reuse
• Coupling: don’t change mutable arguments unless the caller expects
it
• Creates a tight coupling between the caller and callee
• Cohesion: each function should have a single, unified purpose
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 372
UNIVERSITY OF CALCUTTA
Function Basics
YIELD RETURN
Return is generally used for the end of the
Yield is generally used to convert a
execution and “returns” the result to the
regular Python function into a generator.
caller statement.
It replace the return of a function to
It exits from a function and handing back
suspend its execution without destroying
a value to its caller.
local variables.
It is used when the generator returns an It is used when a function is ready to send
intermediate result to the caller. a value.
Code written after yield statement execute while, code written after return statement
in next function call. wont execute.
It can run multiple times. It only runs single time.
Yield statement function is executed from
Every function calls run the function from
the last state from where the function get
the start.
paused.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 373
UNIVERSITY OF CALCUTTA
Function Basics
def double(n): # Counts to ten
return 2 * n # Return twice the for i in range(1, 11):
given number print(i, end=' ‘)
# Call the function with the value 3 print()
and print its result
x = double(3)
print(x) # Count to ten and print each number
def count_to_10():
for i in range(1, 11):
print(i, end=' ‘)
print()
print("Going to count to ten . . .")
count_to_10()
print("Going to count to ten again. . .")
count_to_10()
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 374
UNIVERSITY OF CALCUTTA
Parameter Passing
def increment(x):
print("Beginning execution of increment, x = ", x)
x += 1 # Increment x
print("Ending execution of increment, x = ", x)
def main():
x = 5
print("Before increment, x =", x) efore " " 21=5
increment(x) regining" "n-s
print("After increment, x =", x)
Ending" "n=6
main()
Hter " "2=6
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 375
UNIVERSITY OF CALCUTTA
Documenting Functions
• It is good practice to document a function’s definition with
information that aids programmers who may need to use or
extend the function.
• The purpose of the function
• The function’s purpose is not always evident merely from its
name.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 376
UNIVERSITY OF CALCUTTA
Documenting Functions
• The nature of the return value
• While the function may do a number of interesting things as
indicated in the function’s purpose, what exactly does it return to
the caller?
• We can use comments to document our functions, but
Python provides a way that allows developers and tools to
extract more easily the needed information.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 377
UNIVERSITY OF CALCUTTA
def god (Mig)
If NLY:
Documenting Functions
min:X
Else:
min: y
for i in range (1, minti):
if n [Link]:O:
gid: i
def gcd(n1, n2):
""" Computes the greatest common divisor of integers n1
and n2. ""“ returni
# Determine the smaller of n1 and n2
min = n1 if n1 < n2 else n2
# 1 definitely is a common factor to all ints
largest_factor = 1
for i in range(1, min + 1):
if n1 % i == 0 and n2 % i == 0:
largest_factor = i # Found larger factor
return largest_factor
l
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 378
UNIVERSITY OF CALCUTTA
Local Variables
• Variables defined within functions are local variables.
• Local variables have some very desirable properties:
• The memory required to store a local variable is used only when
the variable is in scope
• The same variable name can be used in different functions without
any conflict.
• A local variable is transitory, so it disappears in between
function invocations.
• Sometimes it is desirable to have a variable that exists
independent of any function executions
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 379
UNIVERSITY OF CALCUTTA
Global Variables
• Global variable lives outside of all functions and is not local
to any particular function.
• Any function is capable of accessing and/or modifying a global
variable
• A variable within a function is local variable, unless the
variable is declared to be a global variable using the global
reserved word
• If a function defines a local variable with the same name as
a global variable, the global variable become
inaccessible to code within the function, i.e. hides the
global variable
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 380
UNIVERSITY OF CALCUTTA
Nonlocal Variables (in Python 3.X)
• Nested functions can reference variables in an enclosing
function’s scope
• With nonlocal statements, nested defs can have both read
and write access to names in enclosing functions
• Unlike global, though, nonlocal applies to a name in an
enclosing function’s scope, not the global module scope
outside all defs
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 381
UNIVERSITY OF CALCUTTA
Nonlocal Variables (in Python 3.X)
# Nested function with nonlocal statement
def tester(start):
state = start # Each call gets its own state
def nested(label):
nonlocal state # Remembers state in enclosing scope
spam 0
print(label, state)
ham 0
state += 1 # Allowed to change it if nonlocal
return nested
eggs 0
F = tester(0) # Nested function without nonlocal statement
F('spam') # Increments state on each call def tester(start):
F('ham') state = start # Referencing nonlocals works normally
F('eggs') def nested(label):
print(label, state) # Remembers state in enclosing scope
spam 0 return nested
ham 1
F = tester(0)
eggs 2
F('spam') # Increments state on each call
F('ham')
F('eggs')
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 382
UNIVERSITY OF CALCUTTA
Example: Function
def smallest_num_in_list( list ): a = [10,20,30,20,10,50,60,40,80,50,40]
min = list[ 0 ] dup_items = set()
for a in list: uniq_items = []
if a < min: min = a for x in a:
return min if x not in dup_items:
print(smallest_num_in_list([1, 2, -8, uniq_items.append(x)
0]))
dup_items.add(x)
print(dup_items)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 383
UNIVERSITY OF CALCUTTA
Quiz
• What is the output of the following code?
>>> X = 'Spam'
>>> def func():
print(X)
>>> func()
↳ spam
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 384
UNIVERSITY OF CALCUTTA
Quiz
• What is the output of the following code?
>>> def func():
X = 'NI’
def nested():
nonlocal X
X = 'Spam’
nested()
print(X)
>>> func()
spam
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 385
UNIVERSITY OF CALCUTTA
Advantages of Local Variable over
Global Variable
• When a function uses local variables exclusively and
performs no other input operations
• When examining the contents of a function, a global
variable requires the reader to look elsewhere (outside the
function) for its meaning
• A function that uses only local variables can be tested for
correctness in isolation from other functions, since other
functions do not affect the behavior of this function
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 386
UNIVERSITY OF CALCUTTA
Advantages of Local Variable over
Global Variable
• When a function uses local variables exclusively and
performs no other input operations
• When examining the contents of a function, a global
variable requires the reader to look elsewhere (outside the
function) for its meaning def process(n): Guess the output,
return n + m # m is a when
globalexecute
integer
• A function that uses only local
variablevariables can be tested for
correctness in isolation from other functions, since other
def assign_m():
functions do not affect the behavior globalof
m this function
m = 5
def inc_m():
global m
DEPARTMENT OF APPLIED
m PHYSICS,
+= 1
EVEN SEMESTER 387
UNIVERSITY OF CALCUTTA
Default Parameters
• Can define own functions that accept a varying number of
parameters by using a technique known as default
parameters def countdown(n=10):
for count in range(n, -1, -1): # Count down from n to zero
print(count)
• May mix non-default and default parameters in the
parameter lists of a function declaration, but all default
parameters within the parameter list must appear after all
the non-default parameters
def sum_range(n, m=100): # OK, default follows non-default
sum = 0
for val in range(n, m + 1):
sum += val
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 388
UNIVERSITY OF CALCUTTA
Recursive Function
• The function optionally must call itself within its definition
• The function optionally must not call itself within its
definition (base case)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 389
UNIVERSITY OF CALCUTTA
Recursive Function Recursive
in copy
def factorial(n): def factorial(n):
""" """
Computes n! Computes n!
Returns the factorial of n. Returns the factorial of n.
""" """
if n == 0: product = 1
while n:
return 1
product *= n
else:
n -= 1
return n * factorial(n - 1) return product
def main(): def main():
""" Try out the factorial function """ """ Try out the factorial function """
print(" 0! = ", factorial(0)) print(" 0! = ", factorial(0))
print(" 1! = ", factorial(1)) print(" 1! = ", factorial(1))
print(" 6! = ", factorial(6)) print(" 6! = ", factorial(6))
print("10! = ", factorial(10)) print("10! = ", factorial(10))
main()
main()
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 390
UNIVERSITY OF CALCUTTA
Functions Reusable
• It is possible to reuse a function if the function definition
does not use any programmer-defined global variables nor
any other programmer-defined functions.
• If a function does use any of these programmer-defined
external entities, must include these dependencies as well
in the new code for the function to viable.
• Python makes easy for developers to package their
functions into modules
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 391
UNIVERSITY OF CALCUTTA
Functions as Data
• A function is special kind of object, just as integers, and
strings are objects.
from math import sqrt
x = sqrt # Assign x to sqrt function object
print(x(16)) # Prints 4.0
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 392
UNIVERSITY OF CALCUTTA
Nested Function
• def is an executable statement, def is simply an executable
statement
• Nested functions can access names in all physically
enclosing def statements
X = 99 # Global scope name: not used
def f1():
X = 88 # Enclosing def local
def f2(): ↗ 88
print(X) # Reference made in nested def
f2()
f1() # Prints 88: enclosing def local
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 393
UNIVERSITY OF CALCUTTA
Nested Function: Factory Functions:
Closures
• Factory functions (a.k.a. closures) are used by programs
that need to generate event handlers on the fly in response
to conditions at runtime.
# Function factory (closure) simply generates and
def maker(N): returns a nested function
def action(X): # Make and return action
return X ** N # action retains N from enclosing scope
return action
>>> f = maker(2) # Pass 2 to argument N calling the nested function
>>> f that maker created and
<function maker.<locals>.action at 0x0000000002A4A158> passed back
>>> f(3) # Pass 3 to X, N remembers 2: 3 ** 2
9
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 394
UNIVERSITY OF CALCUTTA
Nested Function: Factory Functions:
Closures
• Factory functions (a.k.a. closures) are used by programs
that need to generate event handlers on the fly in response
to conditions at runtime.
# Function factory (closure) simply generates and
def maker(N): returns a nested function
def action(X): # Make and return action
return X ** N # action retains N from enclosing scope
return action
>>> g = maker(3) # g remembers 3, f remembers 2 Remember the internal
>>> g(4) # 4 ** 3 state
64
>>> f(4) # 4 ** 2
16
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 395
UNIVERSITY OF CALCUTTA
Lambda Expressions
• To call a function, we must know its name
• Invoking functions without using their names directly
def evaluate(f, x, y):
return f(x, y)
• If no separate function is defined for f, evaluate invokes
the function passed in from the caller
• Want to function will execute exactly one time
• Another way is by using lambda function
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 396
UNIVERSITY OF CALCUTTA
Lambda Expressions
• lambda is a reserved word that introduces a lambda
expression.
• parameterlist is a comma-separated list of parameters as in
the function definition
• expression is a single Python expression
• expression cannot be a complete statement, nor can it
be a block of statements.
# Using lambda function
evaluate(lambda x, y: x * y, 2, 3)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 397
UNIVERSITY OF CALCUTTA
Lambda Expressions
• lambda expression cannot be a Python statement
• Assignments are not possible within lambda expressions,
and loops are not allowed
• lambda’s body is a single expression, not a block of
statements
>>> evaluate(lambda x, y: 3*x + y, 10,2) 32
>>> evaluate(lambda x, y: print(x, y), 10, 2) 10 2
>>> evaluate(lambda x, y: 10 if x == y else 2,
10
5, 5)
>>> evaluate(lambda x, y: 10 if x == y else 2,
5, 3) 2
evaluate(lambda x, y: max(x, y) + x - sqrt(y), 2, 3)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 398
UNIVERSITY OF CALCUTTA
Lambda Expressions
def evaluate(f, x, y):
return f(x, y)
def main():
a = int(input('Enter an integer:’))
print(evaluate(lambda x, y: False if x == a else True, 2, 3))
main()
a is not passed as
a parameter function definition
Closure (captures the captures the variable
variable a)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 399
UNIVERSITY OF CALCUTTA
Generators
• A generator is a programming count = 0 # A global count variable
def remember():
object that produces (that is, global count
generates) a sequence of values
count += 1 # Count this invocation
print('Calling remember (#' + str(count) + ')')
• Construction similar to general print('Beginning program')
function but the local variables
remember()
remember()
are not remember the values remember()
remember()
past execution remember()
print('Ending program')
• Instead of return keyword the
yield keyword is used
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 400
UNIVERSITY OF CALCUTTA
Generators
>>> from yieldsequence import gen
def gen():
>>> x = gen()
yield 3
>>> next(x)
yield 'wow’
3
yield -1
>>> next(x)
yield 1.2
'wow’
>>> from yieldsequence import gen >>> next(x)
>>> gen -1
<function gen at 0x00FA14B0> >>> next(x)
>>> type(gen) 1.2
<class 'function'> >>> next(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
def gen():
StopIteration
yield 3
yield 'wow’
yield -1
yield 1.2
for i in gen():
print(i)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 401
UNIVERSITY OF CALCUTTA
Generators
def generate_multiples(m, n):
count = 0
while count < n:
yield m * count
count += 1
def main():
for mult in generate_multiples(3, 6):
print(mult, end=' ')
print()
if __name__ == '__main__':
main()
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 402
UNIVERSITY OF CALCUTTA
Local Function Definitions
• A function that itself becomes large and
unwieldy.
• further can break down the large function into
smaller pieces
• Sometimes this more fine-grained access is
desirable, but at other times programmers do not
want to expose that level of detail to callers.
• Generalizing the concept of local variables,
Python permits programmers to define
functions within other function definitions.
• These local functions are available to the
code within their enclosing function but are
inaccessible outside their enclosing function
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 403
UNIVERSITY OF CALCUTTA
Local Function Definitions
from math import fabs # Main code for surface_area function
# Compute area of front face
def surface_area(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4, length = fabs(x2 - x1)
x5, y5, z5, x6, y6, z6, x7, y7, z7, x8, y8, z8): height = fabs(y3 - y1)
""" Computes the surface area of a rectangular box front_area = area(length, height)
(cuboid) defined by the 3D points (x,y,z) of # Compute area of side face
its eight corners: width = fabs(z5 - z1)
7------8 returns the side_area = area(width, height)
/| /| absolute value of a # Compute area of top face
3------4 | number, as a float top_area = area(length, width)
| | | | # Compute and return surface area: front/back,
| 5----|-6 # left side/right side, and top/bottom faces
|/ |/ return 2*front_area + 2*side_area + 2*top_area
1------2
""" def volume(length, width, height):
# Local helper function to compute area """ Computes the volume of a rectangular box
def area(length, width): (cuboid) defined by its length, width, and height """
""" Computes the area of a length x width rectangle """ return length * width * height
return length * width
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 404
UNIVERSITY OF CALCUTTA
Local Function Definitions
def get_point(msg): x1, y1, z1 = get_point('Corner 1')
""" Prints a message specified by msg and allows the user to x2, y2, z2 = get_point('Corner 2')
enter the (x, y, z) coordinates of a point. Returns the x3, y3, z3 = get_point('Corner 3')
point as a tuple. """ x4, y4, z4 = get_point('Corner 4')
print(msg) x5, y5, z5 = get_point('Corner 5')
x = float(input("Enter x coordinate: ")) x6, y6, z6 = get_point('Corner 6')
y = float(input("Enter y coordinate: ")) x7, y7, z7 = get_point('Corner 7')
z = float(input("Enter z coordinate: ")) x8, y8, z8 = get_point('Corner 8')
return x, y, z
# Compute the surface area of the box
# Get the coordinates of the box's corners from the user print('Surface area:', surface_area(x1, y1, z1, x2, y2, z2,
print('Enter the coordinates of each of the box\'s corners') x3, y3, z3, x4, y4, z4,
print(''' x5, y5, z5, x6, y6, z6,
7------8 x7, y7, z7, x8, y8, z8))
/| /| # Compute the volume of the box
3------4 | ln = fabs(x2 - x1) # Compute length
| | | | wd = fabs(z5 - z1) # Compute width
| 5----|-6 ht = fabs(y3 - y1) # Compute height
|/ |/ print('Volume:', volume(ln, wd, ht))
1------2
''')
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 405
UNIVERSITY OF CALCUTTA
Decorators
• A decorator simply adds some “decoration” to the function,
usually to augment the function’s behavior
• does not change the way a function works
• A decorator “wraps” a function passed to it.
• A decorator cannot modify the inner workings of a function
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 406
UNIVERSITY OF CALCUTTA
Decorators def show_call_and_return_details(f):
""" Decorates a function f so its call will display the parameter
values and return value. """
func_name = f.__name__ # Get the function's name
def execute_augmented(x, y):
def max(x, y):
call_string = "{}({}, {})".format(func_name, x, y)
“““Determine the maximum of x and y”””
print(">>> Calling " + call_string)
return x if x > y else y
result = f(x, y)
print("<<< Returning {} from ".format(result) + call_string)
max(20, 30)
return result
print('------------------------’)
return execute_augmented
@ show_call_and_return_details
def max(x, y):
""""Determine the maximum of x and y"""
def max(x, y): return x if x > y else y
"""Determine the maximum of x and y"""
call_string = "max({}, {})".format(x, y) # Decorate the functions to provide information about their calls
print(">>> Calling " + call_string) # We can make up a new name
result = x if x > y else y # Or, more typically, simply redirect the original name to a new
print("<<< Returning {} from ".format(result) + call_string) function!
return result augmented_max = show_call_and_return_details(max)
max(20, 30) augmented_max(20, 30)
print('------------------------') print('------------------------')
Or by using “@” syntax before each
function
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS, e.g. @ show_call_and_return_details(max)
407
UNIVERSITY OF CALCUTTA
Partial Application
• The functools module provides an interesting function named partial that
accepts a function as its first parameter and one or more other parameters.
• The partial function returns a new function that is behaviorally related to the
original function passed to it
def add(x, y):
return x + y
• The interpreter will not allow a caller to pass fewer than two or more than two
parameters.
from functools import partial
add5 = partial(add, 5)
• This new add5 function accepts a single parameter.
print(add5(3)) # Works like print(add(5, 3))
• The add5 invocation calls the original add function with 5 as the first argument
and add5’s parameter, 3, as the second argument.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 408
UNIVERSITY OF CALCUTTA
Partial Application
• Partial application allows us to make a new function from an
existing function with one or more of the original function’s
actual parameters “hardwired” into the definition.
• This new function exhibits the same behavior as the original
function but requires fewer parameters during its call.
• Partial application can predetermine only leading parameters.
• It is not possible to predetermine a parameter that follows a
non-predetermined parameter.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 409
UNIVERSITY OF CALCUTTA
Operation of if __name__ == '__main__'
def add(a, b): def add(a, b):
return (a + b) return (a + b)
print (add(10,16)) if __name__ == "__main__":
print (add(10,16))
from eg1 import add from eg1 import add
print (add(7,6)) print (add(7,6))
1. Every Python module has it’s __name__ defined and if this is ‘__main__’, it implies that the
module is being run standalone by the user and we can do corresponding appropriate
actions.
2. If you import this script as a module in another script, the __name__ is set to the name of
the script/module.
3. Python files can act as either reusable modules, or as standalone programs.
4. if __name__ == “main”: is used to execute some code only if the file was run directly, and
not imported. DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 410
UNIVERSITY OF CALCUTTA
Python Scopes and Namespaces
• A namespace is a mapping from names to objects.
• Most namespaces are currently implemented as Python
dictionaries, but that’s normally not noticeable in any way.
• Examples of namespaces are:
• the set of built-in names (functions such as abs(), and built-in
exception names)
• the global names in a module;
• and the local names in a function invocation.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 411
UNIVERSITY OF CALCUTTA
Python Scopes and Namespaces
• In a sense the set of attributes of an object also form a namespace.
• The important thing to know about namespaces is that
there is absolutely no relation between names in different
namespaces;
• for instance, two different modules may both define a function
“maximize” without confusion — users of the modules must prefix
it with the module name.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 412
UNIVERSITY OF CALCUTTA
Python Scopes and Namespaces
• In the expression [Link], modname is a
module object and funcname is an attribute of it.
• In this case there happens to be a straightforward mapping
between the module’s attributes and the global names
defined in the module:
• they share the same namespace!
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 413
UNIVERSITY OF CALCUTTA
Python Scopes and Namespaces
• Namespaces are created at different moments and have
different lifetimes.
• The namespace containing the built-in names is created
when the Python interpreter starts up, and is never deleted.
• The global namespace for a module is created when the
module definition is read in;
• normally, module namespaces also last until the interpreter quits.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 414
UNIVERSITY OF CALCUTTA
Python Scopes and Namespaces
• The statements executed by the top-level invocation of the
interpreter, either read from a script file or interactively, are
considered part of a module called __main__,
• so they have their own global namespace.
• The built-in names actually also live in a module;
• this is called __builtin__.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 415
UNIVERSITY OF CALCUTTA
Python Scopes and Namespaces
• The local namespace for a function is created
• when the function is called
• And deleted
• when the function returns or raises an exception that is not
handled within the function.
• Of course, recursive invocations each have their own local
namespace.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 416
UNIVERSITY OF CALCUTTA
Python Scopes and Namespaces
• A scope is a textual region of a Python program where a
namespace is directly accessible.
• “Directly accessible” here means that an unqualified
reference to a name attempts to find the name in the
namespace.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 417
UNIVERSITY OF CALCUTTA
Python Scopes and Namespaces
• Although scopes are determined statically, they are used
dynamically.
• At any time during execution, there are at least three nested
scopes whose namespaces are directly accessible:
• the innermost scope, which is searched first, contains the local
names; the namespaces of any enclosing functions,
• which are searched starting with the nearest enclosing scope; the
middle scope, searched next, contains the current module’s global
names;
• and the outermost scope (searched last) is the namespace
containing built-in names.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 418
UNIVERSITY OF CALCUTTA
Python Scopes and Namespaces
• If a name is declared global, then all references and
assignments go directly to the middle scope containing the
module’s global names.
• Otherwise, all variables found outside of the innermost
scope are read-only.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 419
UNIVERSITY OF CALCUTTA
Python Scopes and Namespaces
• Usually, the local scope references the local names of the
current function.
• Outside of functions, the local scope references the same
namespace as the global scope:
• the module’s namespace.
• Class definitions place yet another namespace in the local
scope.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 420
UNIVERSITY OF CALCUTTA
Python Scopes and Namespaces
• A special quirk of Python is that assignments always go into
the innermost scope.
• Assignments do not copy data—
• they just bind names to objects.
• The same is true for deletions:
• the statement ‘del x’ removes the binding of x from the
namespace referenced by the local scope.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 421
UNIVERSITY OF CALCUTTA
Python Scopes and Namespaces
• In fact, all operations that introduce new names use the
local scope:
• in particular, import statements and function definitions bind the
module or function name in the local scope. (The global statement
can be used to indicate that particular variables live in the global
scope.)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 422
UNIVERSITY OF CALCUTTA
Example:
• Function to Calculate the Square of a Number
# Define the function
def square(num):
result = num * num
return result
# Call the function
number = int(input("Enter a number: "))
output = square(number)
print("Square of", number, "is", output)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 423
UNIVERSITY OF CALCUTTA
Example:
def calc(a, b):
sum_ = a + b
product = a * b
return sum_, product
# Calling the function
s, p = calc(3, 4)
print("Sum:", s)
print("Product:", p)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 424
UNIVERSITY OF CALCUTTA
Example:
◦ → Multi iterase
def show_marks(*marks):
print("All Marks:", marks) → D, 78,88
print("Total:", sum(marks))
→
show_marks(85, 90, 78, 88)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 425
UNIVERSITY OF CALCUTTA
Example:
def student_info(**kwargs):
for key, value in [Link]():
print(key, ":", value)
student_info(name="Priya", age=20, course="CSE")
name: Priy
age: 20
Ourse: (SE
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 426
UNIVERSITY OF CALCUTTA
Example:
def outer():
print("Inside outer function.") ①/
def inner():
print("Inside inner function.") 2
inner()
outer()
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 427
UNIVERSITY OF CALCUTTA
Exercise:
Problem: Grading System using User-Defined Function
Statement:
Write a function get_grade(marks) that takes marks as input and returns the grade
based on the following conditions:
90 and above: A+
80-89: A
70-79: B
60-69: C
Below 60: F
Requirements:
Use if-elif-else inside the function.
Use the function to display the grade for 5 students (input through loop).
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 428
UNIVERSITY OF CALCUTTA
Exercise:
Problem 2: Student Info Logger using **kwarg:
Statement:
Write a function log_student_info(**kwargs) that takes student details
as keyword arguments (e.g., name, age, branch, roll) and prints them
in a formatted manner.
Example Call:
log_student_info(name="Ravi", age=21, branch="ECE", roll="EE102")
Expected Output:
Student Details: Name : Ravi Age : 21 Branch : ECE Roll : EE102
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 429
UNIVERSITY OF CALCUTTA
COMPUTER PROGRAMMING
PCC-EE 405
Nirmal Murmu
Department of Applied Physics
University of Calcutta
Course Outcomes
• At the end of this course, students will be able to learn about
• CO1: Identify fundamental programming concepts, data structures, and file
handling techniques used in software development.
• CO2: Explain the principles of object-oriented programming, event-driven
programming, and their applications in GUI and system programming.
• CO3: Develop basic to intermediate-level applications using programming
languages and libraries for file manipulation, data handling, and user interaction.
• CO4: Compare and evaluate different programming approaches, paradigms, and
tools for solving computational problems effectively.
• CO5: Assess the efficiency, scalability, and usability of developed applications,
optimizing code performance and debugging issues effectively.
•
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 2
UNIVERSITY OF CALCUTTA
Syllabus
• Module 1: Introduction to Visual basic (8 hour)
• Fundamentals of GUI development using [Link], Concepts of object, method and event in [Link],
Utilisation of various tools, Components and References, basic concept of event handling, I/O File
handling and data handling.
• Module 2: Visual basic Programming (10 hour)
• Learn to develop program in windows environment, simple display program, Key board and
mouse interactive program, Reading and writing I/O files, handling of other windows program -
like reading and writing Excel file, Excel plotting, interfacing of USB/COM ports, development of
net based application in client/server mode.
• Module 3: Introduction to Python libraries (10 hour)
• Python Types, Expressions, Strings, Lists, Tuples, Python memory model (names, mutable and
immutable values), List operations, Regular Expressions, Python Functions, Abstract Data types,
Classes and Objects in Python, Exception handling, Handling files, Python
Scientific/Statistical/Machine Learning Libraries.
• Module 4: Python programming (12 hour)
• Python Programming: Object based program using multi threading, I/O handling of files, Printing
and display using timer operation, program for handling of interfacing of cameras, program to
develop machine learning based applications.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 3
UNIVERSITY OF CALCUTTA
References
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 4
UNIVERSITY OF CALCUTTA
Lecture Plan
Lecture No. Topic Key Concepts
Variables, Data Types, and Python types, expressions,
1
Operators operators, type conversions
Lists, tuples, slicing, loops (for,
2 Arrays and Flow Control
while), conditional statements
Defining functions, arguments,
3 Methods and Functions
return values, recursion
Reading/writing files, handling CSV,
4 File Handling
JSON
Introduction to Scientific NumPy, Pandas, Matplotlib for data
5
Libraries processing
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 5
UNIVERSITY OF CALCUTTA
Lecture Plan
Lecture No. Topic Key Concepts
Object-Oriented Programming Classes, objects, inheritance,
1
(OOPs) in Python polymorphism
Multi-threading and Advanced File Threading basics, file operations,
2
Handling concurrent programming
Timers, Event Handling, and GUI Timer-based operations, GUI
3
Development programming using Tkinter/PyQt
Using OpenCV for image
Camera Interfacing and Data
4 processing, real-time data
Acquisition
acquisition
Machine Learning and AI Basics of Scikit-learn, TensorFlow,
5
Applications AI-driven applications
Final Project Discussion and Developing real-world
6
EVEN SEMESTER
Implementation DEPARTMENT OF APPLIED PHYSICS,
applications, project review 6
UNIVERSITY OF CALCUTTA
Python: Basics
• Variables
• Data types
• Operators
• Arrays
• Flow Control
• Methods
• File Handling
• OOPS
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 440
UNIVERSITY OF CALCUTTA
Introduction to File Handling
• What is file handling?
• Why use files (vs in-memory data)?
• Types of files:
• Text files (.txt)
• Data files (.csv, .json)
• Types of file operations: Open, Read, Write, Append, Close
• File modes: 'r', 'w', 'a', 'r+', 'w+', 'a+’
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 441
UNIVERSITY OF CALCUTTA
Introduction to File Handling
• Syntax:
file = open("[Link]", "mode") # Perform operations
[Link]()
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 442
UNIVERSITY OF CALCUTTA
Introduction to File Handling
• Modes in open() function:
Mode Description
'r' Read (default)
'w' Write (overwrites)
'a' Append
'r+' Read and Write
‘w+' Write and Read (File Created/Truncated)
‘a+’ Append and Read
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 443
UNIVERSITY OF CALCUTTA
Introduction to File Handling
• Modes in open() function:
Mode Read Write Truncate File Create if Missing Pointer at
r+ Start
w+ Start
a+ (Append) End (for write)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 444
UNIVERSITY OF CALCUTTA
Introduction to File Handling
• Reading a File f- open (" student. ext", 4')
file = open("[Link]", "r")
value = f- read() / oread (m)
content = [Link]()
print(content) ring f. readline mbits.
[Link]()
turn [Link] return
• Explanation: list return
• open() returns a file object. Ktime complete return
• read() reads the entire content.
• close() is needed to release the file resource.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 445
UNIVERSITY OF CALCUTTA
Introduction to File Handling
• Writing to a File Writel)
→ string value write in file
file = open("[Link]", "w")
[Link]("Welcome to Python file
handling class!") Writelines()
[Link]()
↳ list of Values.
• Explanation:
open ( "s. txt", "w")
• 'w' mode overwrites if file exists.
;: e)
• Creates new file if it doesn't exist.
. in range(5)
Val = input ( "Name a)
name. append (value)
DEPARTMENT OF APPLIED PHYSICS, f. write lines(name)
EVEN SEMESTER 446
UNIVERSITY OF CALCUTTA
f. closed
Introduction to File Handling
• Read Line by Line Using readline()
file = open("intro_example1.txt", "r")
print("Reading Line by Line:")
line1 = [Link]()
line2 = [Link]()
print("Line 1:", line1)
print("Line 2:", line2)
[Link]()
v
• readline() reads one line at a time.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 447
UNIVERSITY OF CALCUTTA
Introduction to File Handling
• Loop Over File Lines
morent print("Reading all lines using a loop:")
eff
file = open("intro_example1.txt", "r")
for line in file:
Oversees print([Link]()) # strip() to remove extra newline
theuseof [Link]()
read
• File objects are iterable, so for line in file works naturally.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 448
UNIVERSITY OF CALCUTTA
Introduction to File Handling
• Write Multiple Lines Using writelines()
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("intro_example3.txt", "w") as file:
no •[Link](lines)
need for
file-closed)
• writelines() takes a list of strings and writes all at once.
• Write student data in a text file
• Name, Roll Number, Branch (one per line)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 449
UNIVERSITY OF CALCUTTA
Introduction to File Handling
• File Check Before Reading
filename = "[Link]"
try:
with open(filename, "r") as file:
print([Link]())
•
except FileNotFoundError:
print(f"Error: The file '{filename}' does not exist.")
format
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 450
UNIVERSITY OF CALCUTTA
Using with Statement
• Automatically closes the file, even if error occurs.
with open("[Link]", "r") as file:
print([Link]())
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 451
UNIVERSITY OF CALCUTTA
Introduction to File Handling
> f= open eple-txt", "w"):
M- int (in no-of data"))
• Hands-on Setup:
• Create a file named [Link] and append new text.
• Write and read student data from a text file
• Name, Roll Number, Branch (one per line)
• Then read and print the content line by line using readline()
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 452
UNIVERSITY OF CALCUTTA
f- open (" example. tx " "W")
N: int (input( "Enter"))
for i in range (n).
N = input (("Enter name n,
R- int (input/" Enter resa,
B = input/" Enter branchy
f. write (N)
f. write (R)
f. Wnt (B
Introduction to File Handling
# Specify the full file path where you want to store the file
file_path = "D:/MyFiles/[Link]" # <-- Change this to your desired
location
# Step 1: Write names of 5 students
with open(file_path, "w") as file:
[Link]("Ravi\n")
[Link]("Anita\n")
[Link]("Sourav\n")
[Link]("Meera\n")
[Link]("Kunal\n")
# Step 2: Read and print each line using readline()
with open(file_path, "r") as file:
print("Reading student names line by line:")
line = [Link]()
while line:
print([Link]()) # strip() removes newline character
DEPARTMENT OF APPLIED PHYSICS,
line = [Link]()
EVEN SEMESTER 453
UNIVERSITY OF CALCUTTA
File Handling with Exception Handling
• Prevents program crash if file is missing.
• Clean error handling.
try:
with open("[Link]", "r") as file:
data = [Link]()
except FileNotFoundError:
print("The file does not exist!")
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 454
UNIVERSITY OF CALCUTTA
doubt
File Handling with Exception Handling
data = [
["Name", "Age", "Department"],
["Amit", "21", "CSE"],
["Priya", "22", "ECE"],
["Ravi", "23", "ME"]
]
with open("[Link]", "w") as file:
for row in data:
line = '|'.join(row) # Use | as delimiter
[Link](line + "\n")
with open("[Link]", "r") as file:
for line in file:
values = [Link]().split('|') # Split using the delimiter
print(values)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 455
UNIVERSITY OF CALCUTTA
Working with CSV Files
• CSV stands for Comma-Separated Values.
• It is a plain text file that stores tabular data (like a
spreadsheet or database table).
• Each line in a CSV file represents a row, and each value is
separated by a comma (,).
• Easily readable and editable using text editors or Excel.
• Lightweight and language-independent.
Name,Age,Department
Amit,21,CSE
Priya,22,ECE
DEPARTMENT OF APPLIED PHYSICS,
Rohan,20,ME
EVEN SEMESTER
UNIVERSITY OF CALCUTTA
456
Working with CSV Files
newline="" is important on Windows
to prevent extra blank lines.
• Writing CSV File writerow() writes one row at a time (as
import csv a list).
with open("[Link]", "w", newline="") as file:
writer = [Link](file)
[Link](["Name", "Roll No", "Marks"])
[Link](["Ravi", "101", "85"])
[Link](["Anita", "102", "90"])
import csv
with open("[Link]", "r") as
file:
reader = [Link](file)
for row in reader:
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 457
UNIVERSITYprint(row)
OF CALCUTTA
Working with CSV Files doubt
• Using DictWriter and DictReader
import csv
with open("students_dict.csv", "w", newline="") as file:
fieldnames = ["Name", "Age", "Department"]
writer = [Link](file, fieldnames=fieldnames)
[Link]()
[Link]({"Name": "Amit", "Age": 21, "Department": "CSE"})
[Link]({"Name": "Priya", "Age": 22, "Department": "ECE"})
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 458
UNIVERSITY OF CALCUTTA
Working with CSV Files
• Using DictWriter and DictReader
import csv
with open("students_dict.csv", "r") as file:
reader = [Link](file)
for row in reader:
print(row["Name"], "is from", row["Department"])
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 459
UNIVERSITY OF CALCUTTA
Working with CSV Files
• With different delimiter
import csv
with open("data_semicolon.csv", "w", newline="") as file:
writer = [Link](file, delimiter=';')
[Link](["Name", "Age", "Branch"])
[Link](["Amit", 21, "CSE"])
[Link](["Priya", 22, "ECE"])
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 460
UNIVERSITY OF CALCUTTA
Working with CSV Files
• With different delimiter
Separator Symbol Use Case
Comma , Default for .csv
Tab \t Often in .tsv files
Pipe ` `
Semicolon ; Excel exports
Space '' Custom formats
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 461
UNIVERSITY OF CALCUTTA
Working with JSON Files
• JSON stands for JavaScript Object Notation.
• It is a lightweight data-interchange format that is easy for humans to
read and write and easy for machines to parse and generate.
• It stores data as key-value pairs, very similar to Python dictionaries.
• JSON as key-JSON as key-value data format
{
• Use [Link]() and [Link]()value data format "name": "Amit",
"age": 21,
"department": "CSE"
}
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 462
UNIVERSITY OF CALCUTTA
Working with JSON Files
• Why Use JSON Files?
• Platform-independent way to store and exchange data.
• Used heavily in web APIs, data storage, and configuration files.
• Compatible with many programming languages, including Python.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 463
UNIVERSITY OF CALCUTTA
Working with JSON Files
• Writing JSON File
import json
data = {"name": "Amit", "age": 21, "marks": [75, 85,
90]}
with open("[Link]", "w") as file:
[Link](data, file)
import json
with open("[Link]", "r") as file:
content = [Link](file)
print(content)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 464
UNIVERSITY OF CALCUTTA
Converting Between Python and
JSON (In Memory)
• Convert Python to JSON String:
student = {"name": "Ravi", "age": 23}
json_data = [Link](student)
print(json_data) # Output: {"name": "Ravi",
"age": 23}
• Convert JSON String to Python Dictionary:
json_text = '{"name": "Ravi", "age":
23}'
student = [Link](json_text)
print(student["name"])
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 465
UNIVERSITY OF CALCUTTA
Recap
• Which of the following modes is used to open a file for writing and reading,
and overwrites the file if it already exists?
a) 'r+'
b) 'w+'
c) 'a+'
d) 'r'
• What does the readlines() function do in Python?
a) Reads one line from a file
b) Reads the entire file as a string
c) Returns a list of lines from the file
d) Closes the file
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 466
UNIVERSITY OF CALCUTTA
Recap
• Which keyword is used to ensure a file is automatically closed after its
operations are complete?
a) finally
b) exit
c) auto
d) with
• Which method is used to write a single line to a text file?
a) writeLine()
b) writeline()
c) write()
d) writer()
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 467
UNIVERSITY OF CALCUTTA
Example
• Create a Python program to: Start
• Input student details (name, Take student input (name, roll,
marks)
roll, marks)
Save the data to:
• Save data to CSV, JSON,
A .csv file using [Link]()
and TXT files
A .json file using [Link]()
• Read back and display the A .txt file using write()
saved data Open each file to read and display
the content
End
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 468
UNIVERSITY OF CALCUTTA
Example
Start import csv
import json
Take student input (name,
roll, marks) # Step 1: Input student data
Save the data to: name = input("Enter student name: ")
roll = input("Enter roll number: ")
A .csv file using marks = float(input("Enter marks: "))
[Link]()
A .json file using student = {
[Link]() "name": name,
A .txt file using write() "roll": roll,
"marks": marks
Open each file to read and }
display the content
End
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 469
UNIVERSITY OF CALCUTTA
Example
Start # Step 2: Save to CSV
Take student input (name, with open("[Link]", "w", newline="") as
roll, marks) csvfile:
writer = [Link](csvfile)
Save the data to: [Link](["Name", "Roll", "Marks"])
A .csv file using [Link]([student["name"],
[Link]() student["roll"], student["marks"]])
A .json file using print("Data saved to [Link]")
[Link]()
A .txt file using write()
Open each file to read and
display the content
End
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 470
UNIVERSITY OF CALCUTTA
Example
Start # Step 3: Save to JSON
Take student input (name, with open("[Link]", "w") as jsonfile:
roll, marks) [Link](student, jsonfile, indent=4)
print("Data saved to [Link]")
Save the data to:
A .csv file using # Step 4: Save to TXT
[Link]() with open("[Link]", "w") as txtfile:
A .json file using [Link](f"Name: {student['name']}\n")
[Link]() [Link](f"Roll: {student['roll']}\n")
[Link](f"Marks: {student['marks']}\n")
A .txt file using write() print("Data saved to [Link]")
Open each file to read and
display the content
End
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 471
UNIVERSITY OF CALCUTTA
Example
# Step 5: Read and display each file
Start print("\n Reading from [Link]:")
Take student input (name, with open("[Link]", "r") as file:
roll, marks) print([Link]())
Save the data to: print("Reading from [Link]:")
A .csv file using with open("[Link]", "r") as file:
[Link]() print([Link]())
A .json file using
[Link]() print("Reading from [Link]:")
with open("[Link]", "r") as file:
A .txt file using write() print([Link]())
Open each file to read and
display the content
End
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 472
UNIVERSITY OF CALCUTTA
Practice
Problem 1: Student Report Card Manager (TXT File)
Problem Statement:
Write a Python program to:
[Link] details for 5 students (name, roll number, marks in 3 subjects).
[Link] the total and average for each student.
[Link] a grade based on average:
•A+ (90+), A (80–89), B (70–79), C (60–69), F (below 60)
[Link] the report to a student_report.txt file in a clean tabular format.
[Link] the content of the file after writing.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 473
UNIVERSITY OF CALCUTTA
Practice
Problem 2: Course Registration System (CSV + JSON)
Problem Statement:
Design a menu-driven program that:
[Link] entry of student name, roll number, and chosen course.
[Link] each entry to a CSV file named course_enrollments.csv.
[Link] all student records to a JSON file (course_data.json) with proper
indentation.
[Link] loading and displaying all enrolled student data from the JSON file.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 474
UNIVERSITY OF CALCUTTA
COMPUTER PROGRAMMING
PCC-EE 405
Nirmal Murmu
Department of Applied Physics
University of Calcutta
Course Outcomes
• At the end of this course, students will be able to learn about
• CO1: Identify fundamental programming concepts, data structures, and file
handling techniques used in software development.
• CO2: Explain the principles of object-oriented programming, event-driven
programming, and their applications in GUI and system programming.
• CO3: Develop basic to intermediate-level applications using programming
languages and libraries for file manipulation, data handling, and user interaction.
• CO4: Compare and evaluate different programming approaches, paradigms, and
tools for solving computational problems effectively.
• CO5: Assess the efficiency, scalability, and usability of developed applications,
optimizing code performance and debugging issues effectively.
•
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 2
UNIVERSITY OF CALCUTTA
Syllabus
• Module 1: Introduction to Visual basic (8 hour)
• Fundamentals of GUI development using [Link], Concepts of object, method and event in [Link],
Utilisation of various tools, Components and References, basic concept of event handling, I/O File
handling and data handling.
• Module 2: Visual basic Programming (10 hour)
• Learn to develop program in windows environment, simple display program, Key board and
mouse interactive program, Reading and writing I/O files, handling of other windows program -
like reading and writing Excel file, Excel plotting, interfacing of USB/COM ports, development of
net based application in client/server mode.
• Module 3: Introduction to Python libraries (10 hour)
• Python Types, Expressions, Strings, Lists, Tuples, Python memory model (names, mutable and
immutable values), List operations, Regular Expressions, Python Functions, Abstract Data types,
Classes and Objects in Python, Exception handling, Handling files, Python
Scientific/Statistical/Machine Learning Libraries.
• Module 4: Python programming (12 hour)
• Python Programming: Object based program using multi threading, I/O handling of files, Printing
and display using timer operation, program for handling of interfacing of cameras, program to
develop machine learning based applications.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 3
UNIVERSITY OF CALCUTTA
References
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 4
UNIVERSITY OF CALCUTTA
Lecture Plan
Lecture No. Topic Key Concepts
Variables, Data Types, and Python types, expressions,
1
Operators operators, type conversions
Lists, tuples, slicing, loops (for,
2 Arrays and Flow Control
while), conditional statements
Defining functions, arguments,
3 Methods and Functions
return values, recursion
Reading/writing files, handling CSV,
4 File Handling
JSON
Introduction to Scientific NumPy, Pandas, Matplotlib for data
5
Libraries processing
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 5
UNIVERSITY OF CALCUTTA
Lecture Plan
Lecture No. Topic Key Concepts
Object-Oriented Programming Classes, objects, inheritance,
1
(OOPs) in Python polymorphism
Multi-threading and Advanced File Threading basics, file operations,
2
Handling concurrent programming
Timers, Event Handling, and GUI Timer-based operations, GUI
3
Development programming using Tkinter/PyQt
Using OpenCV for image
Camera Interfacing and Data
4 processing, real-time data
Acquisition
acquisition
Machine Learning and AI Basics of Scikit-learn, TensorFlow,
5
Applications AI-driven applications
Final Project Discussion and Developing real-world
6
EVEN SEMESTER
Implementation DEPARTMENT OF APPLIED PHYSICS,
applications, project review 6
UNIVERSITY OF CALCUTTA
Python: Basics
• Variables
• Data types
• Operators
• Arrays
• Flow Control
• Methods
• File Handling
• OOPS
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 475
UNIVERSITY OF CALCUTTA
Object-Oriented Framework
• Two basic programming paradigms:
• Procedural
• Organizing programs around functions or blocks of statements which
manipulate data.
• Object-Oriented
• combining data and functionality and wrap it inside what is called an object.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 476
UNIVERSITY OF CALCUTTA
Object
• An object is an instance of a class.
• fundamental principles of OOP: Encapsulation, Inheritance,
Polymorphism, and Abstraction
• Integers, floating-point numbers, strings, and functions
• function objects, we have treated these objects as passive data
• In object-oriented programming, fuse data and functions together
into software units called objects (rather than treating data as
passive values and functions as active agents that manipulate
data)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 477
UNIVERSITY OF CALCUTTA
Object
• A typical object consists of two parts: data and methods
• The instance variables and methods of an object constitutes the
object’s members
• An object’s data consists of its instance variables.
• The term instance variable comes from the fact that the data is represented by a
variable owned by an object, and an object is an instance of a class.
• Other names for instance variables include attributes and fields.
• Methods are like functions, and they are known also as operations.
• The code that uses an object is called the object’s client
• So, an object provides a service to its clients.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 478
UNIVERSITY OF CALCUTTA
Object-Oriented Framework
• Classes and objects are the two main aspects of object
oriented programming.
• A class creates a new type.
• Where objects are instances of the class.
• An analogy is that we can have variables of type int which
translates to saying that variables that store integers are
variables which are instances (objects) of the int class.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 479
UNIVERSITY OF CALCUTTA
Object-Oriented Framework
• Objects can store data using ordinary variables that belong
to the object.
• Variables that belong to an object or class are called as
fields.
• Objects can also have functionality by using functions that
belong to the class. Such functions are called methods.
• This terminology is important because it helps us to
differentiate between a function which is separate by itself
and a method which belongs to an object.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 480
UNIVERSITY OF CALCUTTA
Object-Oriented Framework
• Remember, that fields are of two types
• they can belong to each instance (object) of the class
• or they belong to the class itself.
• They are called instance variables and class variables respectively.
• A class is created using the class keyword.
• The fields and methods of the class are listed in an
indented block.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 481
UNIVERSITY OF CALCUTTA
Class and Object
• A class is a collection of objects
• Blueprint for the object
• Contains all the attributes and behaviours
class class1(): % class 1 is the name of the class
• Objects are an instance of a class
• Entity that has state and behavior
obj = class1()
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 482
UNIVERSITY OF CALCUTTA
Class and Object
• Python's objects have a bunch of "special methods" often
called magic methods.
• The most common is the __init__ method
• The __init__ method is a method to specify anything that
want to happen when the object is initialized
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 483
UNIVERSITY OF CALCUTTA
Creating a Class
class Person:
pass # A new block
p = Person()
print (p)
#<__main__.Person instance at 0x816a6cc>
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 484
UNIVERSITY OF CALCUTTA
Fields
name = value [Link]
• Example: 1 class Point:
2 x = 0
class Point: 3 y = 0
x = 0
y = 0
# main
p1 = Point()
p1.x = 2
p1.y = -5
• can be declared directly inside class (as shown here)
or in constructors (more common)
• Python does not really have encapsulation or private fields
• relies on caller to "be nice" and not mess with objects' contents
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 485
UNIVERSITY OF CALCUTTA
Using a Class
import class
• client programs must import the classes they use
point_main.py
1 from Point import *
2
3 # main
4 p1 = Point()
5 p1.x = 7
6 p1.y = -3
7 ...
8
9 # Python objects are dynamic (can add fields any time!)
10 [Link] = "Tyler Durden"
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 486
UNIVERSITY OF CALCUTTA
The self
• Class methods have only one specific difference from
ordinary functions
• they have an extra variable that has to be added to the beginning
of the parameter list
• but we do not give a value for this parameter when we call the
method.
• this particular variable refers to the object itself,
• and by convention, it is given the name self.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 487
UNIVERSITY OF CALCUTTA
The self
• Although, we can give any name for this parameter, it is
strongly recommended that we use the name self.
• Any other name is definitely frowned upon.
• There are many advantages to using a standard name
• any reader of our program will immediately recognize that it is the
object variable i.e. the self and even specialized IDEs (Integrated
Development Environments such as Boa Constructor) can help us
if we use this particular name.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 488
UNIVERSITY OF CALCUTTA
The self
• Python will automatically provide this value in the function
parameter list.
• For example, if we have a class called MyClass and an
instance (object) of this class called MyObject, then when
we call a method of this object as [Link](arg1,
arg2), this is automatically converted to
[Link](MyObject, arg1, arg2).
• This is what the special self is all about.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 489
UNIVERSITY OF CALCUTTA
Object Methods
class Person:
def sayHi(self):
print ('Hello, how are you?’ )
p = Person()
[Link]()
# This short example can also be #written as
Person().sayHi()
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 490
UNIVERSITY OF CALCUTTA
Object Methods
def name(self, parameter, ..., parameter):
statements
• self must be the first parameter to any object method
• represents the "implicit parameter" (this in Java)
• must access the object's fields through the self reference
class Point:
def translate(self, dx, dy):
self.x += dx
self.y += dy
...
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 491
UNIVERSITY OF CALCUTTA
"Implicit" Parameter (self)
• Java: this, implicit
public void translate(int dx, int dy) {
x += dx; // this.x += dx;
y += dy; // this.y += dy;
}
• Python: self, explicit
def translate(self, dx, dy):
self.x += dx
self.y += dy
• Exercise: Write distance, set_location, and
distance_from_origin methods.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 492
UNIVERSITY OF CALCUTTA
Exercise Answer
[Link]
1 from math import *
2
3 class Point:
4 x = 0
5 y = 0
6
7 def set_location(self, x, y):
8 self.x = x
9 self.y = y
10 def distance_from_origin(self):
11 return sqrt(self.x * self.x + self.y * self.y)
12 def distance(self, other):
13 dx = self.x - other.x
14 dy = self.y - other.y
15 return sqrt(dx * dx + dy * dy)
16 def translate(self, dx, dy):
17 self.x += dx
18 self.y += dy
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 493
UNIVERSITY OF CALCUTTA
Calling Methods
• A client can call the methods of an object in two ways:
• (the value of self can be an implicit or explicit parameter)
1) [Link](parameters)
or
2) [Link](object, parameters)
• Example:
p = Point()
[Link](1, 5)
[Link](p, 1, 5)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 494
UNIVERSITY OF CALCUTTA
The __init__ method
• __init__ is called immediately after an instance of the class is
created.
• The __init__ method is a method to specify anything that want to
happen when the object is initialized
• It would be tempting but incorrect to call this the constructor of
the class.
• Tempting, because it looks like a constructor (by convention, __init__ is
the first method defined for the class), acts like one (it's the first piece of
code executed in a newly created instance of the class), and even
sounds like one ("init" certainly suggests a constructor-ish nature).
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 495
UNIVERSITY OF CALCUTTA
The __init__ method
• Incorrect, because the object has already been constructed by the
time __init__ is called, and we already have a valid reference to the
new instance of the class.
• But __init__ is the closest thing we're going to get in Python
to a constructor, and it fills much the same role.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 496
UNIVERSITY OF CALCUTTA
Constructors
def __init__(self, parameter, ..., parameter):
statements
• a constructor is a special method with the name __init__
• Example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
...
• How would we make it possible to construct a
Point() with no parameters to get (0, 0)?
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 497
UNIVERSITY OF CALCUTTA
Initialization
[Link]
1 class Car:
2 def __init__(self, brand, model):
3 [Link] = brand
4 [Link] = model
5
6 def display(self):
7 print(f"Car: {[Link]} {[Link]}")
8
9 # Creating object and calling method
10 my_car = Car(“Mahindra", “Thar")
11 my_car.display()
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 498
UNIVERSITY OF CALCUTTA
Initialization
[Link]
1 class Student:
2 def __init__(self, name, roll):
3 [Link] = name
4 [Link] = roll
5
6 # Creating objects
7 student1 = Student("Ravi", 101)
8 student2 = Student("Priya", 102)
9
10 print([Link]) # Output: Ravi
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 499
UNIVERSITY OF CALCUTTA
__init__ in Python: Initializer vs
Constructor
• Many programmers coming from • However, __init__ is not
other languages (like Java or C++) technically a constructor.
naturally assume that __init__ is Here's why:
Python's constructor because: • Object Already Exists When
• It's the first method typically __init__ is Called:
defined in a class • In Python, the object is actually
created before __init__ is called
• It's automatically called when • When you write obj = MyClass(),
creating a new instance Python first:
• It handles initialization of instance • Creates the raw object in
variables memory (this is the actual
construction)
• Its name "init" suggests • Then calls __init__ to initialize
construction that object
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 500
UNIVERSITY OF CALCUTTA
Class Attributes vs Instance Attributes
class Point: p1 = Point()
p2 = Point()
class Point:
def __init__(self, x=0, y=0):
x=0
print(p1.x, p1.y) self.x = x # Instance attribute
y=0 print(p2.x, p2.y) self.y = y
• x = 0 and y = 0 are class p1 = Point()
attributes p2 = Point()
• They belong to the class itself, p1.x = 5 # Only affects p1
not individual instances • Instance Attributes:
• All instances share these • These would be created inside
same values initially __init__ (which this class doesn't
have)
• Each instance would have its own
separate copy
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 501
UNIVERSITY OF CALCUTTA
Class and Object Variables
class Person:
'''Represents a person.'''
population = 0
def __init__(self, name):
'''Initializes the person.'''
[Link] = name
print ('(Initializing %s)’ % [Link])
# When this person is created, # he/she adds to the
population
[Link] += 1
def sayHi(self):
'''Greets the other person. Really, that's all it does.'''
print ('Hi, my name is %s.' % [Link])
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 502
UNIVERSITY OF CALCUTTA
Class and Object Variables
def howMany(self):
'''Prints the current population.''‘
# There will always be at least one person
if [Link] == 1:
print 'I am the only person here.'
else:
print 'We have %s persons here.' % [Link]
swaroop = Person('Swaroop')
[Link]()
[Link]()
kalam = Person('Abdul Kalam')
[Link]()
[Link]()
[Link]()
[Link]()
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
503
UNIVERSITY OF CALCUTTA
Example: OOPS
class Parrot: # instantiate the Parrot class
blu = Parrot("Blu", 10)
# class attribute woo = Parrot("Woo", 15)
species = "bird"
# access the class attributes
# instance attribute print("Blu is a {}".format(blu.__class__.species))
def __init__(self, name, age): print("Woo is also a
{}".format(woo.__class__.species))
[Link] = name
[Link] = age
# access the instance attributes
print("{} is {} years old".format( [Link],
[Link]))
print("{} is {} years old".format( [Link],
[Link]))
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 504
UNIVERSITY OF CALCUTTA
Example: OOPS
class employee():
def __init__(self,name,age,id,salary): # creating a function
[Link] = name # self is an instance of a class
[Link] = age
[Link] = salary
[Link] = id
emp1 = employee("harshit",22,1000,1234) #creating objects
emp2 = employee("arjun",23,2000,2234)
print(emp1.__dict__) #Prints dictionary
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 505
UNIVERSITY OF CALCUTTA
Example: OOPS with Methods
class Parrot: # instantiate the object
blu = Parrot("Blu", 10)
# instance attributes
def __init__(self, name, age): # call our instance methods
[Link] = name print([Link]("'Happy'"))
[Link] = age print([Link]())
# instance method
def sing(self, song):
return "{} sings {}".format([Link], song)
def dance(self):
return "{} is now dancing".format([Link])
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 506
UNIVERSITY OF CALCUTTA
Encapsulation
• Definition: Restricting access to certain parts of an object.
• Private Attributes: Attributes prefixed with __ (double underscore).
• Data Hiding: Protecting an object's internal state by hiding
implementation details
• Controlled Access: Providing public methods to interact with private
data
• Implementation Independence: Allowing internal changes without
affecting external code
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 507
UNIVERSITY OF CALCUTTA
Encapsulation
[Link]
1 class BankAccount:
2 def __init__(self, owner, balance):
3 [Link] = owner
4 self.__balance = balance # Private attribute
5
6 def get_balance(self):
7 return self.__balance
8
9 account = BankAccount(“Shyamal”, 5000)
10 print(account.get_balance()) # Output: 5000
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 508
UNIVERSITY OF CALCUTTA
Encapsulation
In Python, encapsulation is implemented by using:
•Public Attributes:
•Accessible from anywhere: Inside or outside the class.
•No special syntax is needed; the attribute is just defined normally.
[Link]
1 class Student:
2 def __init__(self, name):
3 [Link] = name # Public attribute
4
5 s1 = Student("Rahul")
6 print([Link]) # Output: Rahul
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 509
UNIVERSITY OF CALCUTTA
Encapsulation
In Python, encapsulation is implemented by using:
•Protected Attributes:
•Accessible within the class and its subclasses.
•By convention, prefixed with a single underscore (_).
•Not truly private, but treated as a non-public variable.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 510
UNIVERSITY OF CALCUTTA
Encapsulation
[Link]
1 class Student:
2 def __init__(self, name, age):
3 [Link] = name
4 self._age = age # Protected attribute
5
6 class GraduateStudent(Student):
7 def display(self):
8 print(f"Name: {[Link]}, Age: {self._age}")
9
10 g = GraduateStudent("Priya", 22)
11 [Link]() # Output: Name: Priya, Age: 22
12 print(g._age) # Output: 22 (Accessible, but not recommended)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 511
UNIVERSITY OF CALCUTTA
Encapsulation
In Python, encapsulation is implemented by using:
•Private Attributes:
•Accessible only within the class.
•Defined by prefixing the attribute name with double underscores
(__).
•Python uses name mangling to make them inaccessible outside the
class.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 512
UNIVERSITY OF CALCUTTA
Encapsulation
[Link]
1 class BankAccount:
2 def __init__(self, owner, balance):
3 [Link] = owner
4 self.__balance = balance # Private attribute
5
6 def display_balance(self):
7 return self.__balance
8
9 acc = BankAccount("Ravi", 1000)
10 print(acc.display_balance()) # Output: 1000
11
12 # Trying to access directly
13 try:
14 print(acc.__balance) # This will raise an AttributeError
15 except AttributeError as e:
16 print(e) # Output: 'BankAccount' object has no attribute '__balance'
17
18 # Accessing using name mangling
19 print(acc._BankAccount__balance) # Output: 1000 (But not recommended)
20 SEMESTER
EVEN print(acc.__balance) DEPARTMENT OF APPLIED PHYSICS, 513
UNIVERSITY OF CALCUTTA
OOP Methodology: Encapsulation
• Restrict access to methods and variables
class Computer: c = Computer()
[Link]()
def __init__(self):
self.__maxprice = 900 # change the price
c.__maxprice = 1000
def sell(self): [Link]()
print("Selling Price: {}".format(self.__maxprice))
# using setter function
def setMaxPrice(self, price): [Link](1000)
self.__maxprice = price [Link]()
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 514
UNIVERSITY OF CALCUTTA
Encapsulation
Attribute Type Syntax Access Level Use Case
Accessible from anywhere General-purpose
Public [Link]
(class, subclass, outside) variables
Accessible from class and Intended for internal use
Protected self._name
subclasses but not enforced
Accessible only within the
Private self.__name Sensitive or critical data
class (with name mangling)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 515
UNIVERSITY OF CALCUTTA
Inheritance
• One of the major benefits of object-oriented programming
is reuse of code
• One of the ways this is achieved is through the inheritance
mechanism.
• Creating a new class from an existing class (Parent-Child
relationship).
• Inheritance can be best imagined as implementing a type
and subtype relationship between classes.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 516
UNIVERSITY OF CALCUTTA
Inheritance
class name(superclass):
statements
• Example:
class Point3D(Point): # Point3D extends Point
z = 0
...
• Python also supports multiple inheritance
class name(superclass, ..., superclass):
statements
(if > 1 superclass has the same field/method, conflicts are resolved in left-to-right order)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 517
UNIVERSITY OF CALCUTTA
Inheritance
[Link]
1 class Animal:
2 def speak(self):
3 print("Animal speaks")
4
5 class Dog(Animal): # Inheriting from Animal class
6 def bark(self):
7 print("Dog barks")
8
9 dog = Dog()
10 [Link]() # Output: Animal speaks
11 [Link]() # Output: Dog barks
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 518
UNIVERSITY OF CALCUTTA
Using Inheritance
class SchoolMember:
‘’’Represents any school member.’’’
def __init__(self, name, age):
[Link] = name
[Link] = age
print ('(Initialized SchoolMember: %s)' % [Link] )
def tell(self):
print ('Name:"%s" Age:"%s" ' % ([Link], [Link]), )
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 519
UNIVERSITY OF CALCUTTA
Using Inheritance
class Teacher(SchoolMember):
'''Represents a teacher.'‘’
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
[Link] = salary
print ('(Initialized Teacher: %s)' % [Link] )
def tell(self):
[Link](self)
print ('Salary:"%d"' % [Link] )
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 520
UNIVERSITY OF CALCUTTA
Using Inheritance
class Student(SchoolMember):
'''Represents a student.'‘’
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
[Link] = marks
print ('(Initialized Student: %s)' % [Link] )
def tell(self):
[Link](self)
print ('Marks:"%d"' % [Link] )
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 521
UNIVERSITY OF CALCUTTA
Using Inheritance
t = Teacher('Mrs. Abraham', 40, 30000)
s = Student('Swaroop', 21, 75)
members = [t, s]
for member in members:
[Link]() # Works for instances of Student as well
as Teacher
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 522
UNIVERSITY OF CALCUTTA
Multiple Inheritance
• Python supports a limited form of multiple inheritance as
well.
• A class definition with multiple base classes looks as
follows:
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
<statement-N>
• The only rule necessary to explain the semantics is the
resolution rule used for class attribute references.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 523
UNIVERSITY OF CALCUTTA
Multiple Inheritance
• This is depth-first, left-to-right. Thus, if an attribute is not found in
DerivedClassName, it is searched in Base1, then (recursively) in the
base classes of Base1, and only if it is not found there, it is searched
in Base2, and so on.
• A well-known problem with multiple inheritance is a class derived
from two classes that happen to have a common base class. While it
is easy enough to figure out what happens in this case (the instance
will have a single copy of “instance variables” or data attributes used
by the common base class).
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 524
UNIVERSITY OF CALCUTTA
OOP Methodology: Inheritance
• Creating a new class for using details of an existing class
without modifying it
• Parent class and child class
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 525
UNIVERSITY OF CALCUTTA
Example: Single Inheritance
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal): # Inheriting from
Animal
def bark(self):
print("Dog barks")
dog = Dog()
[Link]() # Output: Animal speaks (Inherited from parent class)
[Link]() # Output: Dog barks (Defined in child class)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 526
UNIVERSITY OF CALCUTTA
Example: Multilevel Inheritance
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal): # Inheriting from Animal
def bark(self):
print("Dog barks")
class Bulldog(Dog): # Inheriting from Dog
def special(self):
print("Bulldog has a strong bite")
b = Bulldog()
[Link]()
[Link]()
[Link]()
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 527
UNIVERSITY OF CALCUTTA
Example: Hierarchical Inheritance
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal): # Inheriting from Animal
def bark(self):
print("Dog barks")
class Cat(Animal): # Inheriting from Animal
def meow(self):
print("Cat meows")
d = Dog()
c = Cat()
[Link]()
[Link]()
[Link]()
[Link]()
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 528
UNIVERSITY OF CALCUTTA
Example: Multiple Inheritance
# parent class
class Father:
def speak(self):
print("Father speaks")
class Mother:
def cook(self):
print("Mother cooks")
c = Child()
class Child(Father, Mother): # Inheriting [Link]()
from both Father and Mother [Link]()
def play(self): [Link]()
print("Child plays")
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 529
UNIVERSITY OF CALCUTTA
Example: Hybrid Inheritance
class Animal:
def speak(self):
print("Animal speaks")
class Mammal(Animal):
def walk(self):
print("Mammal walks")
class Bird(Animal):
def fly(self):
print("Bird flies")
class Bat(Mammal, Bird): # Inheriting from Mammal and Bird
def echo(self):
print("Bat uses echolocation")
b = Bat()
[Link]()
[Link]()
DEPARTMENT OF APPLIED PHYSICS, [Link]()
EVEN SEMESTER 530
UNIVERSITY OF CALCUTTA [Link]()
Inheritance
Concept Explanation
Redefining a parent class method in the
Method Overriding
child class.
super() function Allows access to parent class methods.
MRO (Method Resolution Determines the order in which base
Order) classes are searched.
Use super().method_name() to call a
Accessing Parent Class
parent class method.
Polymorphism in
Achieved through method overriding.
Inheritance
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 531
UNIVERSITY OF CALCUTTA
Practice Problem
Problem:
Create a base class Person with attributes name and age. Create two
child classes Student and Teacher that inherit from Person.
[Link] Student class should have an additional attribute marks.
[Link] Teacher class should have an additional attribute salary.
[Link] method overriding by defining a display() method in both
child classes that overrides the parent class method.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 532
UNIVERSITY OF CALCUTTA
Polymorphism
• Having multiple forms. Same method name but different
implementations.
• Achieved through Method Overloading and Method
Overriding.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 533
UNIVERSITY OF CALCUTTA
Polymorphism
[Link]
1 class Shape:
2 def area(self):
3 pass
4
5 class Square(Shape):
6 def area(self, side):
7 return side * side
8
9 class Circle(Shape):
10 def area(self, radius):
11 return 3.14 * radius * radius
12
13 square = Square()
14 circle = Circle()
15
16 print([Link](4)) # Output: 16
17 print([Link](3)) # Output: 28.26
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 534
UNIVERSITY OF CALCUTTA
OOP Methodology: Polymorphism
• To use a common interface for multiple forms
class Parrot: # common interface
def flying_test(bird):
def fly(self): [Link]()
print("Parrot can fly")
#instantiate objects
def swim(self): blu = Parrot()
print("Parrot can't swim") peggy = Penguin()
class Penguin: # passing the object
flying_test(blu)
def fly(self): flying_test(peggy)
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 535
UNIVERSITY OF CALCUTTA
Abstraction
• Hiding complex details and exposing only necessary parts.
• Implemented using Abstract Classes.
• When you drive a car, you press the accelerator to speed
up. You don't need to know how the engine works
internally. The car abstracts the complexity and provides a
simple interface (accelerator pedal) for the user.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 536
UNIVERSITY OF CALCUTTA
Abstraction
[Link]
1 from abc import ABC, abstractmethod
2
3 class Animal(ABC):
4 @abstractmethod
5 def sound(self):
6 pass
7
8 class Dog(Animal):
9 def sound(self):
10 return "Bark"
11
12 dog = Dog()
13 print([Link]()) # Output: Bark
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 537
UNIVERSITY OF CALCUTTA
OOP Methodology: Polymorphism
from abc import ABC, abstractmethod class Cat(Animal):
def sound(self):
# Abstract Class return "Meow"
class Animal(ABC):
@abstractmethod def habitat(self):
def sound(self): return "Domestic"
pass
# Instantiate objects
@abstractmethod dog = Dog()
def habitat(self): cat = Cat()
pass
print([Link]()) # Output: Bark
# Concrete Class (Implementing Abstract Class) print([Link]()) # Output:
class Dog(Animal): Domestic
def sound(self): print([Link]()) # Output: Meow
return "Bark" print([Link]()) # Output:
Domestic
def habitat(self):
return "Domestic"
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 538
UNIVERSITY OF CALCUTTA
Magic Methods (Dunder Methods)
• Special methods with __ prefix and suffix (e.g., __init__,
__str__, __repr__).
• Enable operator overloading and customization of built-in
behavior.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 539
UNIVERSITY OF CALCUTTA
Magic Methods (Dunder Methods)
• To provide customized behavior for built-in operations.
• To implement operator overloading.
• To make user-defined classes behave like built-in types.
• To enhance code readability and efficiency.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 540
UNIVERSITY OF CALCUTTA
Magic Methods (Dunder Methods)
• __init__() - Constructor Method
• Called when an object is created.
• Used to initialize instance variables.
[Link]
1 class Student:
2 def __init__(self, name, roll):
3 [Link] = name
4 [Link] = roll
5
6 student1 = Student("Ravi", 101)
7 print([Link])
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 541
UNIVERSITY OF CALCUTTA
Magic Methods (Dunder Methods)
• __str__() - String Representation
• Provides a user-friendly string representation of an object.
• Called when print() or str() is used.
[Link]
1 class Student:
2 def __init__(self, name, roll):
3 [Link] = name
4 [Link] = roll
5
6 def __str__(self):
7 return f"Student(Name: {[Link]}, Roll: {[Link]})"
8
9 student1 = Student("Ravi", 101)
10 print(student1) # Output: Student(Name: Ravi, Roll: 101)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 542
UNIVERSITY OF CALCUTTA
Magic Methods (Dunder Methods)
• __add__() - Operator Overloading
• Enables the + operator to be customized for user-defined
classes.
[Link]
1 class Point:
2 def __init__(self, x, y):
3 self.x = x
4 self.y = y
5 def __add__(self, other):
6 return Point(self.x + other.x, self.y + other.y)
7 def __str__(self):
8 return f"({self.x}, {self.y})"
9
10 p1 = Point(1, 2)
11 p2 = Point(3, 4)
12 p3 = p1 + p2
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
543
13 print(p3) # Output: (4, 6)
UNIVERSITY OF CALCUTTA
Magic Methods (Dunder Methods)
Magic Method Description Example Usage
__new__(cls,
Creates a new instance (constructor) obj = MyClass()
[...])
__init__(self,
Initializes the instance obj = MyClass(args)
[...])
__del__(self) Destructor (cleanup before deletion) del obj
String Representation
__str__(self) Informal string representation str(obj), print(obj)
__repr__(self) Official string representation repr(obj), console
__format__(self,
Custom string formatting format(obj, spec)
Methods
format_spec)
__bytes__(self) Byte representation
DEPARTMENT OF APPLIED PHYSICS,
bytes(obj)
EVEN SEMESTER 544
UNIVERSITY OF CALCUTTA
Magic Methods (Dunder Methods)
Magic Method Description Example Usage
Comparison Operators
__eq__(self, other) == Equality check
__ne__(self, other) != Inequality check
__lt__(self, other) < Less than
__gt__(self, other) > Greater than
__le__(self, other) <= Less than or equal
__ge__(self, other) >= Greater than or equal
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 545
UNIVERSITY OF CALCUTTA
Magic Methods (Dunder Methods)
Magic Method Description Example Usage
__add__(self, other) + Addition
Arithmetic Operations
__sub__(self, other) - Subtraction
__mul__(self, other) * Multiplication
__truediv__(self, other) / Division (float)
__floordiv__(self, other) // Floor division
__mod__(self, other) % Modulus
__pow__(self, other) ** Exponentiation
__add__(self, other) + Addition
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 546
UNIVERSITY OF CALCUTTA
Magic Methods (Dunder Methods)
Magic Method Description Example Usage
__len__(self) Returns length len(obj)
__getitem__(self, key) Access item by key/index obj[key]
__setitem__(self, key, value) Set item by key/index obj[key] = value
__delitem__(self, key) Delete item by key/index del obj[key]
Check if item exists
__contains__(self, item) item in obj
(in operator)
__iter__(self) Returns iterator for x in obj
__next__(self) Next item in iteration next(obj)
__len__(self) Returns length len(obj)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 547
UNIVERSITY OF CALCUTTA
Class Method
• Bound to the class and not the instance of the class
• Modify a class state that applies across all instances of the class.
• Defined using the @classmethod decorator.
• Takes cls as the first argument (instead of self), which refers to the
class itself.
• Can access or modify class variables but not instance variables.
• Can be called using [Link]() or [Link]().
• Commonly used for factory methods, where the method returns an
instance of the class.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 548
UNIVERSITY OF CALCUTTA
Class Method
___.py
1 class School:
2 school_name = "Green Valley High" # Class variable
3
4 @classmethod
5 def change_name(cls, new_name):
6 cls.school_name = new_name # Modifying class variable
7
8 @classmethod
9 def show_name(cls):
10 print(f"School Name: {cls.school_name}")
11
12 # Accessing class method using class name
13 School.show_name() # Output: School Name: Green Valley High
14
15 # Changing the school name
16 School.change_name("Blue River Academy")
17 School.show_name() # Output: School Name: Blue River Academy
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 549
UNIVERSITY OF CALCUTTA
Class Methods
Static Methods Class Methods
• Methods within a class that do not have • Methods that can access class-level variables
access to instance (self) or class (cls) data. and methods, but not instance attributes
directly.
• Bound To: The class, not any specific object
instance. • Bound To: The class, not a specific object.
• Accessibility: Cannot modify or access • Accessibility: Can access and modify class
instance attributes or class variables. variables or call other class methods.
• Purpose: Generally used for utility functions • Purpose: Often used to define factory methods
or functions that logically belong to the class or modify class state.
but don’t use or modify any instance or class-
level data. • Decorator: @classmethod
• Decorator: @staticmethod • Takes: The cls argument which refers to the
class itself.
• Cannot: Access any instance attributes or
class attribut • Can: Alter the class state, but not instance-
specific data.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 550
UNIVERSITY OF CALCUTTA
Class Methods
Static Methods Class Methods
class MathOperations: class Employee:
@staticmethod company_name = "TechCorp"
def add(x, y):
return x + y @classmethod
def change_company_name(cls,
# Accessing via class name
print([Link](10, 5)) new_name):
cls.company_name = new_name #
Modifies class-level attribute
# Accessing via class name
Employee.change_company_name("InnovaTech")
print(Employee.company_name)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 551
UNIVERSITY OF CALCUTTA
Class Methods
Static Methods Class Methods
class myClass: class myClass:
def __init__(self): count = 0
self.x = x
def __init__(self):
@staticmethod
self.x = x
def staticMethod():
return ("i am a static method“)
@classmethod
# Notice staticMethod does not require def classMethod(cls):
the self parameter [Link] += 1
# The classMethod can access and modify
class variables. It takes the class name
as a required parameter
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 552
UNIVERSITY OF CALCUTTA
Class Methods
Static Methods Static Methods
class Calculator: class Calculator:
def addNumbers(x, y): # create addNumbers static method
return x + y @staticmethod
def addNumbers(x, y):
# create addNumbers static method
return x + y
[Link] =
staticmethod([Link])
print('Product:',
print('Product:', [Link](15, 110))
[Link](15, 110))
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 553
UNIVERSITY OF CALCUTTA
Complete Point Class
[Link]
1 from math import *
2
3 class Point:
4 def __init__(self, x, y):
5 self.x = x
6 self.y = y
7
8 def distance_from_origin(self):
9 return sqrt(self.x * self.x + self.y * self.y)
10
11 def distance(self, other):
12 dx = self.x - other.x
13 dy = self.y - other.y
14 return sqrt(dx * dx + dy * dy)
15
16 def translate(self, dx, dy):
17 self.x += dx
18 self.y += dy
19
20 def __str__(self):
21 return "(" + str(self.x) + ", " + str(self.y) + ")"
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 554
UNIVERSITY OF CALCUTTA
Complete Student Class
[Link]
1 class Student:
2 school_name = "Green Valley High" # Class variable
3
4 def __init__(self, name, age):
5 [Link] = name
6 [Link] = age
7
8 @classmethod
9 def set_school_name(cls, name):
10 cls.school_name = name # Modifying class variable
11
12 @staticmethod
13 def is_adult(age):
14 return age >= 18
15
16 # Class Method
17 Student.set_school_name("Blue River Academy")
18 print(Student.school_name) # Output: Blue River Academy
19
20 # Static Method
21 print(Student.is_adult(20)) # Output: True
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 555
UNIVERSITY OF CALCUTTA
String Objects
• Objects bundle data and functions together, and the data
that comprise a string
name = input("Please enter your name:") Please enter your name: Shyam
print("Hello " + [Link]() + ", how are you?") Hello SHYAM, how are you?
• The expression [Link]() within the print statement
represents a method call
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 556
UNIVERSITY OF CALCUTTA
String Objects
• object is an expression that represents object
• name is a reference to a string object.
• The period, pronounced dot, associates an object expression
with the method to be called
• methodname is the name of the method to execute.
• The parameterlist is comma-separated list of parameters to the
method
• May empty but required
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 557
UNIVERSITY OF CALCUTTA
String Objects
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 558
UNIVERSITY OF CALCUTTA
String Objects
>>> 'aBcDeFgHiJ'.upper() s = "ABCDEFGHIJK“
'ABCDEFGHIJ’ print(s)
>>> 'This is a sentence.'.rjust(25, '-') for i in range(len(s)):
'------This is a sentence. print("[", s[i], "]", sep="", end="")
print() # Print newline
>>> s = 'ABCEFGHI’
for ch in s:
>>> s
print("<", ch, ">", sep="", end="")
'ABCEFGHI’
print() # Print newline
>>> s.__getitem__(0)
'A’
>>> s.__getitem__(1)
‘B’
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 559
UNIVERSITY OF CALCUTTA
File Objects
• The data obtain after the end of execution, are not available
for future
• Python’s standard library has a file class to make objects
that can store or append data to, and retrieve data from,
disk
• Formal name of the class of file objects TextIOWrapper, and
it is found in the io module
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 560
UNIVERSITY OF CALCUTTA
File Objects
• The functions and classes defined in the io module are available
to any program, and no import statement is required
• f = open('[Link]', 'r’) Default value
• creates and returns a file object (literally a TextIOWrapper object) named
f
• The first argument to open is the name of the file, and the second
argument is a mode.
• The open function supports the following modes:
• 'r' opens the file for reading; raise an exception, if the file does not exist or the user of the
program does not have adequate permissions to open the file
• 'w' opens the file for writing; creates a new file; any pre-existing data in the file
will be lost
• 'a' opens the file to append data to it; new data will be appended
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 561
UNIVERSITY OF CALCUTTA
File Objects
• Once have a file object capable of writing (opened with 'w'
or 'a’), save data to the file associated with that file object
using the write method.
• For a file object named f, the statement [Link]('data')
f = open('[Link]’, ‘w’) f = open('[Link]', 'w') f = open('[Link]', 'r')
[Link]('data’) [Link]('data\n')
[Link]('compute’) [Link]('compute\n') for line in f:
[Link]('process’) [Link]('process\n’) print([Link]())
[Link]() [Link]() [Link]()
remove the
trailing newline
('\n') character
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 562
UNIVERSITY OF CALCUTTA
File Objects
• Every call to the open function should have a
corresponding call to the file object’s close method.
with open('[Link]') as f: # f is a file object
for line in f: # Read each line as text
print([Link]()) # Remove trailing newline character
# No need to close the file
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 563
UNIVERSITY OF CALCUTTA
File Objects
"""
def main():
Uses Python's file class to store data to and retrieve data from a text file.
""" Interactive function that allows the user to
"""
create or consume files of numbers. """
def load_data(filename):
done = False
""" Print the elements stored in the text file named filename. """
while not done:
# Open file to read
cmd = input('S)ave L)oad Q)uit: ')
with open(filename) as f: # f is a file object
if cmd == 'S' or cmd == 's':
for line in f: # Read each line as text
store_data(input('Enter file name:'))
print(int(line)) # Convert to integer and append to the list
elif cmd == 'L' or cmd == 'l':
load_data(input('Enter filename:'))
def store_data(filename):
elif cmd == 'Q' or cmd == 'q':
""" Allows the user to store data to the text file named filename. """
done = True
with open(filename, 'w') as f: # f is a file object
number = 0
if __name__ == '__main__':
while number != 999: # Loop until user provides magic number
main()
number = int(input('Please enter number (999 quits):'))
if number != 999:
[Link](str(number) + '\n') # Convert integer to string to save
else: DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 564
break # Exit loop UNIVERSITY OF CALCUTTA
Fraction Objects
• The fractions module provides the Fraction class
• Fraction objects model mathematical rational numbers; that is, the ratio of two integers.
• The statement,
• f1 = Fraction(3, 4)
• Creates a Fraction object and assigns the variable f1 to the object.
• The expression Fraction(3, 4) calls a class constructor.
• Class constructors allow clients to supply data used in the formation of a new object.
Two attributes, __add__, addition: f1.__add__(f2) is equivalent to f1+f2
numerator and
__mul__, multiplication: f.__mul__(g) is equivalent to f * g
denominator
__eq__, relational quality: f.__eq__(g) is equivalent to f == g
__gt__, greater than: f.__gt__(g) is equivalent to f > g
__sub__, subtraction: f.__sub__(g) is equivalent to f – g
__neg__, unary minus: f.__neg__() is equivalent to -f
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 565
UNIVERSITY OF CALCUTTA
Operator Overloading
• operator overloading: You can define functions so that
Python's built-in operators can be used with your class.
• See also: [Link]
Operator Class Method Operator Class Method
- __neg__(self, other) == __eq__(self, other)
+ __pos__(self, other) != __ne__(self, other)
* __mul__(self, other) < __lt__(self, other)
/ __truediv__(self, other) > __gt__(self, other)
Unary Operators <= __le__(self, other)
- __neg__(self) >= __ge__(self, other)
+ __pos__(self)
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 566
UNIVERSITY OF CALCUTTA
Problem Statement:
• Create a Student Management System that allows:
• Adding student details (name, roll, marks).
• Viewing details of each student.
• Calculating grades based on marks.
• Displaying all students' data.
• Demonstrating inheritance by creating a subclass for
GraduateStudent.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 567
UNIVERSITY OF CALCUTTA
Problem Statement:
Algorithm
[Link]
[Link] a base class Student with:
•Attributes: name, roll, marks.
•Methods: __init__(), calculate_grade(), display_info().
[Link] a subclass GraduateStudent inheriting from Student.
•Additional Attribute: thesis_title.
•Override the display_info() method to include thesis details.
[Link] student objects and demonstrate method calls.
[Link] polymorphism using overridden methods.
[Link]
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 568
UNIVERSITY OF CALCUTTA
Problem Statement:
Algorithm
[Link]
[Link] a base class Student with:
•Attributes: name, roll, marks.
•Methods: __init__(), calculate_grade(), display_info().
[Link] a subclass GraduateStudent inheriting from Student.
•Additional Attribute: thesis_title.
•Override the display_info() method to include thesis details.
[Link] student objects and demonstrate method calls.
[Link] polymorphism using overridden methods.
[Link]
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 569
UNIVERSITY OF CALCUTTA
File Objects
# Base Class
class Student:
def __init__(self, name, roll, marks):
[Link] = name # Instance variable
[Link] = roll # Instance variable
[Link] = marks # Instance variable
def calculate_grade(self):
if [Link] >= 90:
return 'A+'
elif [Link] >= 80:
return 'A'
elif [Link] >= 70:
return 'B'
elif [Link] >= 60:
return 'C'
else:
return 'F'
def display_info(self):
print(f"\nName: {[Link]}")
print(f"Roll Number: {[Link]}")
EVEN
print(f"Marks: {[Link]}")
SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
570
print(f"Grade: {self.calculate_grade()}")
UNIVERSITY OF CALCUTTA
File Objects
# Subclass (Inheritance Example)
class GraduateStudent(Student):
def __init__(self, name, roll, marks, thesis_title):
super().__init__(name, roll, marks) # Inheriting attributes from Student
self.thesis_title = thesis_title # New attribute for GraduateStudent
# Method Overriding
def display_info(self):
super().display_info() # Calling the parent class method
print(f"Thesis Title: {self.thesis_title}")
# Creating Objects (Encapsulation)
student1 = Student("Ravi", 101, 85)
student2 = GraduateStudent("Priya", 102, 92, "Machine Learning in Healthcare")
# Displaying Information (Polymorphism)
student1.display_info()
student2.display_info()
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 571
UNIVERSITY OF CALCUTTA
Exercise
• Problem 1: Library Management System (Encapsulation, Inheritance)
• Problem Statement:
• Create a base class Book with attributes:
• title, author, price.
• Create a subclass LibraryBook that adds:
• book_id, availability_status.
• Implement methods to:
• Display book details.
• Check availability status.
• Borrow a book (changes availability status).
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 572
UNIVERSITY OF CALCUTTA
Special Class Methods
• In addition to normal class methods, there are a number of
special methods which Python classes can define.
• Instead of being called directly by our code (like normal
methods), special methods are called for you by Python in
particular circumstances or when specific syntax is used.
• We can get and set items with a syntax that doesn't include
explicitly invoking methods.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 575
UNIVERSITY OF CALCUTTA
Example: Create Bank Acc Object
# Python program to create Bankaccount class def withdraw(self):
# with both a deposit() and a withdraw() amount = float(input("Enter amount to be
Withdrawn: "))
function
if [Link]>=amount:
class Bank_Account: [Link]-=amount
def __init__(self): print("\n You Withdrew:", amount)
[Link]=0 else:
print("Hello!!! Welcome to the Deposit print("\n Insufficient balance ")
& Withdrawal Machine")
def display(self):
print("\n Net Available
def deposit(self): Balance=",[Link])
amount=float(input("Enter amount to be
Deposited: ")) # Driver code
[Link] += amount
# creating an object of class
print("\n Amount Deposited:",amount) s = Bank_Account()
# Calling functions with that class object
[Link]()
[Link]()
DEPARTMENT OF APPLIED PHYSICS,
[Link]()
EVEN SEMESTER 576
UNIVERSITY OF CALCUTTA
Handling Exception
• Python has its own exception handle routine
• But programmer can write its own also by using try-except
statement
try: $ python try_except.py
text = input('Enter something --> ‘) Enter something --> # Press ctrl-d
except EOFError: Why did you do an EOF on me?
$ python try_except.py
print('Why did you do an EOF on me?’)
Enter something --> # Press ctrl-c
except KeyboardInterrupt:
You cancelled the operation.
print('You cancelled the operation.’)
$ python try_except.py
else:
Enter something --> no exceptions
print('You entered {0}'.format(text))
You entered no exceptions
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 577
UNIVERSITY OF CALCUTTA
Generating Exceptions
raise ExceptionType("message")
• useful when the client uses your object improperly
• types: ArithmeticError, AssertionError, IndexError, NameError,
SyntaxError, TypeError, ValueError
• Example:
class BankAccount:
...
def deposit(self, amount):
if amount < 0:
raise ValueError("negative amount")
...
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 578
UNIVERSITY OF CALCUTTA
Handling Exception
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 579
UNIVERSITY OF CALCUTTA
Raising Exceptions #!/usr/bin/python
• Raise exceptions using # Filename: [Link]
class ShortInputException(Exception):
the raise statement by '''A user-defined exception class.'‘’
providing the name of
def __init__(self, length, atleast):
Exception.__init__(self)
the error/exception
[Link] = length
[Link] = atleast
try:
text = input('Enter something --> ‘)
if len(text) < 3:
raise ShortInputException(len(text), 3)
# Other work can continue as usual here
except EOFError:
$ python [Link]
print('Why did you do an EOF on me?’)
Enter something --> a
except ShortInputException as ex:
ShortInputException: The input was 1 long, expected at least
3 print('ShortInputException: The input was {0}
long, expected at least {1}’\
.format([Link], [Link]))
$ python [Link]
else:
Enter something --> abc
print('No exception was raised.')
No exception was raised.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 580
UNIVERSITY OF CALCUTTA
Custom Types
• A software object generally bundles together data (instance
variables) and functionality (methods)
• The instance variables and methods of an object comprise
its members.
• The class of an object defines the object’s basic structure
and capabilities.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 581
UNIVERSITY OF CALCUTTA
Custom Types
• Define a custom Circle class in Python from which we can
create Circle instances (objects)
Clients should be able to create a Circle object with a specified center
point (a tuple of two numbers) and radius. definitions appear within
the block of a class
An attempt to create a circle with a negative radius should produce a definition they are
ValueError exception. method definitions
Clients can determine a Circle object’s radius via a get_radius method.
Clients can determine a Circle object’s center via a get_center method.
Clients can reposition the circle via a move method.
Clients can increase the circle’s radius by one unit via a grow method.
Clients can decrease the circle’s radius by one unit via a shrink method.
At no time should the circle’s radius fall below zero
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 582
UNIVERSITY OF CALCUTTA
Custom Types
• Define a custom Circle class in Python from which we can
create Circle instances (objects)
__init__: The special name of all constructors in Python classes is __init__. It must create and initialize the
center and radius instance variables, and it must detect an attempt to make a Circle object with a
negative radius. The client code must supply a center (a tuple consisting of two numbers) and a radius.
get_radius: This method simply returns the value of the radius instance variable. This method accepts
no parameters.
get_center: This method simply returns the value of the center instance variable. This method accepts
no parameters.
get_area: This method computes and returns the circle object’s area. This method accepts no
parameters.
get_circumference: This method computes and returns the circumference. This method accepts no
parameters.
move: This method repositions the Circle object’s center. The client must provide a tuple consisting of two numbers. This
tuple represents the new coordinates of the object’s center.
grow: This method increases the Circle object’s radius by one unit. This method accepts no parameters.
shrink: If the Circle object’s radius is greater than zero, this method decreases its radius by one unit. This method does
not change the radius if the radius is zero before the call. This method accepts no parameters.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 583
UNIVERSITY OF CALCUTTA
Custom Types
• Define a custom Circle class in Python from which we can
create Circle instances (objects)
__init__: The special name of all constructors in Python classes is __init__. It must create and initialize the
center and radius instance variables, and it must detect an attempt to make a Circle object with a
negative radius. The client code must supply a center (a tuple consisting of two numbers) and a radius.
get_radius: This method simply returns the value of the radius instance variable. This method accepts
no parameters.
get_center: This method simply returns the value of the center instance variable. This method accepts
no parameters.
get_area: This method computes and returns the circle object’s area. This method accepts no
parameters.
get_circumference: This method computes and returns the circumference. This method accepts no
parameters.
move: This method repositions the Circle object’s center. The client must provide a tuple consisting of two numbers. This
tuple represents the new coordinates of the object’s center.
grow: This method increases the Circle object’s radius by one unit. This method accepts no parameters.
shrink: If the Circle object’s radius is greater than zero, this method decreases its radius by one unit. This method does
not change the radius if the radius is zero before the call. This method accepts no parameters.
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 584
UNIVERSITY OF CALCUTTA
Custom Types def get_circumference(self):
class Circle:
constructor initializes
the center and radius """ Compute and return the circumference of the circle """
""" Represents a geometric circle object """
instance variables of from math import pi
def __init__(self, center, radius):
the object with radius
""" Initalize the center's center and radius """ parameter is return 2*pi*[Link]
nonnegative def move(self, pt):
# Disallow a negative radius
if radius < 0:
instance variable """ Moves the enter of the circle to point pt """
names
raise ValueError('Negative radius') [Link] = pt
accessor methods, or
[Link] = center getters, as they give def grow(self):
clients access to see """ Increases the radius of the circle """
[Link] = radius
the state of an object
def get_radius(self): [Link] += 1
Mutator methods, or
""" Return the radius of the circle """ setters, because they def shrink(self):
return [Link] allow clients to modify """ Decreases the radius of the circle;
the state of an object
def get_center(self): does not affect a circle with radius zero """
""" Return the coordinatess of the center """ if [Link] > 0:
return [Link] [Link] -= 1
def get_area(self):
c1 = Circle((2, 4), 5)
""" Compute and return the area of the circle """
c2 = Circle((0, 0), 1)
from math import pi
print(c1.get_radius())
return pi*[Link]*[Link]
DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 585
UNIVERSITY OF CALCUTTA print(c2.get_radius())
Practice Program
Example: Values and Variables Concepts Covered: Assigning and manipulating values
using variables.
Algorithm Python Code
• Start # Step 2: Declare variables
age = 25 # Integer
• Declare variables with different data types (integer, price = 99.99 # Float
float, string). name = "Alice" # String
• Perform arithmetic operations.
# Step 3: Perform operations
• Print the values with proper formatting. age_after_5_years = age + 5
• End price_discounted = price * 0.9
# Step 4: Print output
print("Name:", name)
print("Age after 5 years:", age_after_5_years)
print("Discounted price:", price_discounted)
Example: Swap Two Variables Without Using a Temporary Concepts Covered: Variables, Arithmetic Operators
Variable
Algorithm Python Code
• Start # Step 2: Take input
a = int(input("Enter first number: "))
• Take two numbers as input (a and b). b = int(input("Enter second number: "))
• Swap values using arithmetic operations (+ and -).
• Print the swapped values. # Step 3: Swap using arithmetic operations
a = a + b
• End b = a - b
a = a - b
# Step 4: Print swapped values
print("After swapping: a =", a, ", b =", b)
Example: Convert Temperature from Celsius to Concepts Covered: Variables, Arithmetic Operators,
Fahrenheit Data Types
Algorithm Python Code
• Start
• Take temperature in Celsius as input. celsius = float(input("Enter temperature in
Celsius: "))
• Use the formula:
• 𝐹 = ( 𝐶 × 9 / 5 ) + 32 fahrenheit = (celsius * 9/5) + 32
• Print the Fahrenheit value.
print("Temperature in Fahrenheit:", fahrenheit)
• End
List Operations Concepts Covered: Creating, modifying, and accessing
lists.
Algorithm Python Code
• Start
# Step 2: Create a list
• Create a list with multiple values. fruits = ["Apple", "Banana", "Cherry"]
• Append a new item to the list.
• Remove an item. # Step 3: Modify list
[Link]("Mango") # Add item
• Sort the list and print the updated values. [Link]("Banana") # Remove item
• End [Link]() # Sort list
# Step 5: Print the list
print("Updated list:", fruits)
Tuple Operations Concepts Covered: Immutable data structures and
indexing.
Algorithm Python Code
• Start
• Create a tuple with values. # Step 2: Create a tuple
colors = ("Red", "Green", "Blue")
• Access elements using indexing.
• Convert tuple to a list and modify it. # Step 3: Access elements
• End print("First color:", colors[0])
# Step 4: Convert to list and modify
colors_list = list(colors)
colors_list.append("Yellow")
new_tuple = tuple(colors_list)
print("Modified tuple:", new_tuple)
Dictionary Operations Concepts Covered: Creating and modifying key-value
pairs.
Algorithm Python Code
• Start
# Step 2: Create dictionary
• Create a dictionary with key-value pairs.
student = {"name": "Rohan", "age": 20, "course":
• Access a value using a key. "Math"}
• Add a new key-value pair.
• End # Step 3: Access value
print("Student Name:", student["name"])
# Step 4: Add a new key-value pair
student["grade"] = "A"
print("Updated Dictionary:", student)
Set Operations Concepts Covered: Unique values and set operations.
Algorithm Python Code
• Start
# Step 2: Create a set
• Create a set with unique values. set1 = {1, 2, 3, 4}
• Add a new item. set2 = {3, 4, 5, 6}
• Perform set operations (union, intersection).
# Step 3: Modify set
• End [Link](5)
# Step 4: Perform set operations
union_set = [Link](set2)
intersection_set = [Link](set2)
print("Union:", union_set)
print("Intersection:", intersection_set)
Operators Example Concepts Covered: Arithmetic, logical, and comparison
operators.
Algorithm Python Code
• Start
a = 10
• Take two numbers.
b = 5
• Perform arithmetic, comparison, and logical
operations. # Arithmetic Operators
• Print results. print("Addition:", a + b)
print("Multiplication:", a * b)
• End
# Comparison Operators
print("Is a greater than b?", a > b)
# Logical Operators
print("Both are non-zero?", a > 0 and b > 0)
Print Formatting Methods Concepts Covered: Formatting output using format(), f-strings.
Algorithm Python Code
• Start
name = "Priya"
• Use different print formatting methods.
age = 25
• Print output using format() and f-strings.
• End # Using format()
print("My name is {} and I am {} years
old.".format(name, age))
# Using f-strings
print(f"My name is {name} and I am {age} years
old.")
Algorithm Python Code
• Start
name = "Priya"
• Use f-strings (f"") to insert variables directly. marks = 95.5
• Print formatted output.
• End print(f"Student: {name}, Marks: {marks}")
print(f"Next year, {name} will have {marks + 5}
marks.")
Algorithm Python Code
• Start
• Use % formatting to insert values. num = 7
pi = 3.14159
• Print formatted output.
• End print("Integer: %d" % num) # %d for integer
print("Float: %.2f" % pi) # %.2f limits to 2
decimal places
Algorithm Python Code
• Start
• Use :.nf inside f-strings to control decimal places. pi = 3.1415926535
• Print formatted output. print(f"Rounded to 2 decimals: {pi:.2f}")
• End print(f"Rounded to 4 decimals: {pi:.4f}")
Algorithm Python Code
• Start
• Use <, >, and ^ inside f-strings for alignment. text = "Python"
• Print formatted output. print(f"Left aligned: {text:<10}") # Left-
• End aligned
print(f"Right aligned: {text:>10}") # Right-
aligned
print(f"Center aligned: {text:^10}") # Center-
aligned
Algorithm Python Code
• Start
• Use sep="delimiter" to change default space # Using sep
print("Apple", "Banana", "Cherry", sep=" | ")
separation.
• Use end="custom_end" to change newline # Using end
behavior. print("Hello", end="... ")
• End print("World!")
List & Dictionary Comprehensions Concepts Covered: Efficient list and dictionary creation.
Algorithm Python Code
• Start
# List Comprehension
• Create a list of squares using list comprehension.
squares = [x ** 2 for x in range(1, 6)]
• Create a dictionary of squares using dictionary print("List of Squares:", squares)
comprehension.
# Dictionary Comprehension
• End squares_dict = {x: x ** 2 for x in range(1, 6)}
print("Dictionary of Squares:", squares_dict)
Nested List Comprehension: Matrix Transposition Concepts Covered: Handling 2D lists.
Algorithm Python Code
• Start
matrix = [
• Define a 3x3 matrix. [1, 2, 3],
• Transpose the matrix using nested list [4, 5, 6],
comprehension. [7, 8, 9]
]
• Print the new matrix.
• End # Transpose using nested list comprehension
transposed_matrix = [[row[i] for row in matrix]
for i in range(len(matrix[0]))]
print("Transposed Matrix:", transposed_matrix)
Example: Create a List of Even Numbers Using List Concepts Covered: List Comprehension
Comprehension
Algorithm Python Code
• Start
even_numbers = [num for num in range(1, 21) if
• Use a list comprehension to generate even
num % 2 == 0]
numbers from 1 to 20. print("Even numbers:", even_numbers)
• Print the list.
• End
Dictionary Comprehension: Square of Numbers Concepts Covered: Dictionary comprehension.
Algorithm Python Code
• Start
squares_dict = {x: x ** 2 for x in range(1, 6)}
• Create a dictionary where keys are numbers 1 to 5 print("Dictionary of squares:", squares_dict)
and values are their squares.
• Print the dictionary.
• End
Dictionary Comprehension: Word Length Mapping Concepts Covered: Working with strings and dictionary
comprehension.
Algorithm Python Code
• Start
• Create a dictionary where keys are words and words = ["apple", "banana", "cherry"]
word_lengths = {word: len(word) for word in
values are their lengths. words}
• Print the dictionary.
• End print("Word length mapping:", word_lengths)
Dictionary Comprehension: Swap Keys and Values Concepts Covered: Reversing dictionaries.
Algorithm Python Code
• Start
• Create a dictionary with some key-value pairs. original_dict = {"a": 1, "b": 2, "c": 3}
swapped_dict = {v: k for k, v in
• Swap keys and values using dictionary original_dict.items()}
comprehension.
• Print the new dictionary. print("Swapped dictionary:", swapped_dict)
• End
Combining Multiple Comprehensions Concepts Covered: List, dictionary, and set
comprehension together.
Algorithm Python Code
• Start
• Generate a list of squares. # List of squares
squares = [x**2 for x in range(1, 6)]
• Convert the list into a dictionary with values as
cubes. # Dictionary with cubes
• Extract unique values using a set comprehension. cubes_dict = {x: x**3 for x in squares}
• End # Extract unique values using set comprehension
unique_values = {v for v in cubes_dict.values()}
print("Squares:", squares)
print("Cubes Dictionary:", cubes_dict)
print("Unique Values:", unique_values)
Problem Statement: Create a Python program to manage
student records, including:
Algorithm Python Code
• Start
# Step 2: Create an empty list to store student
• Create an empty list to store student records. records
• Take multiple student inputs using a loop. students = []
• Store name, age, and marks in a dictionary inside a
# Step 3: Define subjects as a set
list. subjects = {"Math", "Science", "English"}
• Use operators to calculate total and percentage.
• Find the student with the highest marks using # Step 4: Take input for multiple students
num_students = int(input("Enter number of
max().
students: "))
• Use a set to store unique subjects.
• Sort student names alphabetically. for _ in range(num_students):
name = input("Enter student name: ")
• Display results using formatted printing.
age = int(input("Enter age: "))
• End
# Taking marks as dictionary inside list
marks = {subject: int(input(f"Enter marks
for {subject}: ")) for subject in subjects}
# Step 5: Calculate total and percentage
total_marks = sum([Link]())
percentage = total_marks / len(subjects) #
Assuming equal weight for each subject
# Store student details in a dictionary
student = {
"name": name,
"age": age,
"marks": marks,
"total": total_marks,
"percentage": percentage
}
[Link](student)
# Step 6: Find the student with the highest marks
using max()
highest_percentage = max([student["percentage"]
for student in students])
topper = [student for student in students if
student["percentage"] == highest_percentage][0]
# Step 7: Use set comprehension to store unique
subjects
unique_subjects = {sub for sub in subjects}
# Step 8: Sort student names alphabetically
sorted_students = sorted([student["name"] for
student in students])
# Step 9: Display student details with formatted
output
print("\n--- Student Records ---")
for student in students:
print(f"\nName: {student['name']:10} Age:
{student['age']:3} Total: {student['total']:3}
Percentage: {student['percentage']:.2f}%")
# Display the topper
print("\n Topper Details ")
print(f" Name: {topper['name']} Percentage:
{topper['percentage']:.2f}%")
# Display unique subjects and sorted names
print("\nUnique Subjects:", unique_subjects)
print("Sorted Student Names:", sorted_students)
Code for Python 3.x
Operation on list
Python has a set of built-in methods that you can use on dictionaries.
A dictionary is a collection which is ordered, changeable and does not allow duplicates. As of
Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
Method Description Syntax
clear() Removes all the elements from the [Link]()
dictionary
copy() Returns a copy of the dictionary [Link]()
fromkeys() Returns a dictionary with the specified [Link](keys, value)
keys and value
get() Returns the value of the specified key [Link](keyname, value)
items() Returns a list containing a tuple for [Link]()
each key value pair
keys() Returns a list containing the [Link]()
dictionary's keys
pop() Removes the element with the [Link](keyname,
specified key defaultvalue)
popitem() Removes the last inserted key-value [Link]()
pair
setdefault() Returns the value of the specified key. [Link](keyname,
If the key does not exist: insert the value)
key, with the specified value
Code for Python 3.x
update() Updates the dictionary with the [Link](iterable)
specified key-value pairs
value() Returns a list of all the values in the [Link]()
dictionary
1) Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
2) Get the value of the "model" key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
x = [Link]("model") # Using get() function
x = [Link]() # print list of keys
3) Add a new item to the original dictionary, and see that the keys list gets updated as
well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
4) Update the "year" of the car by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
Code for Python 3.x
"year": 1964
}
[Link]({"year": 2020}) # Using update
thisdict["year"] = 2018
5) Adding an item to the dictionary is done by using a new index key and assigning a
value to it:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
[Link]({"color": "red"}) # Using update function
6) Remove an item:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]("model")
print(thisdict)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]() # popitem() method removes the last inserted
item
print(thisdict)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
del thisdict # delete whole dictionary
7) Print the keys and values using for loop
thisdict = {
Code for Python 3.x
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
for x in thisdict:
print(thisdict[x])
for x, y in [Link]():
print(x, y)
8) Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Ram",
"year" : 2004
},
"child2" : {
"name" : "Shayam",
"year" : 2007
},
"child3" : {
"name" : "Jadu",
"year" : 2011
}
}
Code for Python 3.x
Operation on list
Python has a set of built-in methods that you can use on lists/arrays.
Method Description Syntax
append() Adds an element at the end of the list [Link](elmnt)
clear() Removes all the elements from the list [Link]()
copy() Returns a copy of the list [Link]()
count() Returns the number of elements with the specified [Link](value)
value
extend() Add the elements of a list (or any iterable), to the [Link](iterable)
end of the current list
index() Returns the index of the first element with the [Link](elmnt)
specified value
insert() Adds an element at the specified position [Link](pos, elmnt)
pop() Removes the element at the specified position [Link](pos)
remove() Removes the first item with the specified value [Link](elmnt)
reverse() Reverses the order of the list [Link]()
sort() Sorts the list [Link](reverse=True|False,
key=myFunc)
Code for Python 3.x
1) Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
2) Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
3) Using list() constructor
thislist = list(("apple", "banana", "cherry")) # note the
double round-brackets
print(thislist)
4) Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
5) Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
6) Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
[Link]("orange")
print(thislist)
7) Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
[Link](1, "orange")
print(thislist)
8) Add the elements of tropical to this list
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
[Link](tropical)
print(thislist)
9) Remove an item:
thislist = ["apple", "banana", "cherry"]
[Link]("banana")
print(thislist)
thislist = ["apple", "banana", "cherry"]
[Link](1)
print(thislist)
Code for Python 3.x
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
10) Clear the list content:
thislist = ["apple", "banana", "cherry"]
[Link]()
print(thislist)
11) Create a list of squares:
squares = []
for x in range(10):
[Link](x**2)
12) Program to check if the Given List is in Ascending Order or Not
list1 = [1, 2, 3, 5, 4, 8, 7, 9]
temp_list = list1[:]
[Link]()
if temp_list == list1:
print("Given List is in Ascending Order")
else:
print("Given List is not in Ascending Order")
13) Program to Find Even Numbers from a List
list2 = [2, 3, 7, 5, 10, 17, 12, 4, 1, 13]
for i in list2:
if i % 2 == 0:
print(i)
14) Program to Subtract a List from Another List
a = [1, 2, 3, 5]
b = [1, 2]
l1 = []
for i in a:
if i not in b:
Code for Python 3.x
[Link](i)
print(l1)
15) Program to print duplicates from a list of integers:
from collections import Counter
l1 = [1,2,1,2,3,4,5,1,1,2,5,6,7,8,9,9]
d = Counter(l1)
print(d)
new_list = list([item for item in d if d[item]>1])
print(new_list)
16) Given a List, extract all elements whose frequency is greater than K.
# initializing list
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
# printing string
print("The original list : " + str(test_list))
# initializing K
K = 2
res = []
for i in test_list:
# using count() to get count of elements
freq = test_list.count(i)
# checking if not already entered in results
if freq > K and i not in res:
[Link](i)
# printing results
print("The required elements : " + str(res))
Code for Python 3.x
Operation on tuple
Python has a set of built-in methods that you can use on tuple.
Method Description Syntax
count() Returns the number of times a specified value [Link](value)
occurs in a tuple
index() Searches the tuple for a specified value and [Link](value)
returns the position of where it was found
1) Create a tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
2) Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
3) Using tuple() constructor:
thistuple = tuple(("apple", "banana", "cherry")) # note the double
round-brackets
print(thistuple)
4) Print the second item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1]))
5) Extract the values back into variables: unpacking
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
6) Iterate through the items and print the values:
a)
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
Code for Python 3.x
b)
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])
7) Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
8) Return the number of times the value 5 appears in the tuple:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = [Link](5)
print(x)
9) Search for the first occurrence of the value 8, and return its position:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = [Link](8)
print(x)
10) Test if tuple is distinct:
# initialize tuple
test_tup = (1, 4, 5, 6, 1, 4)
# printing original tuple
print("The original tuple is : " + str(test_tup))
# Test if tuple is distinct
# Using loop
res = True
temp = set()
for ele in test_tup:
if ele in temp:
res = False
break
[Link](ele)
# printing result
Code for Python 3.x
print("Is tuple distinct ? : " + str(res))
11) Adding Tuple to List and vice – versa
# initializing list
test_list = [5, 6, 7]
# printing original list
print("The original list is : " + str(test_list))
# initializing tuple
test_tup = (9, 10)
# Adding Tuple to List and vice - versa
# Using tuple(), data type conversion [tuple + list]
res = tuple(list(test_tup) + test_list)
# printing result
print("The container after addition : " + str(res))