0% found this document useful (0 votes)
5 views33 pages

Python Small

The document outlines a computer programming course focusing on Visual Basic and Python, detailing course outcomes and modules. Students will learn fundamental programming concepts, object-oriented programming, and develop applications using various programming languages and libraries. The syllabus includes hands-on activities and examples to reinforce learning in areas such as GUI development, file handling, and machine learning.

Uploaded by

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

Python Small

The document outlines a computer programming course focusing on Visual Basic and Python, detailing course outcomes and modules. Students will learn fundamental programming concepts, object-oriented programming, and develop applications using various programming languages and libraries. The syllabus includes hands-on activities and examples to reinforce learning in areas such as GUI development, file handling, and machine learning.

Uploaded by

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

Course Outcomes Syllabus References

• At the end of this course, students will be able to learn about • 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
COMPUTER PROGRAMMING • CO1: Identify fundamental programming concepts, data structures, and file
handling techniques used in software development.
handling and data handling.
• Module 2: Visual basic Programming (10 hour)
PCC-EE 405 • CO2: Explain the principles of object-oriented programming, event-driven • 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 -
programming, and their applications in GUI and system programming. like reading and writing Excel file, Excel plotting, interfacing of USB/COM ports, development of
Nirmal Murmu • CO3: Develop basic to intermediate-level applications using programming
net based application in client/server mode.
Department of Applied Physics languages and libraries for file manipulation, data handling, and user interaction. • Module 3: Introduction to Python libraries (10 hour)
University of Calcutta • Python Types, Expressions, Strings, Lists, Tuples, Python memory model (names, mutable and
• CO4: Compare and evaluate different programming approaches, paradigms, and immutable values), List operations, Regular Expressions, Python Functions, Abstract Data types,
tools for solving computational problems effectively. Classes and Objects in Python, Exception handling, Handling files, Python
Scientific/Statistical/Machine Learning Libraries.
• CO5: Assess the efficiency, scalability, and usability of developed applications, • Module 4: Python programming (12 hour)
optimizing code performance and debugging issues effectively. • 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, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER 2 EVEN SEMESTER 3 EVEN SEMESTER 4
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

%s → String
Lecture Plan Lecture Plan Print Formatting Methods %d → Integer Using %% to Print a Literal %
① • Using % Operator %f → Floating-point
Lecture No. Topic Key Concepts Lecture No. Topic Key Concepts placeholder
name = "Alice" percentage = 85
Variables, Data Types, and Python types, expressions, Object-Oriented Programming Classes, objects, inheritance, ⑨ 1)
1 1 age = 25 print("Your score is %d%%." % percentage)
Operators operators, type conversions (OOPs) in Python polymorphism
Lists, tuples, slicing, loops (for, Multi-threading and Advanced File Threading basics, file operations, print("My name is %s and I am %d years old." % (name, age)) 'format
2 Arrays and Flow Control 2 "1070 " % in o/P specifier → lid/int)
while), conditional statements Handling concurrent programming 1. s (Str)
• Using .format()
3 Methods and Functions
Defining functions, arguments,
return values, recursion
3
Timers, Event Handling, and GUI
Development
Timer-based operations, GUI
programming using Tkinter/PyQt
⑪ print("My name is {} and I am {} years old.".format(name,
Alice.
(A1) Your score is 851.. → 1. f (twats
Reading/writing files, handling CSV, Using OpenCV for image age))
4 File Handling Camera Interfacing and Data
JSON 4
Acquisition
processing, real-time data (25) The advantage of using {) in place of
5
Introduction to Scientific NumPy, Pandas, Matplotlib for data acquisition • Using f-strings
Libraries processing Machine Learning and AI Basics of Scikit-learn, TensorFlow, % is that dont have to specify the format
5 print(f"My name is {name} and I am {age} years old.") 1. I am/ /years old".
Applications AI-driven applications
name: my' → Print ( "My name is format (name, age"))
Final Project Discussion and Developing real-world
DEPARTMENT OF APPLIED PHYSICS,
6
Implementation DEPARTMENT OF APPLIED PHYSICS,
applications, project review
pi = 3.1415926535
DEPARTMENT OF APPLIED PHYSICS,
age: 21 DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 5 EVEN SEMESTER 6 EVEN SEMESTER 116 EVEN SEMESTER 117
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA print(f"Rounded to 2 decimals: {pi:.2f}")
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Format Specifiers for % Operator Floating-Point Formatting and %[Link] Aligning Output and Debugging Errors Debugging Exercise
Specifie
Data Type Example
r • Formatting Floats with Precision • Right-Aligned Numbers (%5.2f) • Find the Error:
"Hello %s" % "World" → "Hello num1 = 1.2
%s String pi = 3.14159
World" num2 = 12.345
print("Value of pi: %.2f" % pi) # Rounded to 2 decimal
"I am %d years old" % 25 → "I am x = 10
%d Integer places num3 = 123.4567
25 years old" y = "5"
3. 14
%f Floating-point
"Value: %f" % 3.1415 → "Value: print(x + y) Int + string not possible.
3.141500" .2f → Prints 2 decimal places print("%5.2f" % num1) → ...1.20
Float with n %5.2f → Aligns output with minimum width 5 print("%5.2f" % num2) → 1234
%.nf "%.2f" % 3.1415 → "3.14" [2 places after.] print("%5.2f" % num3) → 123.46
decimal places ↓
minmwidth:S 314 → O/P=..-314
%x Hexadecimal "Hex: %x" % 255 → "Hex: ff" (255),0→ (f) u Width:b ↳ 1 space allote d during Ofp minm width can be more than 5.
%o Octal "Oct: %o" % 8 → "Oct: (10"
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 118 EVEN SEMESTER 119 EVEN SEMESTER 120 EVEN SEMESTER 121
UNIVERSITY OF CALCUTTA ↳ Binary, 910005 UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
0

Hands-on Example Hands-on Example Hands-on Example Hands-on Example


• Example 1: Simple Arithmetic Operations
• Example 1: Simple Arithmetic Operations # Get two numbers from the user • Example 2: Even or Odd Number Checker • Example 2: Even or Odd Number Checker
• Objective: Perform basic arithmetic operations using user num1 = float(input("Enter first number: ")) • Objective: Determine if a given number is even or odd using • Objective: Determine if a given number is even or odd
conditional statements.
input. num2 = float(input("Enter second number: ")) using conditional statements.
# Perform basic arithmetic operations • Algorithm: # Get number input
• Concepts Used: Variables, Data Types, Input Handling, [Link]
sum_result = num1 + num2 num = int(input("Enter a number: "))
Operators [Link] the user to enter a number.
Algorithm: product = num1 * num2
[Link] the number in a variable (num).
difference = num1 - num2 # Check if even or odd
Start [Link] modulus operator (%) to check divisibility by 2:
f string
Prompt the user to enter two numbers. # Display results • If num % 2 == 0, print "Even number". if num % 2 == 0:
Store the numbers in variables (num1, num2). print(f"Sum: {sum_result:.2f}") } all upto [Link] • Else, print "Odd number". print(f"{num} is an even number.")
Compute the sum, product, and difference. print(f"Product: {product:.2f}") [Link] else:
Display the results with two decimal places. print(f"Difference: {difference:.2f}") print(f"{num} is an odd number.")
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER
End 122 EVEN SEMESTER 123 EVEN SEMESTER 124 EVEN SEMESTER 125
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
never giveadress
Topic Timeline Basic List Operations List Methods List Methods
Method Operation Syntax Example Method Operation Syntax Example
Topic Key Concepts Hands-on Activity
Defining, accessing elements, slicing, Create a list, perform slicing, • Objective: Perform operations on a list of numbers index() returns the index of [Link](element, start, end) animals = ['cat', 'dog',
'rabbit', 'horse’]
remove() removes the first [Link](element) [Link]('rat')
Lists & Tuples
appending, modifying append elements
the specified matching element J-l:[a. b. c. 449]
List Methods & Practice list operations & • Concepts Used: Lists, Indexing, Append, Remove, Slicing element index = 71
[Link]('dog')
(which is passed as 1- remove (c)
Operations
append(), remove(), sort(), index()
debugging ↳ d-index (value) an argument) from
the list
e: ca, b, c, c, d]
if-elif-else, nested conditions, and/or Build a number classification
Conditional Statements append() adds an item to the [Link](item) [Link](‘cow’)
operators program (positive/negative/zero) count() returns the number [Link](element) numbers = [2, 3, 5, 2, 11,
Print even numbers, reverse a list end of the list of times the Je: [Link], and] 2, 7]
For & While Loops range(), enumerate(), iteration over lists # check the count of 2
using loops extend() adds all the [Link](iterable) [Link]([‘rat’,’lion specified element
Convert list of strings to uppercase ’]) appears in the list.
l-count (c): 3. count = [Link](2) =3
Loop Optimizations List comprehensions, zip(), map() elements of an ↳ Eat, dog, rabbit' horse, rat] ✓
using comprehension iterable (list, tuple, ' 'lion. pop() removes the item at [Link](index) [Link](1)
Error Handling in Loops & Try accessing an out-of-range string etc.) to the the given index
Lists
try-except, handling IndexError in lists
index & handle exception
I: (a, b,c, c, d, e)
end of the list. from the list and returned
Nested Loops & Practical
Iterating over nested lists, pattern printing Print a right-angled triangle pattern insert() inserts an element [Link](i, element) vowel = ['a', 'e', 'i', 'u] returns the removed l-pop(4) →
Use Cases
to the list at the [Link](3, 'o') item
Debugging loops & conditionals, common Solve a logical bug in loop
Debugging & Q&A specified index l-[[Link]
mistakes execution
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS, UNIVERSITY OF
CALCUTTA 126 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
UNIVERSITY OF CALCUTTA
127 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
UNIVERSITY OF CALCUTTA
↳ vowel: Eal.'es128'il.] EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
UNIVERSITY OF CALCUTTA
129

Example: Using .append(), .insert(), Example: Using .append(), .insert(), Example : Using .sort(), .reverse(), and
List Methods
Method Operation Syntax Example
and .remove() and .remove() .count()
reverse() reverses the [Link]() integer=[1,2,3,4,5]
[Link]() ↳[5,4, 3,211] • Objective: Show how to add and remove elements # Step 1: Create an empty list • Problem Statement:
elements of the list fruits = []
sort() sorts the elements [Link](key=..., reverse=...) vowels = ['e', 'a', 'u', 'o',
dynamically in a list. • Create a list of random numbers.
unde­ # Step 2: Append elements
• Concepts Used: .append(), .insert(), .remove()
'i’]
of a given list in a
rstand specific ascending sorted(iterable, /, *,
[Link]()
print('Sorted list:', vowels)
[Link]("Apple") • Sort the list in ascending order using .sort().
once
more.
or descending order key=None, reverse=False)
custom function
[Link](reverse=True)
print('Sorted list (in
• Problem Statement: [Link]("Banana")
[Link]("Cherry") • Reverse the list using .reverse().
using key Descending):', vowels)
• Create an empty list. → ["apple"." banana"," cherry") • Count the occurrences of a specific number.
copy() returns a shallow [Link]() prime_numbers = [2, 3, 5] print("List after appending:", fruits)
copy of the list
numbers = prime_numbers.copy()
↳ [213,5]
• Add three elements using .append().
# Step 3: Insert "Mango" at index 1
clear() removes all items [Link]() prime_numbers.clear()
from the list ↳ [] • Insert an element at index 1 using .insert(). [Link](1, "Mango")
print("List after inserting Mango at index 1:", fruits)
> del (list name) • Remove a specific element using .remove(). → ["apple",
Umango" " banana"," cherry")
print (list name) # Step 4: Remove "Banana"
↳ Name Emr. [Link]("Banana") a. mango" ." cherry")
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, print("List after removing DEPARTMENT
Banana:",OFfruits) → ["apple".
APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 130 EVEN SEMESTER 131 EVEN SEMESTER 132 EVEN SEMESTER 133
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Example : Using .sort(), .reverse(), and


Example: Sort the list using key Example: extend() vs append() Nested List
.count() * * Very Imp
# Step 1: Create a list of numbers
numbers = [3,
# take second element for sort
a1 = [1, 2]
• Support arbitrary nesting
- 7, 2,- 9, 7, 1,
- 7, 5] def takeSecond(elem): • Immediate application of this feature is to represent matrixes, or
a2 = [1, 2]
return elem[1]
print("Original list:", numbers) b = (3, 4) “multidimensional arrays”
# Step 2: Sort the list
# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# a1 = [1, 2, 3, 4] • List in a list >>> M = [[1, 2, 3], # A 3 × 3 matrix, as nested lists
[Link]() [Link](b)
print("Sorted list:", numbers)→ [1,213,517,719] print(a1) → ☐ i 2,314, 314) • E.g., [4, 5, 6], # Code can span lines if bracketed
[7, 8, 9]]
# sort list with key
[Link](key=takeSecond)
• >>> s = [1,2,3] >>> M
# Step 3: Reverse the sorted list # a2 = [1, 2, (3, 4)] • >>> t = [‘begin’, s, ‘end’][[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[Link]() [Link](b)- >>> M[1] # Get row 2
# print list
- → [1.2, (3.4)]
print(a2)
• >>> t
print("Reversed list:", numbers) → [9. 7. 7,5, 3,211] [4, 5, 6]
print('Sorted list:', random) • [‘begin’, [1, 2, 3], ‘end’] >>> M[1][2] # Get row 2, then get item 3 within the
# Step 4: Count occurrences of 7 • >>> t[1][1] row
count_7 = [Link](7) • 2 6
print("Number of times 7 appears:", count_7) → 2
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 134 EVEN SEMESTER 135 EVEN SEMESTER 136 EVEN SEMESTER 137
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

List Comprehensions List Comprehensions List Comprehensions List Comprehensions


• Way to build a new list by running an expression on each • Way to build a new list by running an expression on each squares = [] • Way to process structures like matrix
item in a sequence, one at a time, from left to right item in a sequence, one at a time, from left to right for num in range(1, 6): Interchangable
>>> M = [[1, 2, 3], # A 3 × 3 matrix, as nested lists
• Are coded in square brackets • Are coded in square brackets [Link](num ** 2) List COMPOE
called as hen81' ons [4, 5, 6], # Code can span lines if bracketed
[7, 8, 9]]
• Are composed of an expression and a looping construct • Are composed of an expression and a looping construct print(squares) >>> col2 = [row[1] for row in M] # Collect the items in column 2
that share a variable name that share a variable name >>> col2
>>> L = [] [2, 5, 8]
>>> for n in range(1,11):
squares = [num ** 2 for num in >>> M # The matrix is unchanged
new_list = [expression for item in iterable if condition] [Link](n) range(1, 6)] [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

print(squares)
The operation or >>> L = [n for n in range(1,101)] Give me row[1] for each row in
transformation Each element from The sequence List matrix M, in a new list
applied to each item. the iterable (e.g., A filter to include
of elements to Comprehensions
list, range, tuple).OF APPLIED only specific
DEPARTMENT iterate over.
PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER
UNIVERSITY OF CALCUTTA elements. 138 EVEN SEMESTER
UNIVERSITY OF CALCUTTA
139 EVEN SEMESTER
UNIVERSITY OF CALCUTTA
140 EVEN SEMESTER
UNIVERSITY OF CALCUTTA
141
List Comprehensions List Comprehensions List Comprehensions List Comprehensions
• Way to process structures like matrix • Way to process structures like matrix • Way to process structures like matrix • Way to process structures like matrix
>>> M = [[1, 2,
[4, 5,
[7, 8,
>>> [row[1] + 1
3], # A 3 × 3 matrix, as nested lists
6], # Code can span lines if bracketed
9]]
for row in M] # Add 1 to each item in column 2
>>> 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
y >>> 3 in [1, 2, 3] # Membership
True
>>> for x in [1, 2, 3]:
... print(x, end=' ') # Iteration
>>> res = [c * 4 for c in 'SPAM'] # List comprehensions
>>> res
['SSSS', 'PPPP', 'AAAA', 'MMMM']

[3, 6, 9] >>> diag ... >>> res = []


>>> [row[1] for row in M if row[1] % 2 == 0] # Filter out odd [1, 5, 9] 1 2 3 >>> for c in 'SPAM': # List comprehension equivalent
items ... [Link](c * 4)
[2, 8] ...
>>> res
['SSSS', 'PPPP', 'AAAA', 'MMMM']

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 142 EVEN SEMESTER 143 EVEN SEMESTER 144 EVEN SEMESTER 145
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Example : Filtering Even Numbers


Example : Creating a List of Squares Quick Quiz Tuples
from a List
squares = [] squares = [num ** 2 for num in numbers = [1, 2, 3, 4, 5, 6, 7, even_numbers = [num for num in • Name two ways to build a list containing five integer zeros. • What is a tuple?
for num in range(1, 6): range(1, 6)] 8] numbers if num % 2 == 0] •A tuple is an ordered collection which cannot
[Link](num ** 2) print("Squares:", squares) even_numbers = [] print("Even numbers:",
zeros_list = [0] * 5 zeros_list = [0 for _ in range(5)] be modified once it has been created.
even_numbers)
• In other words, it's a special array, a read-only array.
print("Squares:", squares) for num in numbers: print(zeros_list) print(zeros_list)
if num % 2 == 0: • How to make a tuple? In round brackets
even_numbers.append(num) • Name four operations that change a list object in place. • E.g.,
nums = [1, 2, 3] >>> t = ()
print("Even numbers:", [Link](4) >>> t = (1, 2, 3)
even_numbers) [Link]([4, 5]) >>> t = (1, )
>>> t = 1,
[Link](1, 2) >>> a = (1, 2, 3, 4, 5)
[Link](2) >>> print a[1] # 2

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 146 EVEN SEMESTER 147 EVEN SEMESTER 148 EVEN SEMESTER 149
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Tuples: Identify Difference Tuple Methods Operations in Tuple Tuple Operations


♂ If one element
>>> t = (1, ) >>> t = (1) • Python has two built-in methods that you can use on tuples • Indexing e.g., T[i] >>> T = ('cc', 'aa', 'dd', 'bb') >>> T = tuple(tmp) # Make a
>>> type (t) >>> type (t) • Slicing e.g., T[1:5] >>> tmp = list(T) # Make a list tuple from the list's items
<class 'tuple’> <class 'int'> • Concatenation e.g., T + T from a tuple's items >>> T
Method Operation Syntax E.g
• Repetition e.g., T * 5 >>> [Link]() # Sort the list ('aa', 'bb', 'cc', 'dd')
count() returns the number of times a [Link](value) thistuple = (1, 3, 7,

t = 0, 'Ni', 1.2, 3 specified value appears in the 8, 7, 5, 4, 6, 8, 5)


• Membership test e.g., ‘a’ in T >>> tmp >>> sorted(T) # Or use the
tuple
x = [Link](5) ['aa', 'bb', 'cc', 'dd'] sorted built-in, and save two
>>> type (t) index() finds the first occurrence of the [Link](value) x = [Link](8)
• Length e.g., len(T) steps
<class 'tuple’> specified value and raises an • Concatenate, repeat e.g., T1 + T2, T * 3 ['aa', 'bb', 'cc', 'dd']
exception if the value is not
found

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 150 EVEN SEMESTER 151 EVEN SEMESTER 152 EVEN SEMESTER 153
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

List can be changed


Tuple Operations Example : Tuple List vs. Tuple List vs. Tuple
>>> T = (1, [2, 3], 4) >>> T[1][0] = 'spam' # This • Define a Tuple for a Student Record • What are common characteristics? • What are differences?
>>> T[1] = 'spam' # This fails: works: can change mutables • student = (101, "Alice", 20, "Computer Science") • Both store arbitrary data objects • Tuple doesn’t allow modification
can't change tuple itself inside • print("Student Record:", student) • Both are of sequence data type • Tuple supports format strings
>>> T • Accessing Tuple Elements • Tuple supports variable length parameter in function call.
TypeError: object doesn't • Tuples slightly faster
support item assignment (1, ['spam', 3], 4) • print("Student Name:", student[1])
• Tuple’s size is fixed, it can be stored more compactly than lists which need
• print("Student Course:", student[3]) to over-allocate
Elements of tuple fixed
• Tuple Unpacking ** Revise • Tuple is stored in a single block of memory but list requires two block of
memory, (fixed size and variable size)
• roll, name, age, course = student
• The user is aware of what is inserted in the tuple
• print(f"Roll: {roll}, Name: {name}, Age: {age}, Course: {course}")

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 154 EVEN SEMESTER 155 EVEN SEMESTER 156 EVEN SEMESTER 157
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
List vs. Tuple Example: List vs Tuple Example: List vs Tuple Quick Quiz
Feature List Tuple • How can you determine how large a tuple is?
Mutability Can be modified Cannot be modified # Creating a list # Creating a tuple import sys import timeit my_tuple = (4, 5, 6, 7, 8)
size = len(my_tuple)
Performance Slower (more overhead) Faster (less overhead) fruits_list = ["Apple", "Banana", fruits_tuple = ("Apple", "Banana", print("Tuple size:", size)
~5
"Cherry"] "Cherry")
Memory Usage Takes more memory Takes less memory list_data = [1, 2, 3, 4, 5] list_time = [Link](stmt="[x
print("Original List:", fruits_list) • Write an expression that changes the first item in a tuple. (4, 5, 6)
Dynamic data (e.g., user input, Fixed data (e.g., database print("Original Tuple:", tuple_data = (1, 2, 3, 4, 5) for x in range(100000)]", should become (1, 5, 6) in the process
Use Cases fruits_tuple) number=100)
logs) records, config settings) old_tuple = (4, 5, 6)
# Modifying the list ~ (516) → (1) + (516)
Memory Usage Takes more memory Uses less memory print("List size:", tuple_time = new_tuple = (1,) + old_tuple[1:]
fruits_list[1] = "Mango" # Modifying the tuple [Link](list_data), "bytes") [Link](stmt="(x for x in print(new_tuple) ⇒ (1,5, 6)
Iteration Speed Slower due to mutability Faster since it’s fixed range(100000))", number=100)
print("Modified List:", fruits_list) fruits_tuple[1] = "Mango" ✗ Error print("Tuple size:", • What do you think is happening to X and Y when you type this
Requires dynamic memory [Link](tuple_data), "bytes") sequence?
Extra Processing Stored in a single block
allocation print("List execution time:", >>> X = 'spam' ✗ = eggs.
Modification No need to track list_time)
Overhead
Keeps track of changes
modifications
>>> Y = 'eggs' = spam
print("Tuple execution time:",
Caching (Interning) Not cached Small tuples are cached tuple_time) >>> X, Y = Y, X
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 158 EVEN SEMESTER 159 EVEN SEMESTER 160 EVEN SEMESTER 161
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Dictionaries Dictionaries Dictionaries Dictionary details


• Known as mappings • Contrast with list, • Dictionaries: curly brackets • Keys must be immutable:
• Collections of other objects, but they store objects by key instead of by relative
position • dictionaries as unordered collections • numbers, strings, tuples of immutables
d = { "foo" : 1, "bar" : 2 }
• Don’t maintain any reliable left-to-right order • items are stored and fetched by key, instead of by positional offset • these cannot be changed after creation
print d["bar"] # 2
• Accessed by key, not offset: referred to values some_dict = {} • reason is hashing (fast lookup technique)
• May be changed in-place and can grow and shrink on demand some_dict["foo"] = "yow!"
• Unordered collections of arbitrary objects • not lists or other dictionaries
• What is dictionary? print some_dict.keys() # ["foo"]
• Refer value through key; “associative arrays” • Variable-length, heterogeneous, and arbitrarily nestable: can • these types of objects can be changed "in place"
• Like an array indexed by a string grow and shrink, support nesting to any depth • no restrictions on values
• An unordered set of key: value pairs
• Values of any type; keys of almost any type
• Of the category “mutable mapping”: operations that depend on • Keys will be listed in arbitrary order
• {"name":"Guido", "age":43, ("hello","world"):1, a fixed positional order (e.g., concatenation, slicing) don’t make sense • again, because of hashing
42:"yes", "flag": ["red","white","blue"]}

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 162 EVEN SEMESTER 163 EVEN SEMESTER 164 EVEN SEMESTER 165
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Dictionary Operations Dictionary Methods Dictionary Methods Dictionary Methods


Operation Interpretation • Python has two built-in methods that you can use on Method Operation Syntax Example Method Operation Syntax Example
D = {} Empty dictionary dictionary get() returns the value for the specified
key if the key is in the dictionary
[Link](keyname,
value)
marks = {'Physics':67,
'Maths':87}
pop() removes the specified item
from the dictionary
[Link](key[,
default])
car = {
"brand": "Ford",
D = {'spam': 2, 'eggs': 3} Two-item dictionary Method Operation Syntax Example print([Link]('Physics "model": "Mustang",
D = {'food': {'ham': 1, 'egg': 2}} Nesting ’))
clear() removes all the elements from a [Link]() car = { "year": 1964
"brand": "Ford", print([Link](‘Chemist
D = dict(name='Bob', age=40) Alternative construction techniques: dictionary "model": "Mustang", ry’)) }
"year": 1964 print([Link](‘Chemist x = [Link]("model")
D['eggs'] Indexing by key } ry’, 55)) print(x)
'eggs' in D Membership: key present test [Link]()
items() method returns a view object that [Link]() marks = {'Physics':67, popitems() removes and returns the last [Link]() person = {'name':
len(D) Length: number of stored entries copy() returns a copy of the specified [Link]() x = [Link]()
'Maths':87} element (key, value) pair 'Phill', 'age': 22,
displays a list of dictionary's (key,
dictionary. print([Link]()) inserted into the dictionary. 'salary': 3500.0}
list([Link]()) Dictionary views (Python 3.0) value) tuple pairs
fromkeys() returns a dictionary with the [Link](keys, # vowels keys result =
del D[key] Deleting entries by key keys = {'a', 'e', 'i', 'o', keys() method returns a view object that [Link]() person = {'name':
specified keys and the specified value) 'Phill', 'age': 22, } [Link]()
'u' } displays a list of all the keys in the
D = {x: x*2 for x in range(10)} Dictionary comprehensions (Python 3.0) value value = 'vowel' keys = [Link]() print(result)
vowels = [Link](keys,
dictionary
print(keys)
value)
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, print(vowels) DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 166 EVEN SEMESTER 167 EVEN SEMESTER 168 EVEN SEMESTER 169
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Dictionary Methods Dictionary Dictionary Comprehensions Example: Storing Student Grades


Method Operation Syntax Example • Another way to construct dictionary by zip together its keys
• Start
values() returns a view object that [Link]() and values and pass the result to the dict call
sales = { 'apple': 2,

displays a list of all the values


'orange': 3, 'grapes': 4 }
print([Link]())
• Sequence operations don’t work • Create a dictionary with student
in the dictionary >>> list(zip(['a', 'b', 'c'], [1, 2, 3])) # Zip together keys and names as keys and grades as
setdefault() returns the value of a key (if [Link](k person = {'name': 'Phill'} • Dictionaries are mappings, not sequences values values.
• Access a student's grade using
# key is not in the dictionary
the key is in dictionary). If not, eyname, value) salary = [('a', 1), ('b', 2), ('c', 3)]
it inserts key with a value to [Link]('salary')
print('person = ',person) • Assigning to new indexes adds entries D = dict(zip(['a', 'b', 'c'], [1, 2, 3])) # Make a dict from zip their name.
the dictionary print('salary = ',salary)
result • Modify a student's grade.
# key is not in the dictionary
# default_value is provided
• Keys need not always be strings
>>> D • Add a new student to the
dictionary.
age = [Link]('age',
22) {'a': 1, 'c': 3, 'b': 2}
print('person = ',person)
print('age = ',age) • Iterate through the dictionary
update() updates the dictionary with [Link](iter d = {1: "one", 2: "three"} • Can be done using dictionary comprehension and print all students with their
the elements from another able)
d1 = {2: "two"}
# updates the value of key 2
grades.
dictionary object or from an [Link](d1)
print(d)
>>> D = {k: v for (k, v) in zip(['a', 'b', 'c'], [1, 2, 3])} • End
iterable of key/value pairs >>> D = {x: x ** 2 for x in [1, 2, 3, 4]} # Or: range(1, 5)
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 170 EVEN SEMESTER 171 EVEN SEMESTER 172 EVEN SEMESTER 173
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Example Quick Quiz Data Type Wrap Up Data Type Wrap Up
>>> table = {'1975': 'Holy • >>> for year in table: • Name two ways to build a dictionary with two keys, 'a' and 'b', • Integers: 2323, 3234L • Lists, Tuples, and Dictionaries can store any type (including
Grail', '1979': 'Life of Brian’, print(year + '\t' + each having an associated value of 0. other lists, tuples, and dictionaries!)
• Floating Point: 32.3, 3.1E2
'1983': 'The Meaning of Life'} table[year]) dict1 = {'a': 0, 'b': 0}
• Only lists and dictionaries are mutable
dict2 = dict(a=0, b=0) • Complex: 3 + 2j, 1j
>>> year = '1983' • All variables are references
• Name four operations that change a dictionary object in place. • Lists: l = [ 1,2,3]
>>> movie = table[year] student = {'name': 'Amit', 'age': 20} • Tuples: t = (1,2,3)
>>> movie [Link]({'age': 21, 'grade': 'A’})
[Link]('age’) • Dictionaries: d = {‘hello’ : ‘there’, 2 : 15}
'The Meaning of Life
[Link]()
[Link]('age', 20)
• Make a dictionary that maps keys to more than one value
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 174 EVEN SEMESTER 175 EVEN SEMESTER 176 EVEN SEMESTER 177
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Example: Set Example: Dictionary Example: Tuple Example:


# languages list
languages = ['French’]
#Create a set d = {'Red': 1, 'Green': 2, 'Blue': 3} Find the repeated items of a tuple. # languages tuple
num_set = set([0, 1, 2, 3, 4, 5]) #create a tuple languages_tuple = ('Spanish', 'Portuguese’)
for color_key, value in [Link]():
# languages set
for n in num_set: print(color_key, 'corresponds to ', d[color_key]) tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7 languages_set = {'Chinese', 'Japanese’}

print(n, end=‘ ‘) print(tuplex)


# appending language_tuple elements to language
my_dict = {'data1':100,'data2':-54,'data3':247} #return the number of times it appears [Link](languages_tuple)
in the tuple. print('New Language List:', languages)
result=1
for key in my_dict:
count = [Link](4) # appending language_set elements to language
[Link](languages_set)
result=result * my_dict[key] print(result) print(count)
print('Newer Languages List:', languages)

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 178 EVEN SEMESTER 179 EVEN SEMESTER 180 EVEN SEMESTER 181
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Sorting using Custom Key Course Outcomes Syllabus


# sorting using custom key # sort by name (Ascending order)
employees = [ [Link](key=get_name) • At the end of this course, students will be able to learn about • Module 1: Introduction to Visual basic (8 hour)
{'Name': 'Alan Turing', 'age': 25, 'salary': 10000}, print(employees, end='\n\n') • Fundamentals of GUI development using [Link], Concepts of object, method and event in [Link],
{'Name': 'Sharon Lin', 'age': 30, 'salary': 8000}, Utilisation of various tools, Components and References, basic concept of event handling, I/O File
{'Name': 'John Hopkins', 'age': 18, 'salary': 1000},
{'Name': 'Mikhail Tal', 'age': 40, 'salary': 15000},
# sort by Age (Ascending order)
[Link](key=get_age) COMPUTER PROGRAMMING • CO1: Identify fundamental programming concepts, data structures, and file
handling techniques used in software development.
handling and data handling.
• Module 2: Visual basic Programming (10 hour)
] print(employees, end='\n\n')
PCC-EE 405 • CO2: Explain the principles of object-oriented programming, event-driven • 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 -
# custom functions to get employee info # sort by salary (Descending order) programming, and their applications in GUI and system programming. like reading and writing Excel file, Excel plotting, interfacing of USB/COM ports, development of
def get_name(employee): [Link](key=get_salary, Nirmal Murmu • CO3: Develop basic to intermediate-level applications using programming
net based application in client/server mode.
return [Link]('Name') reverse=True) Department of Applied Physics languages and libraries for file manipulation, data handling, and user interaction. • Module 3: Introduction to Python libraries (10 hour)
print(employees, end='\n\n')
University of Calcutta • Python Types, Expressions, Strings, Lists, Tuples, Python memory model (names, mutable and
• CO4: Compare and evaluate different programming approaches, paradigms, and immutable values), List operations, Regular Expressions, Python Functions, Abstract Data types,
tools for solving computational problems effectively. Classes and Objects in Python, Exception handling, Handling files, Python
def get_age(employee): Scientific/Statistical/Machine Learning Libraries.
return [Link]('age') • CO5: Assess the efficiency, scalability, and usability of developed applications, • Module 4: Python programming (12 hour)
optimizing code performance and debugging issues effectively. • 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
def get_salary(employee): develop machine learning based applications.
return [Link]('salary')
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 182 EVEN SEMESTER 2 EVEN SEMESTER 3
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

References Lecture Plan Lecture Plan Topic Timeline


Topic Key Concepts Hands-on Activity
Lecture No. Topic Key Concepts Lecture No. Topic Key Concepts Defining, accessing elements, slicing, Create a list, perform slicing,
Lists & Tuples
appending, modifying append elements
Variables, Data Types, and Python types, expressions, Object-Oriented Programming Classes, objects, inheritance,
1 1 List Methods & Practice list operations &
Operators operators, type conversions (OOPs) in Python polymorphism append(), remove(), sort(), index()
Operations debugging
Lists, tuples, slicing, loops (for, Multi-threading and Advanced File Threading basics, file operations, if-elif-else, nested conditions, and/or Build a number classification
2 Arrays and Flow Control 2 Conditional Statements
while), conditional statements Handling concurrent programming operators program (positive/negative/zero)
Defining functions, arguments, Timers, Event Handling, and GUI Timer-based operations, GUI Print even numbers, reverse a list
3 Methods and Functions 3 For & While Loops range(), enumerate(), iteration over lists
using loops
return values, recursion Development programming using Tkinter/PyQt
Reading/writing files, handling CSV, Using OpenCV for image Convert list of strings to
Loop Optimizations List comprehensions, zip(), map()
4 File Handling Camera Interfacing and Data uppercase using comprehension
JSON 4 processing, real-time data
Acquisition Error Handling in Loops Try accessing an out-of-range
Introduction to Scientific NumPy, Pandas, Matplotlib for data acquisition try-except, handling IndexError in lists
5 & Lists index & handle exception
Libraries processing Machine Learning and AI Basics of Scikit-learn, TensorFlow, Nested Loops & Iterating over nested lists, pattern Print a right-angled triangle
5
Applications AI-driven applications Practical Use Cases printing pattern
Final Project Discussion and Developing real-world Debugging loops & conditionals, Solve a logical bug in loop
6 Debugging & Q&A
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, Implementation DEPARTMENT OF APPLIED PHYSICS,
applications, project review common mistakes
DEPARTMENT OF APPLIED PHYSICS, UNIVERSITY OF
execution
EVEN SEMESTER 4 EVEN SEMESTER 5 EVEN SEMESTER 6 EVEN SEMESTER CALCUTTA 183
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Quick Recap Quick Recap Python: Basics Python Modules
isis:
• What is the difference between / and // operators in Python? • What method is used to retrieve all keys from a dictionary? • Variables • A Python module is a file containing Python definitions and
• What does the modulus operator (%) do? → remainder, file format • Data types statements.
• How can you update a value in a dictionary?
• How do you check if a number is even or odd using an operator? • Can define functions, classes, and variables
• How can you format floating-point numbers? • Operators
• What will be the result of the following expression? ↳ 902220, 1. 2!: 0 • Can also include runnable code
• Arrays
print(2 + 3 * 4 / 2 - 1) → 7.0 ↳ x = 62.3678
- • Flow Control • Grouping related code into a module makes the code easier
• Write a list comprehension to generate a list of squares from 1 print ("% un
4.37 "%) to understand and use.
to 5. S: [2×+2 for m in range (1,6)]. • Methods fibonacci Series
• What will be the output of the following code? • Helps the code logically organized.
62-367 • File Handling N-int (input ( "Upto what"))
my_tuple = (1, 2, 3) N-0
print ("1. [Link]"-1.2) • OOPS
my_tuple[1] = 5 Immutable.
y-1
2=0 while (2<=2):
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
UNIVERSITY OF CALCUTTA
184 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
UNIVERSITY OF CALCUTTA
462-3 185 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
UNIVERSITY OF CALCUTTA
186 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
UNIVERSITY OF CALCUTTA
print (2) 187

n-∅ y:X 2:10 P N = Y


O Y = Z
Z = NtY

Define Python Module ¼


I/
⅔ 2 0 1 2 3 4 5
Array Array and List Create an Array
Imp 3 0
2 3 5
5
I
Import numpyas up
# Fibonacci numbers module import fibo
• A data structure which can hold more than one value at a • First, import the array module
print([Link](2)) Array List
def fib(n): # write Fibonacci series up to n from fibo import fib 1
time. • Without alias: import array N: np-array
a, b = 0, 1 a-0, b: 1
• Can have only one type of • Can have different types of • Using alias: import array as arr
while a < n:
0, 1,1, 2,3, 5....
• Collection or ordered series of elements of the same type data data
print(a, end=' ')
from fibo import fib • Using * : from array import *
a, b = b, a+b → a:b
print() b-ath
Variable: a
• Operation can be • If different data types are type → Only signed It
def fib2(n): # return Fibonacci series up to n
from fibo import *
Value 1 2 3 … 99
performed based on data stored, operation can not be import array import array as arr from array import *
result = []
Indexing a[0] a[1] a[2] … a[100]
types performed a = [Link](‘i’,[1,2,3,4]) a = [Link](‘i’,[1,2,3,4]) a = array(‘i’,[1,2,3,4])

a, b = 0, 1
while a < n: Import all names array('i', [1, 2, 3, 4]) array('i', [1, 2, 3, 4]) array('i', [1, 2, 3, 4])
[Link](a)
a, b = b, a+b import sys l Array
return result Name of constructor
[Link](0, the module
'G:/Library/Project/Python/Jupyter_
if __name__ == "__main__": demo')
print('Running the fibo module')
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS, Import188
from EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
189 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
190 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
191
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
different path

Example: Storing and Manipulating


Array Operation Array Operation Array Operation import array # Step 2: Import array
Student Marks module
marks = [Link]('i', [85, 90, 78,
Single element


88, 76]) # 'i' indicates an integer
• Accessing array elements: • Add elements to an array: Set of item index element • Concatenation: Joining array using the + symbol • Start array

Forward indexing a[0] a[1] … a[99] [Link](5) ✓ [Link]([6, 7]) [Link]([2, 8]) import array
• Import the array module. print("First student's marks:",
a = [Link](‘d’,[1.1,2.2,3.8]) • Create an array to store five student marks[0])
Values 1 2 … 100 array('i', [1, 2, 3, 4, 5, 6, 7]) [95, 90,78, 88,76]
array('i', [1, 2, 3, 4, 5]) array('i', [1, 2, 8, 3, 4, 5, 6, b = [Link](‘d’,[3.1, 3.7]) array(‘d’,[1.1,2.2,3.8, 3.1, 3.7]) marks. • = 95
marks[1]
7])
c = [Link](‘d’) ↑
Backward indexing a[-100] a[-99] … a[-1] • Removing elements: c = a + b double. • Access an element using an index. print("Updated Marks:", marks)
print("\nAll Student Marks:")
• Determine length: import array • pop(): remove an element and return it print(c) • Modify an element at a given index.
for mark in marks: 95 88
a = [Link](‘i’,[1,2,3,4]) • remove(): remove an element with a specific value without return • Iterate through the array and print all 90 76
len(a)
l l
l .
it • Slicing values. print(mark)
78
pop is return [Link](89)
import array
.
Popping last element 3.7
• Append a new value to the array.
a = [Link](‘d’,[1.1,2.2,3.8, 3.1, 3.7]) Popping 4th element 3.1
type fnc
import array print("After Appending:", marks)
↳ [95. 90,78, 88,1
print(“Popping last element”, [Link]()) array(‘d’, [2.2, 3.8])
• Remove an element from the array.

→ 3.1 a = [Link](‘d’,[1.1,2.2,3.8]) array(‘d’,[1.1,2.2,3.8])
print(“Popping 4th element”, [Link](3)) [Link](78) 7.6189
3'/ print(a[0:3]) -
4
[Link](1.1)
print(a) [2. 2,3-8)
• End print("After Removing 78:", marks)
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, ↳ [95,50, 88,76-89
EVEN SEMESTER 192 EVEN SEMESTER 193 EVEN SEMESTER 194 EVEN SEMESTER 195
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Python: Basics Python’s Statements Python’s Statements Python’s Statements


• Expressions process objects and are embedded in Statement Role Example Statement Role Example Statement Role Example
• Variables • Statements are the things to tell Python what your statements while X > Y:
while/else General loops
• Data types programs should do print('hello')
• Statements code the larger logic of a program’s operation while True:
• Operators • Python Program Structure pass Empty place holder
• Statements always exist in modules pass
• Programs are composed of modules. while True:
• Arrays • Modules contain statements.
Statement Role Example Statement Role Example Statement Role Example break Loop exit
if exittest(): break
Assignment Creating references a, *b = 'good', 'bad', 'ugly
• Flow Control • Statements contain expressions. Calls and other continue Loop continue
while True:
Running functions [Link]("spam, ham") if skiptest(): continue
• Methods • Expressions create and process objects. expressions
def f(a, b, c=1, *d):
print calls Printing objects print('The Killer', joke) def Functions and method
• File Handling • Python syntax is composed of statements and expressions print(a+b+c+d[0])
if "python" in text: def f(a, b, c=1, *d):
if/elif/else Selecting actions
• OOPS • Semicolon can be used as statement separators print(text) return Functions results
return a+b+c+d[0]
for x in mylist:
for/else Sequence iteration
print(x)
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 196 EVEN SEMESTER 197 EVEN SEMESTER 198 EVEN SEMESTER 199
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Python’s Statements Python’s Statements Flow Control The if Statement
Statement Role Example Statement Role Example Statement Role Example Statement Role Example Statement Role Example Statement Role Example

yield Generator functions


def gen(n): try: • Till now, understanding of python programming a series of • The if statement is used to check a condition and if the
for i in n: yield i*2 action()
try/except/ finally Catching exceptions
except:
statements condition is true,
x = 'old'
global Namespaces def function(): print('action error')
• Python faithfully executes them in the same order • Run a block of statements (called the if-block), else process
global x, y; x = 'new' raise Triggering exceptions raise EndSearch(location)
• What if you wanted to change the flow of how it works? another block of statements (called the else-block)
def outer(): assert Debugging checks assert X > Y, 'X too small'
nonlocal Namespaces (3.0+)
x = 'old' with open('data') as myfile: • Three flow control statements in Python - if, for and while • The else clause is optional
def function(): with/as Context managers (2.6+)
process(myfile)
nonlocal x; x = 'new'
del data[k]
import Module access import sys del Deleting references del data[i:j]
from Attribute access from sys import stdin del [Link]
class Subclass(Superclass):
class Building objects staticData = []
def method(self): pass
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 200 EVEN SEMESTER 201 EVEN SEMESTER 202 EVEN SEMESTER 203
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Example: if Statement
General Form of The if Statement if Statement and Indentation if Statement Division of Two Numbers with Zero Check
• The reserved word if begins a if statement.
• The condition is a Boolean expression that
determines whether or not the body will be
executed.
if x < 10:
y = x

• How many spaces should you indent?


if x < 10: y = x
C, C++, Java, JavaScript, or Perl Python language
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.
• A colon (:) must follow the condition. • Python requires at least one, Prompt the user to enter the divisor divisor = int(input('Please enter dividend:
'))
• The block is a block of one or more • Some programmers consistently use two, four (the most popular (denominator).
statements to be executed if the condition is number), but some prefer a more dramatic display and use eight if (x > y) { if x > y:
Store the input in divisor. # If possible, divide them and report the
result
true. • A four space indentation for a block is the recommended Python style. Check if the divisor is not zero:
• The statements within the block must all be x = 1; x = 1 If divisor != 0, proceed with division: if divisor != 0:
indented the same number of spaces from the • In most programming editors you can set the Tab key to insert spaces y = 2; y = 2 Compute quotient = dividend / quotient = dividend/divisor
left. • Must use the same distance consistently throughout a Python program } divisor print(dividend, '/', divisor, "=", quotient)
• If the block contains just one statement, will
place it on the same line as the if Display the result. print('Program finished')
Print "Program finished".
End
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 204 EVEN SEMESTER 205 EVEN SEMESTER 206 EVEN SEMESTER 207
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Example: if Statement (understand) If Else If Else Example: if Statement


# 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 # Get two integers from the user
# Attenuate the number if necessary print(digit, end="") # Print the hundreds-place digit
• The reserved word if begins the if/else statement. dividend = int(input('Please enter the number to divide:
if num < 0: # Make sure number is not too small num %= 100 # Discard hundreds-place digit • The condition is a Boolean expression, determines whether or not the '))
num = 0 # Extract and print tens-place digit if block or the else block will be executed. divisor = int(input('Please enter dividend: '))
if num > 9999: # Make sure number is not too big digit = num//10 # Determine the tens-place digit • A colon (:) must follow the condition. # If possible, divide them and report the result
• The if-block is a block of one or more statements to be executed if the
num = 9999 print(digit, end="") # Print the tens-place digit
if divisor != 0:
print(end="[") # Print left brace num %= 10 # Discard tens-place digit
condition is true.
# Extract and print thousands-place digit # Remainder is the one-place digit print(dividend, '/', divisor, "=", dividend/divisor)
• The if-block is a block of one or more statements to be executed if the
--
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
condition is true.
• it must be indented one level deeper than the if line: sometimes called the body
else:
print('Division by zero is not allowed')
num %= 1000 # Discard thousands-place digit
of the if.
Please enter an integer in the range 0...9999: 38 • The reserved word else begins the second part of the if/else Please enter the number to divide: 32
[0038] statement. A colon (:) must follow the else. Please enter dividend: 0
Please enter an integer in the range 0...9999: -450 • 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 Division by zero is not allowed
[0000]

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 208 EVEN SEMESTER 209 EVEN SEMESTER 210 EVEN SEMESTER 211
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

If Else If Else example Indentation matters! Extending if-else blocks


• Fundamental building block of software Try running the example below. • Code is grouped by its indentation • We can add infinitely more if statements using elif
What do you get? • Indentation is the number of whitespace or tab characters
Conditional before the code.
statement
Executed if answer is True • If you put code in the wrong block then you will get
Executed if answer is
unexpected behavior
False

• elif = else + if which means that the previous statements


must be false for the current one to evaluate to true

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 212 EVEN SEMESTER 213 EVEN SEMESTER 214 EVEN SEMESTER 215
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Compound Boolean Expressions Compound Boolean Expressions Compound Boolean Expressions Compound Boolean Expressions
x <= y and x <= z (x <= y) and (x <= z) x <= y<= z
• Any nonzero number or nonempty object is true. • Logical operators and, or (left associative), and not • The and operator evaluates left to right, this means that if
• Zero numbers, empty objects, and the special object None are • Suppose e1 and e2 are two Boolean expressions x = 10 e1 is false, there is no need to evaluate e2.
y = 20
considered false. • e1 and e2 is true only if e1 and e2 are both true; b = (x == 10) # assigns True to b
• If it finds the expression to be false, it does not bother to
• A combination of two or more Boolean expressions using logical • if either one is false or both are false, the compound expression is false. if x == y == z: b = (x != 10) # assigns False to b check the right expression. This approach is called short-
operators is called a compound Boolean expression. • Boolean expressions e1 and e2, print('They are all the same') b = (x == 10 and y == 20) # assigns True to b circuit evaluation.
• e1 or e2 is false only if e1 and e2 are both false;
b = (x != 10 and y == 20) # assigns False to b
• The order of the subexpressions can affect performance
b = (x == 10 and y != 20) # assigns False to b
if x < 10 and input("Print value (y/n)?") == 'y':
• if either one is true or both are true, the compound expression is true. b = (x != 10 and y != 20) # assigns False to b
print(x)
• If e is a true Boolean expression, not e is false; if e is false, not e is b = (x == 10 or y == 20) # assigns True to b expensive
b = (x != 10 or y == 20) # assigns True to b • To prevent run-time errors expression
true b = (x == 10 or y != 20) # assigns True to b (x != 0) and (z/x > 1)
b = (x != 10 or y != 20) # assigns False to b

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 216 EVEN SEMESTER 217 EVEN SEMESTER 218 EVEN SEMESTER 219
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Quick quiz If Statements If Statements: A Few Special Cases If-Else Statements


• What would happen if both conditions are True? var1 = 100 (True) if a == b and c == d and \ var1 = 100
if var1: d == e and f == g: if var1:
print ("1 - Got a true expression value") print('olde') # Backslashes allow continuations... print ("1 - Got a true expression value")

print (var1)↳ 100 print (var1)

C
else:
if (a == b and c == d and print ("1 - Got a false expression value")
var2 = 0 (false)
d == e and e == f): print (var1)
if var2:
print('new') # But parentheses usually do too
print ("2 - Got a true expression value") var2 = 0
f
if var2:
Only the first True condition executes in an if-elif-else block. print (var2) print ("2 - Got a true expression value")
If both conditions are True, the first one in order executes, and others are skipped. print (var2)
Solution: Rearrange conditions from most specific to least specific to ensure correct else:
behavior. print ("2 - Got a false expression value")
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
220 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
221 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
222 EVEN SEMESTER
print
DEPARTMENT OF (var2)
APPLIED PHYSICS,
223
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Example: Checking Even or Odd Example: Checking User Login do nothing eat fivestar
The pass Statement Nested Conditionals
Number Credentials
• Start • In a code fragment the programmer wishes to do nothing if the
• Start condition is not satisfied
• The statements in the block of the if or the else may be any Python
• Store predefined username statements, including other if/else statements.
• Take an integer input from
and password.
the user. if x < 0:
• Take username and password # Do nothing (This will not work!) not legal Python value = int(input("Please enter an integer value in the range 0...10: ")
• Use the modulus operator input from the user. else: if value >= 0: # First check
(%) to check divisibility by 2: • Compare the input with print(x) if value <= 10: # Second check
• If num % 2 == 0, print "Even stored credentials: print("In range")
Number". • If both match, print "Login if x < 0: print("Done")
• Otherwise, print "Odd Successful".
pass # Do nothing do nothing
Number". • Otherwise, print "Invalid
Credentials". else:
• End • End print(x)

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 224 EVEN SEMESTER 225 EVEN SEMESTER 226 EVEN SEMESTER 227
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

P: int (input (" Enter price"D

1 The if/else Ternary Expression Example : if/else Example : if/else if P 710,000:


d: P # (002)
Example : if/else
Print (d)
• Which sets A to either Y or Z, based on the truth value of X: • Display the discounted product price in store elif P) 5000:
• For instance consider a function to convert a numerical
• The discount structure in different slabs of discount − d: P * (0.1) grade to a letter grade, ’A’, ’B’, ’C’, ’D’ or ’F’, where the
X = 1 A = Y if X else Z
• 20% on amount exceeding 10000, Print (d)
cutoffs for ’A’, ’B’, ’C’, and ’D’ are 90, 80, 70, and 60
Y = 2 print(A)
Z = 3 • 10% for amount between 5000-10000,
respectively. N = int(input( "Enter no."D
esif. P > 1000 :
if X: • 5% if it is between 1000 to 5000. d =p * 10.05) if 1790
A = Y short-circuits
else: • no discount if amount<1000 Print (d) Print( "Grade A")
A = Z else: ell/ A 780 and n Lgo
print(A) d:O
Print ("No discounty
Print ("Grad eBM
ell f m 770 and M (680
Print( "Grade ea)
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 228 EVEN SEMESTER 229 EVEN SEMESTER 230 EVEN SEMESTER 231
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Example : if/else Short-circuit Evaluation Short-circuit Evaluation Short-circuit Evaluation
def letterGrade(score):
def letterGrade(score):
if score >= 90: if score >= 90:
• The act of avoiding executing parts of a Boolean expression • or: (Shortckt only if first term: True) print(1 or cdef check():
• all() returns True if all elements in def check(i):
letter = 'A' letter = 'A' return "geeks"
else: # grade must be B, C, D or F elif score >= 80:
that have no effect on the final result. • It checks the first statement a sequence are true. It stops print("geeks")
return i
if score >= 80: • If it’s true, Python returns that value evaluating when a False value is
letter = 'B' without checking the second statement print(1 and check()) # Output: geeks
letter = 'B' encountered.
else: # grade must be C, D or F elif score >= 70: • When Python detects that there is nothing to be gained by • The second statement is only evaluated check()) # Output: 1 print(all(check(i) for i in [1, 1, 0, 0,
if score >= 70: letter = 'C' evaluating the rest of a logical expression, it stops its if the first one is false. print(0 or check() or 1) # Output: • any() returns True if at least one 3])) # Output: False

letter = 'C' elif score >= 60: evaluation and does not do the computations in the rest of • and: (short cut only if the first term = false") geeks
element in a sequence is true. It print(any(check(i) for i in [0, 0, 0, 1,
print(0 or check() and 1) # Output: 1 3])) # Output: True
else: # grade must D or F letter = 'D' the logical expression. • If the first statement is false, the entire stops evaluating when a True
if score >= 60:
else: expression must be false, value is found.
letter = 'D' An expression containing and or
• Only if the first value is true does it stops execution when the truth value
else: letter = 'F'
check the second statement and return of expression has been achieved.
letter = 'F' return letter the value.
return letter
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 232 EVEN SEMESTER 233 EVEN SEMESTER 234 EVEN SEMESTER 235
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Short-circuit Evaluation Class Quiz 0-100000000005 Class Quiz Caution about Using Floats
• Do not evaluate the second operand of binary short-circuit • What is the output of the following program: • What is the output of the following program: • Representation of real numbers in a computer can not be
logical operator if the result can be deduced from the first exact
operand y = 0.1*3
• Computers have limited memory to store data
• Also applies to nested logical operators if y != 0.3: import math
• Between any two distinct real numbers, there are infinitely many


print ('Launch a Missile') y = 0.1 * 3
real numbers.
• On a typical machine running Python, there are 53 bits of
else: precision available for a Python float
if not [Link](y, 0.3, rel_tol=1e-9): # Allowing small rounding errors
true false false true print ("Let's have peace") print("Launch a Missile")
not( (2>5) and (3/0 > 1) ) or (4/0 < 2) else:
Launch a Missile print("Let's have peace")
Evaluates to true
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 236 EVEN SEMESTER 238 EVEN SEMESTER 239 EVEN SEMESTER 240
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Using if-elif-else for a Simple Menu


Caution about Using Floats Comparing Floats
System
• The value stored internally for the decimal number 0.1 is • Because of the approximations, comparison of floats is not print("Select Operation:") elif choice == '3':

the binary fraction exact. print("1. Addition") print("Result:", num1 * num2)

0.00011001100110011001100110011001100110011001100110011010 • Solution?
print("2. Subtraction")
print("3. Multiplication")
else: COMPUTER PROGRAMMING
print("Result:", num1 / num2)
PCC-EE 405
• Equivalent to decimal value • Instead of print("4. Division")
else:
choice = input("Enter choice (1/2/3/4): ")
0.1000000000000000055511151231257827021181583404541015625 Nirmal Murmu
x == y if choice in ('1', '2', '3', '4'):
print("Invalid input! Please select a
valid option.") Department of Applied Physics
• Approximation is similar to decimal approximation 1/3 = use "))
num1 = float(input("Enter first number:
University of Calcutta
0.333333333... abs(x-y) <= epsilon num2 = float(input("Enter second number:
"))
• No matter how many digits you use, you have an where epsilon is a suitably chosen small value if choice == '1':
approximation print("Result:", num1 + num2)
elif choice == '2':
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 241 EVEN SEMESTER 242 EVEN SEMESTER
print("Result:", num1 - num2) 243
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Course Outcomes Syllabus References Lecture Plan


• At the end of this course, students will be able to learn about • Module 1: Introduction to Visual basic (8 hour) Lecture No. Topic Key Concepts
• Fundamentals of GUI development using [Link], Concepts of object, method and event in [Link], Variables, Data Types, and Python types, expressions,
Utilisation of various tools, Components and References, basic concept of event handling, I/O File 1
• CO1: Identify fundamental programming concepts, data structures, and file handling and data handling. Operators operators, type conversions
handling techniques used in software development. • Module 2: Visual basic Programming (10 hour) Lists, tuples, slicing, loops (for,
• Learn to develop program in windows environment, simple display program, Key board and 2 Arrays and Flow Control
• CO2: Explain the principles of object-oriented programming, event-driven mouse interactive program, Reading and writing I/O files, handling of other windows program - while), conditional statements
programming, and their applications in GUI and system programming. like reading and writing Excel file, Excel plotting, interfacing of USB/COM ports, development of
Defining functions, arguments,
net based application in client/server mode. 3 Methods and Functions
• CO3: Develop basic to intermediate-level applications using programming • Module 3: Introduction to Python libraries (10 hour) return values, recursion
languages and libraries for file manipulation, data handling, and user interaction.
• Python Types, Expressions, Strings, Lists, Tuples, Python memory model (names, mutable and Reading/writing files, handling CSV,
• CO4: Compare and evaluate different programming approaches, paradigms, and immutable values), List operations, Regular Expressions, Python Functions, Abstract Data types, 4 File Handling
tools for solving computational problems effectively. Classes and Objects in Python, Exception handling, Handling files, Python JSON
Scientific/Statistical/Machine Learning Libraries.
• CO5: Assess the efficiency, scalability, and usability of developed applications, Introduction to Scientific NumPy, Pandas, Matplotlib for data
• Module 4: Python programming (12 hour) 5
optimizing code performance and debugging issues effectively. Libraries processing
• 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, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 2 EVEN SEMESTER 3 EVEN SEMESTER 4 EVEN SEMESTER 5
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Lecture Plan Timeline While loop WHILE loop
Topic Activity
Lecture No. Topic Key Concepts - Why do we use loops?
Introduction to Loops
- Difference between while loop and for loop • A while loop doesn't run for a predefined number of • The reserved word while begins the while statement.
Object-Oriented Programming Classes, objects, inheritance,
1
(OOPs) in Python polymorphism
Basic while Loop Example
- Example 1: Printing numbers 1 to 10
- Example 2: while with a counter (Hands-on practice for students)
iterations. Instead, it stops as soon as a given condition • The condition determines whether the body will be (or will
Multi-threading and Advanced File Threading basics, file operations, Practical while Loop Examples
- Example 3: User login system (keep asking for correct password)
- Example 4: Sum of first N numbers using while (Live coding and discussion)
becomes true/false. continue to be) executed.
2
Handling concurrent programming Break and Quick Quiz on while Loops
- Conduct Quick Quiz (MCQs + coding questions)
• A colon (:) must follow the condition
- Discuss answers and common mistakes
Timers, Event Handling, and GUI Timer-based operations, GUI
3
Development programming using Tkinter/PyQt
Introduction to for Loop
- Difference between for and while loops
- When to use for loops instead of while loops 2 • block is a block of one or more statements to be executed
Using OpenCV for image Basic for Loop Example
- Example 5: Printing numbers 1 to 10
- Example 6: Iterating through a list (Hands-on practice)
3 as long as the condition is true.
Camera Interfacing and Data - Example 7: Iterating through a dictionary (student marks example)
4
• block must be indented one level deeper than the line that begins
4 processing, real-time data Advanced for Loop Examples
Acquisition - Example 8: Word frequency counter (Live coding and discussion)
the while statement
$
acquisition - Explain break and continue
Machine Learning and AI Basics of Scikit-learn, TensorFlow, Control Statements (break, continue) - Example: Using break inside while to exit on condition
• The block technically is part of the while statement.
5 - Example: Using continue inside for loop to skip specific iterations
Applications AI-driven applications - 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)
Final Project Discussion and Developing real-world - Encourage students to solve it and discuss their approach
6
EVEN SEMESTER
Implementation DEPARTMENT OF APPLIED PHYSICS,
applications, project review 6 Recap and
EVENQ&A
SEMESTER
- 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
244 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
245 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
246
CALCUTTA
UNIVERSITY OF CALCUTTA - Answer any questions from students UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Example: WHILE loop Example: WHILE loop Example: WHILE loop Example: while Loop with a Counter
# Program to add natural
• Printing Numbers from 1 to 10 = N" Add natural n integer numbers: # numbers up to • Algorithm
count = 1 # Initialize counter
using while Loop While n ≤ 10:
Algorithm: # sum = 1+2+3+...+n Start
• Algorithm Print (n) # To take input from the user,
while count <= 5: # Should we continue?
Start Initialize a variable count = 2
print(count) # Display counter, then Start rent / # n = int (input ("Enter n: "))
count += 1 # Increment counter Initialize a variable num = 1 Initialize a counter variable n = 10 Use a while loop with condition count <= 20
# initialize sum and counter Inside the loop:
1
Use a while loop with the condition num <= 10 num = 1
Inside the loop:
sum = 0 :
Print count
2 Print num num = 1 # Step 2: Initialize variable While num <= 10, do the following: i = 1
- .

while i <= n:
Increment count by 2
3 Increment num by 1 Increment num by 1 (num += 1)
End while num <= 10: # Step 3: Condition check sum = sum + i End count = 2 # Step 2: Initialize counter
4
print(num) # Step 4: Print number Print num i = i+1 # update counter
5 while count <= 20: # Step 3: Condition check
num += 1 # Step 4: Increment number End # print the sum
print ("The sum is", sum) print(count) # Step 4: Print even number
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 247 EVEN SEMESTER 248 EVEN SEMESTER 249 EVEN SEMESTER 250
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA count += 2 # Step 4: Increment by 2
UNIVERSITY OF CALCUTTA

Example: while Loop with a Counter Example: WHILE loop Doubt Example: WHILE loop Example: while Loop
# Counts up from zero. The user continues the count by entering
• Modify the code to print only the first 10 multiples of Print a list of integer number # print a list of integer number # 'Y'. The user discontinues the count by entering 'N'.
count = 0 # The current count
• User Login System (Keep Asking for Correct Password)
5 using a while loop! M: 1
var='0'
entry = 'Y' # Count to begin with • Algorithm
while [Link]()==True:
while entry != 'N' and entry != 'n': Start
While n ≤ 10:
var=input('enter a number..') # Print the current value of count Set correct_password = "Python123"
Print (5ᵗʰ): if [Link]()==True: print(count) Ask the user to enter a password.
print ("Your input", var) entry = input('Please enter "Y" to continue or "N" to quit: ')
N: NH if entry == 'Y' or entry == 'y’:
While the entered password is not correct:
print ("End of while loop") Print "Incorrect password. Try again."
count += 1 # Keep counting
# Check for "bad" entry Ask for the password again.
elif entry != 'N' and entry != 'n’: When the correct password is entered, print "Access Granted!"
print('"' + entry + '" is not a valid choice') End
# else must be 'N' or 'n'
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 251 EVEN SEMESTER 252 EVEN SEMESTER 253 EVEN SEMESTER 254
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Example: while Loop Login System Example: WHILE loop Definite Loops vs. Indefinite Loops Abnormal WHILE Loop
correct_password = “Python123“ # Step 2: Set the correct x = 'spam'
password
while x: # While x is not empty } IMP n = 1 n = 1
n = 1
password = input("Enter password: ") # Step 3: Ask for user print(x, end=' ') while n <= 10: stop = int(input()) a = 1
input x = x[1:] # Strip first character off x print(n) while n <= stop: while a==1:
n += 1 print(n) print(n)
# Step 4: Keep asking until the correct password is entered spam pam am On
m After m string is empty n += 1
while password != correct_password: n += 1
print("Incorrect password. Try again.")
password = input("Enter password: ")

print("Access Granted!") # Step 5: Successful login message

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 255 EVEN SEMESTER 256 EVEN SEMESTER 257 EVEN SEMESTER 258
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Example: Practical Example – User Example: Practical Example – User
Abnormal Loop Termination Quick Quiz
Login System Login System
• A while statement executes until its condition becomes false • Algorithm • Algorithm
correct_password = "Python123" # Step 2 How many times are we going to execute the while loop?
• A running program checks this condition first to determine if it should Start Start
execute the statements in the loop’s body. password = input("Enter password: ") # Step 3
Set correct_password = "Python123“ Set correct_password = "Python123“
• It then re-checks this condition only after executing all the statements
in the loop’s body. Ask the user to enter a password. Ask the user towhile
enter apassword
password.!= correct_password: # Step 4:
• Ordinarily a while loop will not immediately exit its body if its Condition
While the entered check
password is not correct:
While the entered password is not correct:
condition becomes false before completing all the statements in its print("Incorrect password. Try again.")
Print "Incorrect password.
body Print "Incorrect password.
password
Try again."Ask for = input("Enter
the password again. password: ") # Ask again i
Try again."Ask for the password again.
x = 10
When the correct password is entered: 4
while x == 10:
print('First print statement in the while loop’) When the correct password is entered: 5
print("Access Granted!") # Step 5: Successful login
top-exit
x = 5 # Condition no longer true; do we exit immediately?
print('Second print statement in the while loop') Print "Access Granted!“
Print "Access Granted!“
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
259 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
260
End
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
261 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
262
UNIVERSITY OF CALCUTTA
End UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Quick Quiz Quick Quiz Iterables Iterators (doubt)


built-in Python
function
How many times are we going to execute the while loop? What will happen if the following code runs? • Iterable means an object can be used in iteration • If an object is iterable, it can be passed to the iter()
Returns iterator
• The few datatypes are iterable • The few datatypes are iterable object
while True: x = 5 5 • Open files in Python are iterable iterable containers

print('Inside while loop') while x > 0: 5
iter('apple') # String
print(x) 5 iter(['apple', 'banana', 'cherry’]) # List
5 iter(('apple', 'banana', 'cherry’)) # Tuple
5:
iter({'apple', 'banana', 'cherry’}) # Set
iter({'apple ': 1, 'banana ': 2, 'cherry ': 3}) # Dict
I

do times iter(42) # Integer


iter(3.1) # Float
iter(len) # Built-in function

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 263 EVEN SEMESTER 264 EVEN SEMESTER 265 EVEN SEMESTER 266
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Create an Iterator Python Iterators FOR loop Example


• Iterator is a value producer that yields successive values • Iterator retains its state internally, reset with each execution • Iterate over a sequence or an "iterable" object • Say we want to go over a list and print each item along with its
from its associated iterable object index
• Doesn’t generate all the items • Allows us to iterate over a set amount of variables within a Already Index
• To create an object/class as an iterator: __iter__() • Obtain values from an iterator in one direction data structure. During that we can manipulate each item (532T OVTLE
and __next__() to the object however we want
• __iter__(): create iterator
• __next__(): obtain the next value from in iterator
a = ['Dog', 'Cow', 'Cat’]
itr = iter(a)
• Again, indentation is important here!
Traceback (most recent call last):
print(next(itr))
File "<string>", line 9, in <module>
• Sequences and containers are iterable.
print(next(itr))
print(next(itr)) StopIteration • Examples: tuples, lists, strings, dictionaries. • What if we have much more than 4 items in the list, say, 1000?
print(next(itr))
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 267 EVEN SEMESTER 268 EVEN SEMESTER 269 EVEN SEMESTER 270
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Example: FOR Statement Example: FOR Loop Example: FOR Loop FOR loop with range()
> for m in list: End value
• Now with a for loop Print ("The fruit is'Ini'indek,list. index (al)
# Program to find the sum of all numbers stored in a list # Iterate from i = 0 to i = 3 # Print list of item
# List of numbers for i in range(4): languages = ['Swift', 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
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] print(i) 'Python', 'Go'] sum += i • range(1, 10, 2) -> 1;3;5;7;9
O print(sum) • range(10, 0, -1) -> 10;9;8;7;6;5;4;3;2;1
# variable to store the sum for language in languages: • range(10, 0, -2) -> 10;8;6;4;2
sum = 0 print(language)
• range(2, 11, 2) -> 2;4;6;8;10
• range(-5, 5) -> -5;-4;-3;-2;-1;0;1;2;3;4
# iterate over the list 2 Begin value • range(1, 2) -> 1
• range(1, 1) -> (empty)
for val in numbers: 3 Swift • range(1, -1) -> (empty)
• Saves us writing more lines Python
• range(1, -1, -1) -> 1;0 7 -101
sum = sum+val 48
• range(0) -> (empty)
• Doesn't limit us in term of size go.
print ("The sum is", sum)
Step value
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 271 EVEN SEMESTER 272 EVEN SEMESTER 273 EVEN SEMESTER 274
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
DEPARTMENT OF APPLIED PHYSICS, UNIVERSITY
# Step 2: Take input from user
• Algorithm
Numerical FOR Loop Iterating Through a Dictionary
} Hold, do
sentence = input("Enter a sentence: ").lower()
after dictionary Start

OF CALCUTTA
Take a sentence input from the user.
# Step 3: Split the sentence into words
Convert the sentence to lowercase and split it
• Calculate square of n numbers a = {'apple ': 1, 'banana ': 2, 'cherry ': 3}

Example: into a list of words.


# loop variable is assigned to the dictionary’s keys words = [Link]()
N: int (input(" Enterrange"D
for i in range (i, nti): for k in a: Create an empty dictionary to store word

Word counts.
Print (" Square of i is:" i'*2)
print(k)
# Step 4: Create an empty dictionary to store word frequency
# To access the dictionary values within the loop
Use a for loop to iterate through each word: word_count = {}
Frequency
for k in a:
If the word is already in the dictionary,
print(a[k])
increment its count.
# To access the dictionary values within the loop

Counter
Otherwise, add the word with an initial # Step 5: Iterate through the word list using a for loop
for v in [Link]():
count of 1. for word in words:
print(v)
# To access the dictionary both the keys and values within the loop Sort the dictionary based on word occurrences if word in word_count:
print([Link]()) in descending order.
word_count[word] += 1 # Increment count if word exists
for k, v in [Link](): Print the top N occurring words.
print('k =', k, ', v =', v) else:
End
word_count[word] = 1 # Add word with count 1
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 275 EVEN SEMESTER 276 EVEN SEMESTER 277 EVEN SEMESTER 278
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Control Statement & Description Break statement Break statement


• break statement m- s
• Allows us to go(break) out of a loop preliminary.
• Terminates the loop statement and transfers execution to the • Adds a bit of controllability to a while loop.
statement immediately following the loop.
• Usually used with an if.
# Step 6: Sort the dictionary based on word frequency (descending • continue statement
N = -S

3 • Can also be used in a for loop. sum = 0 # Initialize sum


entry = 0 # Ensure the loop is entered
order) • Causes the loop to skip the remainder of its body and immediately
sorted_word_count = sorted(word_count.items(), key=lambda x: x[1], retest its condition prior to reiterating. # Request input from the user

reverse=True) print("Enter numbers to sum, negative number ends list:")


• pass statement while True: # Loop forever? Not really

• The pass statement in Python is used when a statement is required entry = int(input()) # Get the value
# Step 7: Print top occurring words
syntactically but you do not want any command or code to if entry < 0: # Is number negative number?

execute.
break # If so, exit the loop
print("\nWord Frequency Count:")
sum += entry # Add entry to running sum
for word, count in sorted_word_count: print("Sum =", sum) # Display the sum

print(f"{word}: {count}")
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 279 EVEN SEMESTER 280 EVEN SEMESTER 281 EVEN SEMESTER 282
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Example: Break Statement Example: Break Statement The CONTINUE Statement Example: The CONTINUE Statement
i = 1 # Demonstrating Use of fruits = ["apple", # Checking for a Number in • break statement inside a loop, it skips the rest of the body i = 0 # Iterate over a
Python break Statement "banana", "cherry"] List
while i < 6: no=int(input('any number: '))
of the loop and exits the loop while i < 6: 1 sequence but skipping a
print(i) 1 for letter in 'Python': for x in fruits:
numbers=[11,33,55,39,55,75,37 • continue statement skips the rest of the body of the loop for i += 1 particular item
if letter == 'h':
print(x) current iteration and immediately checks the loop’s
2 for letter in 'Python':
if i == 3: 2 break
,21,23,41,13] if i == 3:
condition continue 4 if letter == 'h':
break if x == "banana": for num in numbers:
print ('Current Letter
i += 1 3 :', letter) break
if num==no:
• If the loop’s condition remains true, the loop’s execution print(i) continue
apple
print ('number found resumes at the top of the loop 5 print ('Current
P in list')
y break fruits = ["apple", "banana", "cherry"] Letter:', letter)
banana else:
for x in fruits: 6
if x == "banana":
t print ('number not found continue
in list') print(x)
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 283 EVEN SEMESTER 284 EVEN SEMESTER 285 EVEN SEMESTER 286
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Example: The CONTINUE Statement Example: The CONTINUE Statement The continue Statement The PASS Statement
# Checking Prime Factors Calculate the sum of the 𝑛 numbers
# Checking Prime Factors • Used when a statement is required syntactically but do not
1. Accept input from user (n) num = 60 sum = 0
done = False
want any command or code to execute
2. Set divisor (d) to 2 print ("Prime factors
3. Perform following till n>1 for: ", num) while not done: while True:
4. Check if given number (n) is divisible val = int(input("Enter positive integer (999 quits):")) pass # Busy-wait for keyboard interrupt (Ctrl+C)
d=2
by divisor (d). if val < 0:
while num > 1:
5. If n%d==0
if num%d==0:
print("Negative value", val, "ignored") • Used is as a place-holder for a function or conditional
a. Print d as a factor
print (d)
continue # Skip rest of body for this iteration bodyto keep thinking at a more abstract level.
b. Set new value of n as n/d if val != 999:
c. Repeat from 4 num=num/d print("Tallying", val) • The pass is silently ignored:
6. If not continue sum += val def initlog(*args):
a. Increment d by 1 d=d+1 else: pass # Remember to implement this!
b. Repeat from 3 done = (val == 999) # 999 entry exits loop
def initlog(*args):
print("sum =", sum) ...
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 287 EVEN SEMESTER 288 EVEN SEMESTER 289 EVEN SEMESTER 290
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Example: PASS Statement WHILE/ELSE Example: WHILE/ELSE FOR/ELSE
for letter in 'Python': p • Python loops support an optional else block # Add five nonnegative numbers supplied by the user • Else-block will be executed when the loop is finished
l count = sum = 0
if letter == 'h': • The else block in the context of a loop provides code to
y execute when the loop exits normally else block does not
print('Please provide five nonnegative numbers when prompted') O S
pass while count < 5:
execute # Get value from the user
[ .
- .
so 651
+ for x in range(6):
print ('This is pass block') • If the loop terminates due to a break statement val = float(input('Enter number: '))
- print(x) n-5
if val < 0:
print ('Current Letter :', letter) b else:
print('Negative numbers not acceptable! Terminating')
i = 1 print("Finally finished!")
print ("Good bye!") O while i < 6: break
print(i) count += 1
n i += 1 sum += val
else: else:
print("i is no longer less than 6") print('Average =', sum/count)
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 291 EVEN SEMESTER 292 EVEN SEMESTER 293 EVEN SEMESTER 294
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Example: FOR/ELSE Example: Loop with Function Quiz Continue and Update Expr But ache
# Vowel count # Checking for Even Numbers • What will be the output of the following program

• Make sure continue does not bypass update-expression for
word = input('Enter text (no X\'s, please): ')
vowel_count = O0
- out def contains_even_number(lst):
for ele in lst:
while loops
for vc in word: if ele % 2 == 0: ✓
if c == 'A' or c == 'a' or c == 'E' or c == 'e' \
print("The list contains an even number") # print all odd numbers < 10 # print all odd numbers < 10
break # Terminate the loop
or c == 'I' or c == 'i' or c == 'O' or c == 'o': else:
i = 1 i = 1 i is not incremented

print(c, ', ', sep='', end='') # Print the vowel while i <= 10: while i <= 10:
print("The list does not contain an even number") when even number
• 9" if i%2==0: # even 7
vowel_count += 1 # Count the vowel
# elif c == 'X' or c =='x': I ' # Example usage: if i%2==0: # even encountered.
j
# print('X not allowed') print("For List 1:") continue continue Infinite loop!!
# break contains_even_number([1, 9, 8])
else: print (i, end=‘ ‘) print (i, end=‘ ‘)
print("\nFor List 2:")
print(' (', vowel_count, ' vowels)', sep='')
contains_even_number([1, 3, 5]) i = i+1 i = i+1
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 295 EVEN SEMESTER 296 EVEN SEMESTER 297 EVEN SEMESTER 298
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Problem Problem Course Outcomes


• Problem 1: Find Prime Factors of a Number (Using while loop, • Problem 2: Sum of Even and Odd Numbers (Using for
modulus operator %, integer division //, prime factorization.) Loop) • At the end of this course, students will be able to learn about
• Algorithm • Algorithm
Start Start COMPUTER PROGRAMMING • CO1: Identify fundamental programming concepts, data structures, and file
handling techniques used in software development.
Take an integer N from the user. Take an integer N from the user. PCC-EE 405 • CO2: Explain the principles of object-oriented programming, event-driven
Start with a divisor d = 2 (smallest prime number). programming, and their applications in GUI and system programming.
Initialize sum_even = 0 and sum_odd = 0. Nirmal Murmu
While N is greater than 1: • CO3: Develop basic to intermediate-level applications using programming
Use a for loop from 1 to N: Department of Applied Physics languages and libraries for file manipulation, data handling, and user interaction.
If N is divisible by d:
If the number is even, add it to sum_even. University of Calcutta • CO4: Compare and evaluate different programming approaches, paradigms, and
Print d tools for solving computational problems effectively.
Divide N by d (N = N // d) Else, add it to sum_odd.
• CO5: Assess the efficiency, scalability, and usability of developed applications,
Else, increase d by 1. Print both sums. optimizing code performance and debugging issues effectively.
End End •

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER 299 EVEN SEMESTER 301 EVEN SEMESTER 2
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Syllabus References Lecture Plan Lecture Plan


• Module 1: Introduction to Visual basic (8 hour) Lecture No. Topic Key Concepts Lecture No. Topic Key Concepts
• Fundamentals of GUI development using [Link], Concepts of object, method and event in [Link], Variables, Data Types, and Python types, expressions, Object-Oriented Programming Classes, objects, inheritance,
Utilisation of various tools, Components and References, basic concept of event handling, I/O File 1 1
handling and data handling. Operators operators, type conversions (OOPs) in Python polymorphism
• Module 2: Visual basic Programming (10 hour) Lists, tuples, slicing, loops (for, Multi-threading and Advanced File Threading basics, file operations,
• Learn to develop program in windows environment, simple display program, Key board and 2 Arrays and Flow Control 2
mouse interactive program, Reading and writing I/O files, handling of other windows program - while), conditional statements Handling concurrent programming
like reading and writing Excel file, Excel plotting, interfacing of USB/COM ports, development of
net based application in client/server mode. Defining functions, arguments, Timers, Event Handling, and GUI Timer-based operations, GUI
3 Methods and Functions 3
• Module 3: Introduction to Python libraries (10 hour) return values, recursion Development programming using Tkinter/PyQt
• Python Types, Expressions, Strings, Lists, Tuples, Python memory model (names, mutable and Reading/writing files, handling CSV, Using OpenCV for image
immutable values), List operations, Regular Expressions, Python Functions, Abstract Data types, 4 File Handling Camera Interfacing and Data
Classes and Objects in Python, Exception handling, Handling files, Python JSON 4 processing, real-time data
Scientific/Statistical/Machine Learning Libraries. Acquisition
Introduction to Scientific NumPy, Pandas, Matplotlib for data acquisition
• Module 4: Python programming (12 hour) 5
Libraries processing Machine Learning and AI Basics of Scikit-learn, TensorFlow,
• Python Programming: Object based program using multi threading, I/O handling of files, Printing 5
and display using timer operation, program for handling of interfacing of cameras, program to Applications AI-driven applications
develop machine learning based applications.
Final Project Discussion and Developing real-world
6
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
3 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
4 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
5 EVEN SEMESTER
Implementation DEPARTMENT OF APPLIED PHYSICS,
applications, project review 6
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
doubt
Python: Basics Timeline Functions Example: Calculation of Square Root
# File [Link]
• Variables Time Slot Topic Activity
• Some programs are repeatedly used in other Python script # Get value from the user
Explain built-in methods with val = float(input('Enter number: '))
• Data types
0 - 10 min Introduction to Methods
examples for performing some operation # Compute a provisional square root

• A function is a block of reusable code which only runs when


root = 1.0
• Operators 10 - 30 min List, String, Dictionary Methods Hands-on practice # How far off is our provisional root?
Explain return, arguments, it is called. diff = root*root - val
• Arrays 30 - 45 min Defining User-Defined Methods
default values # Loop until the provisional root
• For example compute square root of a number
-

# is close enough to the actual root


• Flow Control 45 - 60 min Lambda & Scope of Variables
Live coding with lambda,
L

• Can be computed by writing a code in the Python script while diff > 0.00000001 or diff < -0.00000001:

Y
global variables
print(root, 'squared is', root*root) # Report how we
• Methods ✓ 60 - 70 min Introduction to File Handling Why file handling is needed? • Use that piece of code where require (copy-paste) are doing
Hands-on practice with text root = (root + val/root) / 2 # Compute new
• File Handling 70 - 90 min Reading & Writing Files
files provisional root
# How bad is our current approximation?
• OOPS 90 - 110 min Working with CSV & JSON Files Example programs diff = root*root - val
110 - 120 min Exception Handling in File I/O Live demo, Q&A # Report approximate square root
print('Square root of', val, '=', root)
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 303 EVEN SEMESTER 304 EVEN SEMESTER 305 EVEN SEMESTER 306
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

w
Standard Functions in Python Function-related Tools Function-related Tools def fu ( c

"1 Function-related Tools


• One way to make code more reusable is by packaging it in Statement Examples • def is executable code • yield sends a result object back to the caller, but remembers
functions Calls myfunc('spam', 'eggs', meat=ham) • function does not exist until Python reaches and runs the def where it left off
def, def adder(a, b=1, *c):
• A function is a unit of reusable code return return a + b + c[0]
• it’s legal to nest def statements inside if statements, while loops, • global declares module-level variables that are to be
and even other defs assigned
• Some of the functions available in the Python standard library. global def changer():

• Python provides a collection of standard functions stored in


global x; x = 'new' • def creates an object and assigns it to a name • nonlocal declares enclosing function variables that are to
O nonlocal def changer(): • generates a new function object and assigns it to the function’s
libraries called modules. nonlocal x; x = 'new' be assigned
name
• These functions include print, input, int, float, str, and type. yield def squares(x): • Allows enclosing functions to serve as a place to retain state
for i in range(x): yield i ** 2 • attributes attached to them to record data
• The Python standard library includes many other functions lambda funcs = [lambda x: x**2, lambda x: x*3] • lambda creates an object but returns it as a result • Arguments are passed by assignment
useful for common programming tasks. • Arguments, return values, and variables are not declared
• return sends a result object back to the caller
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 308 EVEN SEMESTER 309 EVEN SEMESTER 310 EVEN SEMESTER 311
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

OOPS ept where a


5, 3
sing . can behave differently
Python Function g ###in.. "b Nested Python Function Why Use Functions? Polymorphism bas , data its interacting
a i.. r
• In Python, a function is a named block of code that • Do not need to be fully defined before the program runs • Maximizing code reuse and minimizing redundancy • The meaning of an operation depends on the objects being
performs a specific task • defs are not evaluated until they are reached and run • allow us to code an operation in a single place and use it operated upon
• Python function works similar to mathematical function in many places
#Syntax of Python function #Syntax of Python function
if test:
def func(): # Define func this way • Procedural decomposition da5M
def function_name(parameters): def <name>(arg1, arg2,... argN): def times(x, y): # Create and assign function
"""docstring""" """docstring"""
... • one function for each subtask in the process return x * y # Body executed when called
else:
#statement(s) <statements> def func(): # Or else this way →8
print(times(2, 4))
print(times('Ni', 4))
Ni Ni Ni Ni Function
...
defreturn
add (Rigy
my >→ add-lambe bda may: Nty -
... [0] * y
Point (add/5,31) Pr int (ad ida↳(51n3o)need for return func() # Call the version selected and built
= [oooo] 3- f
8 ↳ faster response.
p of
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER -.
add (5, 3) UNIVERSITY OF CALCUTTA
312 EVEN SEMESTER
UNIVERSITY OF CALCUTTA
313 EVEN SEMESTER
UNIVERSITY OF CALCUTTA
314 EVEN SEMESTER
UNIVERSITY OF CALCUTTA
315

Example: Calculation of Square Root Example: Calculation of Square Root M import math *
Functions and Modules Functions and Modules
Function # File [Link]
# Get value from the user
Function amath. squt
how
val = float(input('Enter number: '))
def Srout (n): def squareroot(val):
• All functions are not automatically invoked by interpreter -> • A Python module is simply a file that contains Python code. • Programmers must use one or more import statements
return (NAAS)
"""
This function calculates square root
of the value passed in as parameter.
Newton ✗ import • The name of the file dictates the name of the module; within a program or within the interactive interpreter
N-int (input ("Entera")) """
# Compute a provisional square root Raphson Babif • Module: collection of functions • for example, a file named [Link] contains the functions available • The Python distribution for a given platform stores these
standard modules somewhere on the computer’s hard
root = 1.0
Print (snot (a) from the standard math module
lion
# How far off is our provisional root?
Client code or
Importing sqrt function
drive.
diff = root*root - val
# Loop until the provisional root
# is close enough to the actual root
calling code
from math module • The Python standard library contains thousands of
while diff > 0.00000001 or diff < -0.00000001:
print(root, 'squared is', root*root) # Report how we are doing
def sroot (M
from math import sqrt
# Get value from the user
functions distributed throughout more than 230 modules. • The interpreter knows where to locate these standard
root = (root + val/root) / 2 # Compute new provisional root
# How bad is our current approximation?
import math
return (math-sort (n)
num = float(input("Enter number: "))
Function invocation or • One of the modules, known as the built-ins module (actual modules when an executing program needs to import
them.
# Compute the square root
diff = root*root - val
return root N = int (input ("enter") root = sqrt(num) function call name __builtins__), In modules import module
r * O)
Print (sroot (x))
# Report result
• contains print, input, etc.
Module-funch
# Report approximate square root print("Square root of", num, "=", root)
n root =squareroot(val)
print(root)

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 316 EVEN SEMESTER 317 EVEN SEMESTER 318 EVEN SEMESTER 319
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Functions and Modules Python Functions The Built-in Functions The Built-in Functions
sart No import s. ment needed abs
Sgt 1
• Python provides a number of ways to import functions from • There are broadly two types, • The dir is another built-in function, to check directory
a module • Built-in functions • dir(__builtins__): reveals all the components that a module has to
• User defined functions
=
• These functions include print, input, int, float, str, and type offer
• from math import sqrt, log10, cos
• from math import sqrt • The Python standard library, comes with installation, • The __builtins__ module is special because its components • The parameter passed by the caller is known as the actual
• Can import the entire module, as shown here: includes, are automatically available to any Python program with— parameter. or argument. value put in c e fnc inside prog

• import math • built-in functions no import statement is required • The parameter specified by the function is called the formal
• text processing services • The full name of the print function is __builtins__.print parameter. given -Sno defin
• numeric and mathematical modules
import math
y = [Link](x) >>> print('Hi’)
• During a function call the first actual parameter is assigned
• math, number, random, statistics, etc. Hi
to the first formal parameter, the second actual parameter
qualified name: (module-
print
print(math.log10(100))
[Link]-name) • concurrent execution >>> __builtins__.print('Hi’)
is assigned to the second formal parameter, etc.
- builtins. print
Hi
• threading, multiprocessing, etc. >>> id(__builtins__.print) • call [Link](10,2) computes 102 = 100
Ref: [Link]
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 320 EVEN SEMESTER 321 EVEN SEMESTER 322 EVEN SEMESTER 323
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Python __builtins__ Functions Python Standard Library: math time Function time Function
Start
Python Built-in Functions
# List the prime numbers for the range 𝑛 • The time module contains a number of functions that relate • time.perf_counter:


'abs' 'classmethod' 'enumerate' 'hash' 'locals' 'property' 'str'
'all' 'compile' 'eval' 'help' 'map' 'range' 'sum'
from math import sqrt to time. • measure elapsed time
'any' 'complex' 'exec' 'hex' 'max' 'repr' 'super'
max_value = int(input('Display primes up to what value? '))
value = 2 # Smallest prime number • The time is represented as the number of seconds since • take difference between the first call to time.perf_counter and the
'ascii' 'copyright' 'execfile' 'id' 'memoryview' 'reversed' 'tuple' January 1, 1970. second call to time.perf_counter represents an elapsed time in
while value <= max_value:
'bin' 'credits' 'filter' 'input' 'min' 'round' 'type' # See if value is prime seconds;
'bool' 'debugcell' 'float' 'int' 'next' 'runcell' 'vars'
is_prime = True # Provisionally, value is prime
# Try all possible factors from 2 to value - 1
• This is the point at which UNIX time starts, also called the • [Link]. The [Link] function suspends the program’s
'breakpoint' 'debugfile' 'format' 'isinstance' 'object' 'runfile' 'zip' trial_factor = 2
root = sqrt(value) # Compute the square root of value
“epoch.”. execution for a specified number of seconds.
'bytearray' 'delattr' 'frozenset' 'issubclass' 'oct' 'set' while trial_factor <= root:

time
from time import perf_counter from time import sleep
'bytes' 'dict' 'get_ipython' 'iter' 'open' 'setattr' if value % trial_factor == 0:
is_prime = False # Found a factor print("Enter your name: ", end="") for count in range(10, -1, -1): # Range
10
Randon
break # No need to continue; it is NOT prime 10, 9, 8, ..., 0
'callable' 'dir' 'getattr' 'len' 'ord 'slice' start_time = perf_counter()
trial_factor += 1 # Try the next potential factor print(count) # Display the count
'cell_count' 'display' 'globals' 'license' 'pow' 'sorted' if is_prime:
name = input()
sleep(1) 9
elapsed = perf_counter() - start_time
'chr' 'divmod' 'hasattr' 'list' 'print' 'staticmethod' print(value, end= ' ') # Display the prime number
value += 1 # Try the next potential prime number print(name, "it took you", elapsed, "seconds
print() # Move cursor down to next line to respond")
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 324 EVEN SEMESTER 325 EVEN SEMESTER 326 EVEN SEMESTER 327
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

time Function time Function Random Numbers Random Numbers • 1001


"

• [Link](): returns the number of seconds passed since • [Link](): accepts an epoch time and returns • Some applications require behavior that appears random. • Some applications require behavior that appears random.
epoch → 1ˢᵗ Jan 1970 a struct_time object • All algorithmic random number generators actually • All algorithmic random number generators actually
• [Link](): takes seconds passed since epoch as an produce pseudorandom numbers, not true random produce pseudorandom numbers, not true random
argument and returns a string representing local time numbers. numbers.
import time
Day Mont Date Hour Min Second • If the generator is used long enough, the pattern of • If the generator is used long enough, the pattern of
only retur
Year
result = [Link](0) numbers produced repeats itself exactly. numbers produced repeats itself exactly.
print("result:", result)
import time selon import time Sun Jan 5 11: 32: 2 3 2022
print("\nyear:", result.tm_year) • A sequence of true random numbers would not contain • A sequence of true random numbersfrom random would not seed
import randrange, contain
seconds = [Link]()
print("Seconds since epoch =", # seconds passed since epoch
print("month:", result.tm_mon) such a repeating subsequence. such a repeating subsequence. seed(23) # Set random number seed

• Python standard library has a very good pseudorandom • Python standard library has a veryprint(randrange(1,
for i in range(0, 100): # Print 100 random numbers
seconds) seconds = 1654428743.6917613
print("day of the month:", result.tm_mday)
good pseudorandom

print("tm_hour:", result.tm_hour) 1001), end=' ') # Range
local_time = [Link](seconds)
print("Local time:", local_time)
print("minute of the hour:", result.tm_min) number generator based the Mersenne Twister algorithm. number generator based the Mersenne Twister algorithm.
1...1,000, inclusive
print()
print("second of the minute:", result.tm_sec)

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 328 EVEN SEMESTER 329 EVEN SEMESTER 330 EVEN SEMESTER 331
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

stringas expression
Random Numbers: The Rolling of a
Random Numbers System-specific Functions The eval and exec Functions
Die
• The [Link] function establishes the initial value from random import randrange elif value == 4:
• The sys module provides a number of functions and • eval() allows you to evaluate arbitrary Python expressions
[Link] returns the next value in the sequence of # Roll the die three times print("| * * |")
from a string-based or compiled-code-based input.
pseudorandom values variables that give programmers access to system
for i in range(0, 3): print("| |")
# Generate random number in the range 1...7 print("| * * |")

• The program begins its pseudorandom number generation with value = randrange(1, 7) elif value == 5:
specific information. • eval is a built-ins function named that evaluate a string in the
a seed value, 23
print("| * * |")
same way that the interactive shell would evaluate it
# Show the die
print("+-------+") print("| * |")
• E.g.:“take a number x, add 900 +x, then subtract 52.” if value == 1: print("| * * |")
import sys eval("2 ** 8") x1 = eval(input('Entry x1? ‘))
elif value == 6:
• If [Link] function is omitted, the program derives its
print("| |")
code = compile("5 + 4", "<string>", print('x1 =', x1, ' type:', type(x1))
print("| * * * |")
print("| * |") sum = 0
initial value in the sequence from the time kept by the operating print("| |") print("| |")
"eval") # compiled-code-based x2 = eval(input('Entry x2? ‘))
system from random import randrange, seed
elif value == 2: print("| * * * |") while True: eval(code)
print(eval(input()))
print('x2 =', x2, ' type:', type(x2))
print("| * |") else: x = int(input('Enter a number (999 ends):’)) x3 = eval(input('Entry x3? ‘))
Ifthe seed seed(23) # Set random number seed print("| |") print(" *** Error: illegal die value ***")
if x == 999: print('x3 =', x3, ' type:', type(x3))
value is changed
for i in range(0, 100): # Print 100 random numbers print("| * |") print("+-------+")
Print "2*8") → 298 x4 = eval(input('Entry x4? ‘))
print(randrange(1, 1001), end=' ') # Range
elif value == 3: [Link](0) → stop
print("| * |") print('x4 =', x4, ' type:', type(x4))
1...1,000, inclusive sum += x Prontleval ("2*81- 16/
We get diff print()
print("| * |") x5 = eval(input('Entry x5? ‘))
print("| * |") print('Sum is', sum) print('x5 =', x5, ' type:', type(x5))
olp each time
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 332 EVEN SEMESTER 333 EVEN SEMESTER 334 EVEN SEMESTER 335
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
execs executes all

The eval and exec Functions lines as code in Python Function Python Function Python Method
string
code:"
for i in range e)
Parse expression Aspect Method Function Module Library # Function
• String Methods
A file containing def square(x):
Definition
A function associated A block of
Python definitions
A collection of modules Method Description Example
print (i) with an object reusable code packaged together return x * x
n and functions lower() Converts to lowercase "Python".lower() → 'python'
Compile it to bytecode How it's called [Link]() function() [Link]() [Link]() # Method
exec (Code) s = "python" upper() Converts to uppercase "hello".upper() → 'HELLO'
Used Imported using
Used with data types Imported using import print([Link]())
Where it’s used
like strings, lists, dicts
independently or import
library_name
strip() Removes leading/trailing spaces " text ".strip() → 'text'
within code blocks module_name # Module
Evaluate it as a Python expression "apple".replace("a", "A") →
import math import numpy import math replace() Replaces part of string
Example "abc".upper() print("Hello")
[Link](4) [Link]([1, 2, 3]) print([Link](16)) 'Apple'
Type
Bound to a Independent or
.py file
Framework or collection of # Library find() Finds substring index "hello".find("e") → 1
Return the result of the evaluation class/object user-defined modules import numpy as np
Splits by whitespace or
Can contain...
Only operates on Any logic or Functions, classes, Modules, tools, datasets, a = [Link]([1, 2, 3]) split() "a,b,c".split(',') → ['a', 'b', 'c']
object’s data computation variables sub-libraries print(a) separator
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, UNIVERSITY OF DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 336 EVEN SEMESTER CALCUTTA 337 EVEN SEMESTER 338 EVEN SEMESTER 339
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Python Method User Defined Function Function Basics Python Function Explore
• List Methods • So far, the code has been placed within a single block of code • There are two aspects to every Python function: #Function with No Parameters and No Return
• That single block may have contained sub-blocks for the bodies • Function definition: The definition of a function contains the code that determines the def greet():
• Dictionary Methods of structured statements like if and while,
function’s behavior
print("Hello, welcome to Python!")
• Function invocation: A function is used within a program via a function invocation.
• Tuple Methods • The program’s execution begins with the first statement in the • Every function contains four parts
block and ends when the last statement in that block is finished. • def—The def keyword introduces a function definition. greet()
• Set Methods • A single block of code (like in all our programs to this point) that • Name—The name is an identifier
does all the work itself is called monolithic code. • The name chosen for a function should accurately portray its intended purpose or describe its
functionality.
• Monolithic code that is long and complex is undesirable for • Parameters—every function definition specifies the parameters that it accepts from callers. # Function with Parameters and Return Value
several reasons: • The parameters appear in a parenthesized comma-separated list. def add(a, b):
• It is difficult to write correctly. • A colon follows the parameter list. return a + b
• Body—every function definition has a block of indented statements that constitute the
• It is difficult to debug. function’s body.
• It is difficult to extend • The body contains the code to execute when callers invoke the function. result = add(5, 3)
• The code within the body is responsible for producing the result, if any, to return to the caller. print("Sum:", result)
• An optional return statement to return a value from the function.
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 340 EVEN SEMESTER 341 EVEN SEMESTER 342 EVEN SEMESTER 343
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Function - Name Resolution: The LEGB Function - Name Resolution: The LEGB
Python Function Explore Test Knowledge
Rule ✗0
&
In $⅓
Rule
#Function with Default Parameter • Practice 1: Greet the User • With a def statement:
def greet(name="Guest"):
↳ print("Hello,", name) name great/ -) • Write a method that takes a user’s name and prints a • Name assignments create or change local names by
- greeting. default.
• Name references search at most four scopes: local, then
y, z = 1, 2 # Global variables in


greet() ✓ # Output: Hello, Guest module
• Expected Output: def all_global():
greet("Amit") # Output: Hello, Amit enclosing functions (if any), then global, then built-in. global x # Declare globals assigned
• Names declared in global and nonlocal statements map x = y + z # No need to declare y, z:
# Function with Variable-Length Arguments Enter your name: Riya assigned names to enclosing module and function
LEGB rule

def total_sum(*numbers): I + 2+3+4 Hello, Riya! Welcome to Python Programming. scopes, respectively
return sum(numbers)
= 10
print("Total:", total_sum(1, 2, 3, 4))
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 344 EVEN SEMESTER 345 EVEN SEMESTER 346 EVEN SEMESTER 347
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Function: The Built-in Scope Function: Cross File Variability Arguments and Shared References Function Basics: The return Statement
# [Link]
• built-in scope is just a built-in module called builtins X = 99 # This code doesn't know about [Link] • Arguments are passed by automatically assigning objects • Used to exit a function and return to the caller
C' to local variable names • Contain an expression that gets evaluated and the value is
# [Link]
import first • Assigning to argument names inside a function does not returned
print(first.X) # OK: references a name in another file affect the caller • If no return statement, then will return none object
def hider(): first.X = 88 # But changing it can be too subtle and implicit
open = 'spam' # Local variable, hides built-in here
>>> def f(a): # a is assigned to (references) the passed object
... # [Link]
open('[Link]') # Error: this no longer opens a file in this
a = 99 # Changes local variable a only
X = 99
scope!
def setX(new): # Accessor make external changes explit >>> b = 88
global X # And can manage access in a single place >>> f(b) # a and b both reference same 88 initially
hide the built-in
function called
open
X = new
# [Link] 88 ⇔
>>> print(b) # b is not changed

import first
[Link](88) # Call the function instead of changing directly
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 348 EVEN SEMESTER 349 EVEN SEMESTER 350 EVEN SEMESTER 351
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Function Basics: The return Statement Argument Matching Syntax Argument Matching Syntax Argument Matching Syntax
Syntax Location Interpretation Syntax Location Interpretation Syntax Location Interpretation
func(value) Caller Normal argument: matched by position Normal argument: matches any passed value by position Matches and collects remaining positional arguments in a
• Used to exit a function and return to the caller func(name=value) Caller Keyword argument: matched by name
def func(name) Function
or name
def func(*name) Function
tuple
• Contain an expression that gets evaluated and the value is func(*iterable) Caller Pass all objects in iterable as individual positional arguments def func(*name) Function
Matches and collects remaining positional arguments in a
def func(*other, name) Function
Arguments that must be passed by keyword only in calls
tuple (3.X)
returned func(**dict) Caller
Pass all key/value pairs in dict as individual keyword
arguments Arguments that must be passed by keyword only in calls
def func(*, name=value) Function
• If no return statement, then will return none object (3.X)

>>> def changer(a, b): # Arguments assigned references to objects


In a function call, In a function header,
In a function header,
a = 2 # Changes local name's value only simple values are matched by position, a simple name is matched by position or name depending on how the caller passes it,
- a simple name is matched by position or name depending on how the caller passes it,
b[0] = 'spam' # Changes shared object in place the name=value form tells Python to match by name to arguments instead; these are the name=value form specifies a default value
>>> X = 16- [ "2) co]-'R'→ [n,z) the name=value form specifies a default value
called keyword arguments the *name form collects any extra unmatched positional arguments in a tuple,
>>> L = [1, 2] # Caller: Using a *iterable or **dict in a call allows us to package up arbitrarily many positional the *name form collects any extra unmatched positional arguments in a tuple,
the **name form collects extra keyword arguments in a dictionary.
>>> changer(X, L) # Pass immutable and mutable objects or keyword objects in sequences (and other iterables) and dictionaries, respectively, 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 *
>>> X, L # X is unchanged, L is different! and unpack them as separate, individual arguments when they are passed to the 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.
(1, ['spam', 2]) function. are keyword-only arguments and must be passed by keyword in calls.
r

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 352 EVEN SEMESTER 353 EVEN SEMESTER 354 EVEN SEMESTER 355
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Argument Matching Syntax Argument Matching Syntax Argument Matching Syntax Argument Matching Syntax
23 err
>>> def f(a, b, c): print(a, b, c) fla, b. c)

def func(spam, eggs, toast=0, ham=0): # First 2 required
>>> f(1, 2, 3) print((spam, eggs, toast, ham)) • * and **, are designed to support functions that take any • ** works for keyword arguments—it collects them into a
Or (3. 2,' number of arguments new dictionary, which can then be processed with normal
--
>>> f(c=3, b=2, a=1)
Or
func(1, 2) # Output: (1, 2, 0, 0) ✓
func(1, ham=1, eggs=0) # Output: (1, 0, 0, 1) • * collects unmatched positional arguments into a tuple dictionary tools
>>> f(1, c=3, b=2) # a gets 1 by position, b and c passed by name func(spam=1, eggs=0) # Output: (1, 0, 0, 0) >>> def f(**args): print(args)
func(toast=1, eggs=2, spam=3) # Output: (3, 2, 1, 0) * >>> f() variable lengt , word
>>> def f(a, b=2, c=3): print(a, b, c) # a required, b and c optional
func(1, 2, 3, 4) # Output: (1, 2, 3, 4) >>> def f(*args): print(args) 4- (1,2, 3.4) {}
.
>>> f(1) # Use defaults >>> f() ↳ variable
length arguments.
✓ ✓

>>> f(a=1) >>> f(a=1, b=2)


f/a-1, 2. C-3)
() > def fl. (2, 2, 3,4) {'a': 1, 'b': 2}
>>> f(1, 4) # Override defaults Python matches by >>> f(1) retto
1 4 3 name, not by position (1,)
>>> f(1, 4, 5) >>> f(1, 2, 3, 4)
print (fl[
Multiaelrlowed . ilp allowed f((1,2, 3,4))
1 4 5 (1, 2, 3, 4) 1,2,3,6
>>> f(1, c=6) # Choose defaults
1 2 6 DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 356 EVEN SEMESTER 357 EVEN SEMESTER 358 EVEN SEMESTER 359
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Argument Matching Syntax Argument Matching Syntax Keyword-Only


post argument
Arguments Ordering Rules
• * unpacks a collection of arguments, rather than building a • ** syntax in a function call unpacks a dictionary of # Does not accept a variable-length argument list, but expects all
arguments following the * as keywords
• keyword-only arguments must be specified after a single
collection of arguments key/value pairs into separate keyword arguments: def kwonly(a, *, b, c):
star
After ☆ ' nd argument
print(a, b, c) • named arguments cannot appear after the **args arbitrary
>>> def func(a, b, c, d): print(a, b, c, d) >>> def func(a, b, c, d): print(a, b, c, d)
keywords form
or default
kwonly(1, c=3, b=2) ✓ >>> def f(a, *b, c=6, **d): print(a, b, c, d) # Collect args in header
>>> args = (1, 2) >>> args = {'a': 1, 'b': 2, 'c': 3} kwonly(c=3, b=2, a=1) ✓
→ Concaditation >>> args['d'] = 4
>>> f(1, 2, 3, x=4, y=5) # Default used
>>> args += (3, 4) kwonly(1, 2,3) v 1 (2, 3) 6 {'y': 5, 'x': 4} ✓
>>> func(*args) # Same as func(1, 2, 3, 4) >>> func(**args) # Same as func(a=1, b=2, c=3, d=4) >>> f(1, 2, 3, x=4, y=5, c=7) # Override default
1 2 3 4 ↳ The ☆ in fric call ≤ ent 1 2 3 4 TypeError: kwonly() takes 1 (2, 3) 7 {'y': 5, 'x': 4}
1 positional argument
unpacks the tuple >>> f(1, 2, 3, c=7, x=4, y=5) # Anywhere in keywords
but 3 were given
1 (2, 3) 7 {'y': 5, 'x': 4}
func (arg) missing} argume, >>> 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, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER
UNIVERSITY OF CALCUTTA
360 EVEN SEMESTER
UNIVERSITY OF CALCUTTA
361 EVEN SEMESTER
UNIVERSITY OF CALCUTTA
362 1 SEMESTER
EVEN (3,) 2 {'x': 4} UNIVERSITY OF CALCUTTA
363

Ordering Rules Explore: Keyword-Only Argument Explore: Argument Matching Syntax


⑨ It has to be nly
Explore: Argument Matching Syntax
def demo(a, b=10, *args, d, **kwargs): def greet(a, /, b, *, c):
• keyword-only arguments must appear before a **args def book_ticket(name, *, seat="Window", meal="Veg"): print("a =", a) ↳ multi iterabe ↳ ament print(a, b, c)
print(f"Passenger: {name}")
form in function call print("b =", b)
print(f"Seat Preference: {seat}") print("args =", args) greet(1, b=2, c=3)
>>> def f(a, *b, c=6, **d): print(a, b, c, d) # KW-only between * and ** print(f"Meal Preference: {meal}") print("d =", d) Kwargs' 2:/00, 7:20}
>>> f(1, *(2, 3), **dict(x=4, y=5)) # Unpack args at call
1 (2, 3) 6 {'y': 5, 'x': 4}
print("kwargs =", kwargs) • a is positional-only
book_ticket("Amit", seat="Aisle", meal="Non-Veg") (3. 4,5)
>>> f(1, *(2, 3), **dict(x=4, y=5), c=7) # Keywords before **args!
demo(1, 2, 3, 4, 5, d=6, x=100, y=200) , • b can be positional or keyword
SyntaxError: invalid syntax
>>> f(1, *(2, 3), c=7, **dict(x=4, y=5)) # Override default
• Class Practice to create a function should print all • c is keyword-only
1 (2, 3) 7 {'y': 5, 'x': 4} information posh • Class Practice to create a function should print all
>>> f(1, c=7, *(2, 3), **dict(x=4, y=5)) # After or before * information
def register_student(name, *, branch, year): def pizza_order(name, size="medium", *toppings, extra_cheese=False,
1 (2, 3) 7 {'y': 5, 'x': 4}
>>> f(1, *(2, 3), **dict(x=4, y=5, c=7)) # Keyword-only in ** # Should print all information **extras):
1 (2, 3) 7 {'y': 5, 'x': 4} # Print all arguments in order
pizza_order("Rohit", "large", "mushrooms", "corn", extra_cheese=True,
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER
UNIVERSITY OF CALCUTTA
364 EVEN SEMESTER
UNIVERSITY OF CALCUTTA
365 sauce="BBQ")
EVEN SEMESTER
UNIVERSITY OF CALCUTTA
366 EVEN SEMESTER
UNIVERSITY OF CALCUTTA
367
Function Basics: The return Statement Function Basics: The yield Statement Function Basics: The yield Statement Function Basics: The yield Statement
Using the for loop
# calculation of square list of number • Using the next() function
def square(list1):
• Used in a function to return values to the caller function yield list1[0]**2
def square(list1): def square(list1): yield list1[1] ** 2
newList = list() • It returns a generator object to the caller newList = list() yield list1[2] ** 2
for i in list1: • Executed from the last state from where the function get for i in list1: yield list1[3] ** 2
[Link](i * i) paused [Link](i * i) yield list1[4] ** 2
return newList yield newList yield list1[5] ** 2
• Generator object can be accessed using the next() function
input_list = [1, 2, 3, 4, 5, 6]
• Python generators are a simple way of creating iterators input_list = [1, 2, 3, 4, 5, 6]
print("input list is:", input_list)
input_list = [1, 2, 3, 4, 5, 6] print("input list is:", input_list) output = square(input_list)
print("input list is:", input_list) output = square(input_list) print("Output from the generator is:", output)
output = square(input_list)
1114,9, 16,28, 363 print("Output from the generator is:", output) print("Elements in the generator are:")
print("Output list is:", output) print("Elements in the generator are:",next(output)) for i in output:
print(i)
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 368 EVEN SEMESTER 369 EVEN SEMESTER 370 EVEN SEMESTER 371
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Function Design Concepts Function Basics Function Basics Parameter Passing


YIELD RETURN

• Coupling: use arguments for inputs and return for outputs Yield is generally used to convert a
Return is generally used for the end of the def double(n):
return 2 * n # Return twice the
# Counts to ten
for i in range(1, 11):
def increment(x):
execution and “returns” the result to the print("Beginning execution of increment, x = ", x)
regular Python function into a generator.
• The best ways to isolate external dependencies to a small number caller statement.
given number
# Call the function with the value 3
print(i, end=' ‘)
print()
x += 1 # Increment x
print("Ending execution of increment, x = ", x)
• Coupling: use global variables only when truly necessary It replace the return of a function to
It exits from a function and handing back
and print its result
x = double(3)
suspend its execution without destroying
• can create dependencies and timing issues that make programs local variables.
a value to its caller. print(x) # Count to ten and print each number def main():
difficult to debug, change, and reuse def count_to_10(): x = 5
efore " " 21=5
It is used when the generator returns an It is used when a function is ready to send for i in range(1, 11): print("Before increment, x =", x)
• Coupling: don’t change mutable arguments unless the caller expects intermediate result to the caller. a value.
print()
print(i, end=' ‘)
increment(x) regining" "n-s
print("After increment, x =", x)
it Code written after yield statement execute while, code written after return statement
Ending" "n=6
in next function call. wont execute. print("Going to count to ten . . .")
• Creates a tight coupling between the caller and callee count_to_10() main()
It can run multiple times. It only runs single time. print("Going to count to ten again. . .") Hter " "2=6
• Cohesion: each function should have a single, unified purpose count_to_10()

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, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 372 EVEN SEMESTER 373 EVEN SEMESTER 374 EVEN SEMESTER 375
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

def god (Mig)


If NLY:

Documenting Functions Documenting Functions Documenting Functions Local Variables


min:X
Else:
min: y
for i in range (1, minti):
if n [Link]:O:
• It is good practice to document a function’s definition with • The nature of the return value gid: i
• Variables defined within functions are local variables.
information that aids programmers who may need to use or • While the function may do a number of interesting things as
def gcd(n1, n2):
""" Computes the greatest common divisor of integers n1 • Local variables have some very desirable properties:
extend the function. indicated in the function’s purpose, what exactly does it return to and n2. ""“ returni • The memory required to store a local variable is used only when
the caller? # Determine the smaller of n1 and n2 the variable is in scope
• The purpose of the function • The same variable name can be used in different functions without
• The function’s purpose is not always evident merely from its • We can use comments to document our functions, but min = n1 if n1 < n2 else n2
# 1 definitely is a common factor to all ints any conflict.
name. Python provides a way that allows developers and tools to
extract more easily the needed information.
largest_factor = 1
for i in range(1, min + 1):
• A local variable is transitory, so it disappears in between
if n1 % i == 0 and n2 % i == 0: function invocations.
largest_factor = i # Found larger factor • Sometimes it is desirable to have a variable that exists
return largest_factor
l
independent of any function executions

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 376 EVEN SEMESTER 377 EVEN SEMESTER 378 EVEN SEMESTER 379
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Global Variables Nonlocal Variables (in Python 3.X) Nonlocal Variables (in Python 3.X) Example: Function
# Nested function with nonlocal statement
def tester(start):
• Global variable lives outside of all functions and is not local • Nested functions can reference variables in an enclosing state = start # Each call gets its own state
def smallest_num_in_list( list ): a = [10,20,30,20,10,50,60,40,80,50,40]

to any particular function. function’s scope def nested(label):


nonlocal state # Remembers state in enclosing scope
min = list[ 0 ] dup_items = set()

• Any function is capable of accessing and/or modifying a global spam 0 for a in list: uniq_items = []
variable • With nonlocal statements, nested defs can have both read print(label, state)
state += 1 # Allowed to change it if nonlocal
ham 0 if a < min: min = a for x in a:

• A variable within a function is local variable, unless the and write access to names in enclosing functions return nested
eggs 0
return min if x not in dup_items:
F = tester(0) # Nested function without nonlocal statement
variable is declared to be a global variable using the global • Unlike global, though, nonlocal applies to a name in an F('spam') # Increments state on each call def tester(start):
print(smallest_num_in_list([1, 2, -8,
0]))
uniq_items.append(x)

reserved word enclosing function’s scope, not the global module scope F('ham')
F('eggs')
state = start # Referencing nonlocals works normally dup_items.add(x)
def nested(label): print(dup_items)
• If a function defines a local variable with the same name as outside all defs print(label, state) # Remembers state in enclosing scope

a global variable, the global variable become spam 0 return nested

inaccessible to code within the function, i.e. hides the ham 1


eggs 2
F = tester(0)
global variable F('spam') # Increments state on each call
F('ham')
F('eggs')
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 380 EVEN SEMESTER 381 EVEN SEMESTER 382 EVEN SEMESTER 383
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Advantages of Local Variable over Advantages of Local Variable over
Quiz Quiz
Global Variable Global Variable
• What is the output of the following code? • What is the output of the following code? • When a function uses local variables exclusively and • When a function uses local variables exclusively and
>>> X = 'Spam' >>> def func(): performs no other input operations performs no other input operations
>>> def func(): X = 'NI’ • When examining the contents of a function, a global • When examining the contents of a function, a global
def nested(): variable requires the reader to look elsewhere (outside the variable requires the reader to look elsewhere (outside the
print(X) function) for its meaning function) for its meaning def process(n): Guess the output,
nonlocal X return n + m # m is a when
globalexecute
>>> func() • A function that uses only local variables can be tested for • A function that uses only local
variablevariables can be tested for
integer

X = 'Spam’
↳ spam nested()
correctness in isolation from other functions, since other correctness in isolation from other functions, since other
def assign_m():
functions do not affect the behavior of this function functions do not affect the behavior globalof
m this function
print(X)
>>> func()
spam m = 5

def inc_m():
global m
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED
m PHYSICS,
+= 1
EVEN SEMESTER 384 EVEN SEMESTER 385 EVEN SEMESTER 386 EVEN SEMESTER 387
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Default Parameters Recursive Function Recursive Function Recursive Functions Reusable


in copy
• Can define own functions that accept a varying number of • The function optionally must call itself within its definition def factorial(n):
"""
def factorial(n):
"""
• It is possible to reuse a function if the function definition
parameters by using a technique known as default Computes n! does not use any programmer-defined global variables nor
• The function optionally must not call itself within its
Computes n!

parameters
Returns the factorial of n. Returns the factorial of n.
any other programmer-defined functions.
definition (base case)
def countdown(n=10): """ """
if n == 0: product = 1
for count in range(n, -1, -1): # Count down from n to zero
while n:
print(count) return 1
product *= n
else:
n -= 1 • If a function does use any of these programmer-defined
• May mix non-default and default parameters in the return n * factorial(n - 1) return product
external entities, must include these dependencies as well
parameter lists of a function declaration, but all default def main(): def main(): in the new code for the function to viable.
parameters within the parameter list must appear after all """ Try out the
print(" 0! = ",
factorial function """
factorial(0))
""" Try out the
print(" 0! = ",
factorial function """
factorial(0))
the non-default parameters print(" 1! = ", factorial(1)) print(" 1! = ", factorial(1))

def sum_range(n, m=100): # OK, default follows non-default


print(" 6! = ",
print("10! = ",
factorial(6))
factorial(10))
print(" 6! = ",
print("10! = ",
factorial(6))
factorial(10)) • Python makes easy for developers to package their
sum = 0 main() functions into modules
for val in range(n, m + 1): main()
sum += val
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 388 EVEN SEMESTER 389 EVEN SEMESTER 390 EVEN SEMESTER 391
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Nested Function: Factory Functions: Nested Function: Factory Functions:


Functions as Data Nested Function
Closures Closures
• A function is special kind of object, just as integers, and • def is an executable statement, def is simply an executable • Factory functions (a.k.a. closures) are used by programs • Factory functions (a.k.a. closures) are used by programs
strings are objects. statement that need to generate event handlers on the fly in response that need to generate event handlers on the fly in response
• Nested functions can access names in all physically to conditions at runtime. to conditions at runtime.
enclosing def statements # Function factory (closure) simply generates and # Function factory (closure) simply generates and
def maker(N): returns a nested function def maker(N): returns a nested function
from math import sqrt def action(X): # Make and return action def action(X): # Make and return action
X = 99 # Global scope name: not used
x = sqrt # Assign x to sqrt function object return X ** N # action retains N from enclosing scope return X ** N # action retains N from enclosing scope
def f1():
print(x(16)) # Prints 4.0 return action return action
X = 88 # Enclosing def local
def f2(): ↗ 88 >>> f = maker(2) # Pass 2 to argument N calling the nested function >>> g = maker(3) # g remembers 3, f remembers 2 Remember the internal
print(X) # Reference made in nested def >>> f that maker created and >>> g(4) # 4 ** 3 state
f2() <function maker.<locals>.action at 0x0000000002A4A158> passed back 64
f1() # Prints 88: enclosing def local >>> f(3) # Pass 3 to X, N remembers 2: 3 ** 2 >>> f(4) # 4 ** 2
9 16
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 392 EVEN SEMESTER 393 EVEN SEMESTER 394 EVEN SEMESTER 395
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Lambda Expressions Lambda Expressions Lambda Expressions Lambda Expressions


• To call a function, we must know its name • lambda is a reserved word that introduces a lambda • lambda expression cannot be a Python statement def evaluate(f, x, y):
return f(x, y)

• Invoking functions without using their names directly expression. • Assignments are not possible within lambda expressions, def main():
a = int(input('Enter an integer:’))
def evaluate(f, x, y): • parameterlist is a comma-separated list of parameters as in and loops are not allowed print(evaluate(lambda x, y: False if x == a else True, 2, 3))
return f(x, y)
the function definition • lambda’s body is a single expression, not a block of
• If no separate function is defined for f, evaluate invokes main()

the function passed in from the caller • expression is a single Python expression statements
a is not passed as
• Want to function will execute exactly one time • expression cannot be a complete statement, nor can it >>> evaluate(lambda x, y: 3*x + y, 10,2) 32 a parameter
Closure (captures the
function definition
10 2 captures the variable
be a block of statements. >>> evaluate(lambda x, y: print(x, y), 10, 2)
variable a)
• Another way is by using lambda function >>> evaluate(lambda
5, 5)
x, y: 10 if x == y else 2,
10
# Using lambda function >>> evaluate(lambda x, y: 10 if x == y else 2,
evaluate(lambda x, y: x * y, 2, 3) 5, 3) 2

evaluate(lambda x, y: max(x, y) + x - sqrt(y), 2, 3)


DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 396 EVEN SEMESTER 397 EVEN SEMESTER 398 EVEN SEMESTER 399
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Generators Generators Generators Local Function Definitions
>>> from yieldsequence import gen

• A generator is a programming count = 0 # A global count variable


def gen():
yield 3
>>> x = gen() • A function that itself becomes large and
object that produces (that is,
def remember():
global count
yield 'wow’
>>> next(x)
3
def generate_multiples(m, n): unwieldy.
count = 0
• further can break down the large function into
yield -1

generates) a sequence of values


count += 1 # Count this invocation >>> next(x)
yield 1.2 while count < n:
print('Calling remember (#' + str(count) + ')') 'wow’
yield m * count smaller pieces
• Sometimes this more fine-grained access is
>>> from yieldsequence import gen
• Construction similar to general
>>> next(x)
print('Beginning program') >>> gen -1
count += 1
desirable, but at other times programmers do not
function but the local variables
remember() <function gen at 0x00FA14B0> >>> next(x)
remember() >>> type(gen) 1.2 def main(): want to expose that level of detail to callers.
are not remember the values remember()
remember()
<class 'function'> >>> next(x) for mult in generate_multiples(3, 6):
• Generalizing the concept of local variables,
past execution
Traceback (most recent call last): print(mult, end=' ')
remember()
def gen():
File "<stdin>", line 1, in <module>
print() Python permits programmers to define
functions within other function definitions.
print('Ending program') StopIteration

• Instead of return keyword the


yield 3
yield 'wow’ if __name__ == '__main__':
yield keyword is used yield -1
main() • These local functions are available to the
code within their enclosing function but are
yield 1.2

for i in gen(): inaccessible outside their enclosing function


print(i)
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 400 EVEN SEMESTER 401 EVEN SEMESTER 402 EVEN SEMESTER 403
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Local Function Definitions Local Function Definitions Decorators 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
from math import fabs # Main code for surface_area function def get_point(msg): x1, y1, z1 = get_point('Corner 1') def execute_augmented(x, y):
# Compute area of front face """ Prints a message specified by msg and allows the user to x2, y2, z2 = get_point('Corner 2') def max(x, y):

• A decorator simply adds some “decoration” to the function,


call_string = "{}({}, {})".format(func_name, x, y)
def surface_area(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4, length = fabs(x2 - x1) enter the (x, y, z) coordinates of a point. Returns the x3, y3, z3 = get_point('Corner 3') “““Determine the maximum of x and y”””
print(">>> Calling " + call_string)
x5, y5, z5, x6, y6, z6, x7, y7, z7, x8, y8, z8): height = fabs(y3 - y1) point as a tuple. """ x4, y4, z4 = get_point('Corner 4') return x if x > y else y
usually to augment the function’s behavior
result = f(x, y)
""" Computes the surface area of a rectangular box front_area = area(length, height) print(msg) x5, y5, z5 = get_point('Corner 5')
print("<<< Returning {} from ".format(result) + call_string)
(cuboid) defined by the 3D points (x,y,z) of # Compute area of side face x = float(input("Enter x coordinate: ")) x6, y6, z6 = get_point('Corner 6') max(20, 30)
• does not change the way a function works
return result
its eight corners: width = fabs(z5 - z1) y = float(input("Enter y coordinate: ")) x7, y7, z7 = get_point('Corner 7') print('------------------------’)
return execute_augmented
7------8 returns the side_area = area(width, height) z = float(input("Enter z coordinate: ")) x8, y8, z8 = get_point('Corner 8')

• A decorator “wraps” a function passed to it.


@ show_call_and_return_details
/| /| absolute value of a # Compute area of top face return x, y, z
def max(x, y):
3------4 | number, as a float top_area = area(length, width) # Compute the surface area of the box
| | | | # Compute and return surface area: front/back, # Get the coordinates of the box's corners from the user print('Surface area:', surface_area(x1, y1, z1, x2, y2, z2, """"Determine the maximum of x and y"""
| 5----|-6
|/ |/
# left side/right side, and top/bottom faces
return 2*front_area + 2*side_area + 2*top_area
print('Enter the coordinates of each of the box\'s corners')
print('''
x3, y3, z3, x4, y4, z4,
x5, y5, z5, x6, y6, z6,
• A decorator cannot modify the inner workings of a function def max(x, y):
"""Determine the maximum of x and y"""
return x if x > y else y

1------2 7------8 x7, y7, z7, x8, y8, z8)) call_string = "max({}, {})".format(x, y) # Decorate the functions to provide information about their calls
""" def volume(length, width, height): /| /| # Compute the volume of the box print(">>> Calling " + call_string) # We can make up a new name
# Local helper function to compute area """ Computes the volume of a rectangular box 3------4 | ln = fabs(x2 - x1) # Compute length result = x if x > y else y # Or, more typically, simply redirect the original name to a new
def area(length, width): (cuboid) defined by its length, width, and height """ | | | | wd = fabs(z5 - z1) # Compute width print("<<< Returning {} from ".format(result) + call_string) function!
""" Computes the area of a length x width rectangle """ return length * width * height | 5----|-6 ht = fabs(y3 - y1) # Compute height return result augmented_max = show_call_and_return_details(max)
return length * width |/ |/ print('Volume:', volume(ln, wd, ht))
1------2 max(20, 30) augmented_max(20, 30)
''') print('------------------------') print('------------------------')

Or by using “@” syntax before each


function
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
404 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
405 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
406 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS, e.g. @ show_call_and_return_details(max)
407
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Partial Application Partial Application Operation of if __name__ == '__main__' Python Scopes and Namespaces
• The functools module provides an interesting function named partial that • Partial application allows us to make a new function from an
accepts a function as its first parameter and one or more other parameters. def add(a, b): def add(a, b): • A namespace is a mapping from names to objects.
• The partial function returns a new function that is behaviorally related to the existing function with one or more of the original function’s return (a + b) return (a + b)

• Most namespaces are currently implemented as Python


original function passed to it actual parameters “hardwired” into the definition. print (add(10,16)) if __name__ == "__main__":

def add(x, y):


print (add(10,16)) dictionaries, but that’s normally not noticeable in any way.
return x + y • This new function exhibits the same behavior as the original
• The interpreter will not allow a caller to pass fewer than two or more than two function but requires fewer parameters during its call. from eg1 import add from eg1 import add
• Examples of namespaces are:
parameters. • the set of built-in names (functions such as abs(), and built-in
from functools import partial • Partial application can predetermine only leading parameters. print (add(7,6)) print (add(7,6))
exception names)
add5 = partial(add, 5) 1. Every Python module has it’s __name__ defined and if this is ‘__main__’, it implies that the
• This new add5 function accepts a single parameter.
• It is not possible to predetermine a parameter that follows a module is being run standalone by the user and we can do corresponding appropriate
• the global names in a module;
print(add5(3)) # Works like print(add(5, 3)) non-predetermined parameter. actions. • and the local names in a function invocation.
2. If you import this script as a module in another script, the __name__ is set to the name of
• The add5 invocation calls the original add function with 5 as the first argument the script/module.
and add5’s parameter, 3, as the second argument. 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
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
not imported. DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 408 EVEN SEMESTER 409 EVEN SEMESTER 410 EVEN SEMESTER 411
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Python Scopes and Namespaces Python Scopes and Namespaces Python Scopes and Namespaces Python Scopes and Namespaces
• In a sense the set of attributes of an object also form a namespace. • In the expression [Link], modname is a • Namespaces are created at different moments and have • The statements executed by the top-level invocation of the
• The important thing to know about namespaces is that module object and funcname is an attribute of it. different lifetimes. interpreter, either read from a script file or interactively, are
there is absolutely no relation between names in different • In this case there happens to be a straightforward mapping • The namespace containing the built-in names is created considered part of a module called __main__,
namespaces; between the module’s attributes and the global names when the Python interpreter starts up, and is never deleted. • so they have their own global namespace.
• for instance, two different modules may both define a function defined in the module: • The global namespace for a module is created when the • The built-in names actually also live in a module;
“maximize” without confusion — users of the modules must prefix • they share the same namespace! • this is called __builtin__.
it with the module name. module definition is read in;
• normally, module namespaces also last until the interpreter quits.

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 412 EVEN SEMESTER 413 EVEN SEMESTER 414 EVEN SEMESTER 415
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Python Scopes and Namespaces Python Scopes and Namespaces Python Scopes and Namespaces Python Scopes and Namespaces
• The local namespace for a function is created • A scope is a textual region of a Python program where a • Although scopes are determined statically, they are used • If a name is declared global, then all references and
• when the function is called namespace is directly accessible. dynamically. assignments go directly to the middle scope containing the
• And deleted • “Directly accessible” here means that an unqualified • At any time during execution, there are at least three nested module’s global names.
• when the function returns or raises an exception that is not reference to a name attempts to find the name in the scopes whose namespaces are directly accessible: • Otherwise, all variables found outside of the innermost
handled within the function. namespace. • the innermost scope, which is searched first, contains the local scope are read-only.
• Of course, recursive invocations each have their own local names; the namespaces of any enclosing functions,
namespace. • 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, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 416 EVEN SEMESTER 417 EVEN SEMESTER 418 EVEN SEMESTER 419
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Python Scopes and Namespaces Python Scopes and Namespaces Python Scopes and Namespaces Example:
• Usually, the local scope references the local names of the • A special quirk of Python is that assignments always go into • In fact, all operations that introduce new names use the • Function to Calculate the Square of a Number
current function. the innermost scope. local scope: # Define the function
• Outside of functions, the local scope references the same • Assignments do not copy data— • in particular, import statements and function definitions bind the def square(num):
module or function name in the local scope. (The global statement result = num * num
namespace as the global scope: • they just bind names to objects. can be used to indicate that particular variables live in the global return result
• the module’s namespace. • The same is true for deletions: scope.)
• Class definitions place yet another namespace in the local • the statement ‘del x’ removes the binding of x from the # Call the function
scope. namespace referenced by the local scope. number = int(input("Enter a number: "))
output = square(number)
print("Square of", number, "is", output)

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 420 EVEN SEMESTER 421 EVEN SEMESTER 422 EVEN SEMESTER 423
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Example: Example: Example: Example:


◦ → Multi iterase
def calc(a, b): def show_marks(*marks): def student_info(**kwargs): def outer():
print("All Marks:", marks) → D, 78,88
sum_ = a + b
product = a * b print("Total:", sum(marks))
for key, value in [Link](): print("Inside outer function.") ①/
→ print(key, ":", value)
return sum_, product
show_marks(85, 90, 78, 88)
def inner():
# Calling the function student_info(name="Priya", age=20, course="CSE") print("Inside inner function.") 2
s, p = calc(3, 4)
print("Sum:", s) name: Priy inner()
print("Product:", p)
age: 20 outer()
Ourse: (SE
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 424 EVEN SEMESTER 425 EVEN SEMESTER 426 EVEN SEMESTER 427
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Exercise: Exercise: Course Outcomes


Problem: Grading System using User-Defined Function Problem 2: Student Info Logger using **kwarg: • At the end of this course, students will be able to learn about
Statement: Statement:
Write a function get_grade(marks) that takes marks as input and returns the grade
based on the following conditions:
Write a function log_student_info(**kwargs) that takes student details COMPUTER PROGRAMMING • CO1: Identify fundamental programming concepts, data structures, and file
handling techniques used in software development.
90 and above: A+ as keyword arguments (e.g., name, age, branch, roll) and prints them PCC-EE 405 • CO2: Explain the principles of object-oriented programming, event-driven
80-89: A in a formatted manner. programming, and their applications in GUI and system programming.
70-79: B Nirmal Murmu • CO3: Develop basic to intermediate-level applications using programming
60-69: C Example Call: Department of Applied Physics languages and libraries for file manipulation, data handling, and user interaction.
Below 60: F University of Calcutta • CO4: Compare and evaluate different programming approaches, paradigms, and
log_student_info(name="Ravi", age=21, branch="ECE", roll="EE102")
tools for solving computational problems effectively.
Requirements: • CO5: Assess the efficiency, scalability, and usability of developed applications,
Use if-elif-else inside the function. Expected Output: optimizing code performance and debugging issues effectively.
Use the function to display the grade for 5 students (input through loop). Student Details: Name : Ravi Age : 21 Branch : ECE Roll : EE102 •

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER 428 EVEN SEMESTER 429 EVEN SEMESTER 2
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Syllabus References Lecture Plan Lecture Plan
• Module 1: Introduction to Visual basic (8 hour) Lecture No. Topic Key Concepts Lecture No. Topic Key Concepts
• Fundamentals of GUI development using [Link], Concepts of object, method and event in [Link], Variables, Data Types, and Python types, expressions, Object-Oriented Programming Classes, objects, inheritance,
Utilisation of various tools, Components and References, basic concept of event handling, I/O File 1 1
handling and data handling. Operators operators, type conversions (OOPs) in Python polymorphism
• Module 2: Visual basic Programming (10 hour) Lists, tuples, slicing, loops (for, Multi-threading and Advanced File Threading basics, file operations,
• Learn to develop program in windows environment, simple display program, Key board and 2 Arrays and Flow Control 2
mouse interactive program, Reading and writing I/O files, handling of other windows program - while), conditional statements Handling concurrent programming
like reading and writing Excel file, Excel plotting, interfacing of USB/COM ports, development of
net based application in client/server mode. Defining functions, arguments, Timers, Event Handling, and GUI Timer-based operations, GUI
3 Methods and Functions 3
• Module 3: Introduction to Python libraries (10 hour) return values, recursion Development programming using Tkinter/PyQt
• Python Types, Expressions, Strings, Lists, Tuples, Python memory model (names, mutable and Reading/writing files, handling CSV, Using OpenCV for image
immutable values), List operations, Regular Expressions, Python Functions, Abstract Data types, 4 File Handling Camera Interfacing and Data
Classes and Objects in Python, Exception handling, Handling files, Python JSON 4 processing, real-time data
Scientific/Statistical/Machine Learning Libraries. Acquisition
Introduction to Scientific NumPy, Pandas, Matplotlib for data acquisition
• Module 4: Python programming (12 hour) 5
Libraries processing Machine Learning and AI Basics of Scikit-learn, TensorFlow,
• Python Programming: Object based program using multi threading, I/O handling of files, Printing 5
and display using timer operation, program for handling of interfacing of cameras, program to Applications AI-driven applications
develop machine learning based applications.
Final Project Discussion and Developing real-world
6
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
3 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
4 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
5 EVEN SEMESTER
Implementation DEPARTMENT OF APPLIED PHYSICS,
applications, project review 6
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Python: Basics Introduction to File Handling Introduction to File Handling Introduction to File Handling
• Variables • What is file handling? • Syntax: • Modes in open() function:
• Data types • Why use files (vs in-memory data)? Mode Description
• Operators • Types of files: file = open("[Link]", "mode") # Perform operations
'r' Read (default)
• Arrays • Text files (.txt) [Link]()
• Data files (.csv, .json) 'w' Write (overwrites)
• Flow Control 'a' Append
• Types of file operations: Open, Read, Write, Append, Close
• Methods 'r+' Read and Write
• File modes: 'r', 'w', 'a', 'r+', 'w+', 'a+’
• File Handling ‘w+' Write and Read (File Created/Truncated)
• OOPS ‘a+’ Append and Read
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 440 EVEN SEMESTER 441 EVEN SEMESTER 442 EVEN SEMESTER 443
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

f. closed

Introduction to File Handling Introduction to File Handling Introduction to File Handling Introduction to File Handling
• Modes in open() function: • Reading a File • Writing to a File Writel) • Read Line by Line Using readline()
f- open (" student. ext", 4')
→ string value write in file
file = open("[Link]", "r") file = open("[Link]", "w") file = open("intro_example1.txt", "r")
value = f- read() / oread (m) print("Reading Line by Line:")
content = [Link]() [Link]("Welcome to Python file
Mode Read Write Truncate File Create if Missing Pointer at handling class!")
print(content) ring f. readline mbits. Writelines() line1 = [Link]()
r+ Start [Link]() [Link]() line2 = [Link]()
w+ Start turn [Link] return ↳ list of Values. print("Line 1:", line1)
a+ (Append) End (for write) • Explanation: • Explanation: print("Line 2:", line2)
list return open ( "s. txt", "w")
• open() returns a file object. Ktime • 'w' mode overwrites if file exists. [Link]()
complete return ;: e) v
• read() reads the entire content. • Creates new file if it doesn't exist.
• close() is needed to release the file resource.
. in range(5) • readline() reads one line at a time.
Val = input ( "Name a)
name. append (value)

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, f. write lines(name) DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 444 EVEN SEMESTER 445 EVEN SEMESTER 446 EVEN SEMESTER 447
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

f. closed

Introduction to File Handling Introduction to File Handling Introduction to File Handling Using with Statement
• Loop Over File Lines • Write Multiple Lines Using writelines() • File Check Before Reading • Automatically closes the file, even if error occurs.
morent lines = ["Line 1\n", "Line 2\n", "Line 3\n"] filename = "[Link]"
print("Reading all lines using a loop:")
eff
with open("intro_example3.txt", "w") as file: try: with open("[Link]", "r") as file:
file = open("intro_example1.txt", "r")
no •[Link](lines) with open(filename, "r") as file: print([Link]())
for line in file: need for print([Link]())
Oversees print([Link]()) # strip() to remove extra newline file-closed) •
except FileNotFoundError:
theuseof [Link]()
• writelines() takes a list of strings and writes all at once. print(f"Error: The file '{filename}' does not exist.")
read
• File objects are iterable, so for line in file works naturally. • Write student data in a text file
• Name, Roll Number, Branch (one per line) format
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 448 EVEN SEMESTER 449 EVEN SEMESTER 450 EVEN SEMESTER 451
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
f- open (" example. tx " "W")

Introduction to File Handling Introduction to File Handling File Handling with Exception Handling
N: int (input( "Enter"))

for i in range (n).


> f= open eple-txt", "w"): # Specify the full file path where you want to store the file
N = input (("Enter name n,
M- int (in no-of data")) file_path = "D:/MyFiles/[Link]" # <-- Change this to your desired
• Hands-on Setup: R- int (input/" Enter resa,
location • Prevents program crash if file is missing.
B = input/" Enter branchy # Step 1: Write names of 5 students
• Create a file named [Link] and append new text. with open(file_path, "w") as file:
• Clean error handling.
f. write (N) [Link]("Ravi\n")
f. write (R) [Link]("Anita\n")
• Write and read student data from a text file f. Wnt (B [Link]("Sourav\n")
try:
• Name, Roll Number, Branch (one per line) [Link]("Meera\n")
[Link]("Kunal\n") with open("[Link]", "r") as file:
# Step 2: Read and print each line using readline() data = [Link]()
with open(file_path, "r") as file:
• Then read and print the content line by line using readline() print("Reading student names line by line:")
except FileNotFoundError:
line = [Link]() print("The file does not exist!")
while line:
print([Link]()) # strip() removes newline character
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
line = [Link]() DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 452 EVEN SEMESTER 453 EVEN SEMESTER 454
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

doubt
File Handling with Exception Handling Working with CSV Files Working with CSV Files Working with CSV Files doubt
data = [ newline="" is important on Windows
to prevent extra blank lines.
["Name", "Age", "Department"],
["Amit", "21", "CSE"],
• CSV stands for Comma-Separated Values. • Writing CSV File writerow() writes one row at a time (as • Using DictWriter and DictReader
import csv a list).
["Priya", "22", "ECE"],
• It is a plain text file that stores tabular data (like a import csv
["Ravi", "23", "ME"]
] spreadsheet or database table). with open("[Link]", "w", newline="") as file:
with open("students_dict.csv", "w", newline="") as file:
writer = [Link](file)
with open("[Link]", "w") as file:
• Each line in a CSV file represents a row, and each value is [Link](["Name", "Roll No", "Marks"])
fieldnames = ["Name", "Age", "Department"]
writer = [Link](file, fieldnames=fieldnames)
for row in data: separated by a comma (,). [Link](["Ravi", "101", "85"])
line = '|'.join(row) # Use | as delimiter [Link](["Anita", "102", "90"])
[Link](line + "\n") • Easily readable and editable using text editors or Excel. import csv
[Link]()
[Link]({"Name": "Amit", "Age": 21, "Department": "CSE"})
with open("[Link]", "r") as file: • Lightweight and language-independent. [Link]({"Name": "Priya", "Age": 22, "Department": "ECE"})
with open("[Link]", "r") as
for line in file: Name,Age,Department file:
values = [Link]().split('|') # Split using the delimiter Amit,21,CSE reader = [Link](file)
print(values) Priya,22,ECE
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
for row in reader:
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER
UNIVERSITY OF CALCUTTA
455 Rohan,20,ME
EVEN SEMESTER
UNIVERSITY OF CALCUTTA
456 EVEN SEMESTER
UNIVERSITYprint(row)
OF CALCUTTA
457 EVEN SEMESTER
UNIVERSITY OF CALCUTTA
458

Working with CSV Files Working with CSV Files Working with CSV Files Working with JSON Files
• Using DictWriter and DictReader • With different delimiter • With different delimiter • JSON stands for JavaScript Object Notation.
import csv
import csv
Separator Symbol Use Case • It is a lightweight data-interchange format that is easy for humans to
with open("students_dict.csv", "r") as file:
with open("data_semicolon.csv", "w", newline="") as file: Comma , Default for .csv read and write and easy for machines to parse and generate.
writer = [Link](file, delimiter=';')
reader = [Link](file) Tab \t Often in .tsv files
[Link](["Name", "Age", "Branch"]) • It stores data as key-value pairs, very similar to Python dictionaries.
for row in reader:
[Link](["Amit", 21, "CSE"])
Pipe ` `
print(row["Name"], "is from", row["Department"])
[Link](["Priya", 22, "ECE"]) Semicolon ; Excel exports • JSON as key-JSON as key-value data format
{
Space '' Custom formats • Use [Link]() and [Link]()value data format "name": "Amit",
"age": 21,
"department": "CSE"
}
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 459 EVEN SEMESTER 460 EVEN SEMESTER 461 EVEN SEMESTER 462
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Converting Between Python and


Working with JSON Files Working with JSON Files Recap
JSON (In Memory)
• Writing JSON File • Convert Python to JSON String: • Which of the following modes is used to open a file for writing and reading,
• Why Use JSON Files? and overwrites the file if it already exists?
import json student = {"name": "Ravi", "age": 23} a) 'r+'
• Platform-independent way to store and exchange data. json_data = [Link](student) b) 'w+'
data = {"name": "Amit", "age": 21, "marks": [75, 85, print(json_data) # Output: {"name": "Ravi", c) 'a+'
• Used heavily in web APIs, data storage, and configuration files. 90]}
with open("[Link]", "w") as file:
"age": 23} d) 'r'
• Compatible with many programming languages, including Python. [Link](data, file) • Convert JSON String to Python Dictionary: • What does the readlines() function do in Python?
a) Reads one line from a file
import json b) Reads the entire file as a string
json_text = '{"name": "Ravi", "age":
23}' c) Returns a list of lines from the file
with open("[Link]", "r") as file: d) Closes the file
student = [Link](json_text)
content = [Link](file)
print(student["name"])
print(content)
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 463 EVEN SEMESTER 464 EVEN SEMESTER 465 EVEN SEMESTER 466
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Recap Example Example Example
• Which keyword is used to ensure a file is automatically closed after its • Create a Python program to: Start Start import csv Start # Step 2: Save to CSV
import json
operations are complete? Take student input (name, roll, Take student input (name, Take student input (name, with open("[Link]", "w", newline="") as
• Input student details (name, roll, marks) roll, marks) csvfile:
a) finally marks) # Step 1: Input student data
roll, marks) Save the data to: name = input("Enter student name: ") Save the data to:
writer = [Link](csvfile)
b) exit Save the data to: [Link](["Name", "Roll", "Marks"])
c) auto • Save data to CSV, JSON, A .csv file using roll = input("Enter roll number: ")
A .csv file using [Link]([student["name"],
A .csv file using [Link]() [Link]() marks = float(input("Enter marks: "))
[Link]()
d) with and TXT files student["roll"], student["marks"]])
A .json file using [Link]() A .json file using student = { A .json file using print("Data saved to [Link]")
• Which method is used to write a single line to a text file? • Read back and display the A .txt file using write() [Link]() "name": name, [Link]()
a) writeLine() saved data Open each file to read and display A .txt file using write() "roll": roll, A .txt file using write()
"marks": marks
b) writeline() the content Open each file to read and } Open each file to read and
c) write() display the content display the content
End
d) writer() End End
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 467 EVEN SEMESTER 468 EVEN SEMESTER 469 EVEN SEMESTER 470
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Example Example Practice Practice


# Step 5: Read and display each file
Start # Step 3: Save to JSON
Start print("\n Reading from [Link]:") Problem 1: Student Report Card Manager (TXT File) Problem 2: Course Registration System (CSV + JSON)
Take student input (name, with open("[Link]", "w") as jsonfile: Take student input (name, with open("[Link]", "r") as file:
roll, marks) [Link](student, jsonfile, indent=4) roll, marks) print([Link]())
Problem Statement: Problem Statement:
print("Data saved to [Link]")
Save the data to: Save the data to: print("Reading from [Link]:") Write a Python program to: Design a menu-driven program that:
A .csv file using # Step 4: Save to TXT A .csv file using with open("[Link]", "r") as file: [Link] details for 5 students (name, roll number, marks in 3 subjects). [Link] entry of student name, roll number, and chosen course.
[Link]() with open("[Link]", "w") as txtfile: [Link]() print([Link]())
[Link] the total and average for each student. [Link] each entry to a CSV file named course_enrollments.csv.
A .json file using [Link](f"Name: {student['name']}\n") A .json file using [Link] a grade based on average: [Link] all student records to a JSON file (course_data.json) with proper
[Link]() [Link](f"Roll: {student['roll']}\n") [Link]() print("Reading from [Link]:")
[Link](f"Marks: {student['marks']}\n") with open("[Link]", "r") as file: •A+ (90+), A (80–89), B (70–79), C (60–69), F (below 60) indentation.
A .txt file using write() print("Data saved to [Link]") A .txt file using write() print([Link]())
[Link] the report to a student_report.txt file in a clean tabular format. [Link] loading and displaying all enrolled student data from the JSON file.
Open each file to read and Open each file to read and
display the content display the content [Link] the content of the file after writing.
End End
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 471 EVEN SEMESTER 472 EVEN SEMESTER 473 EVEN SEMESTER 474
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Course Outcomes Syllabus References


• At the end of this course, students will be able to learn about • 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
COMPUTER PROGRAMMING • CO1: Identify fundamental programming concepts, data structures, and file
handling techniques used in software development.
handling and data handling.
• Module 2: Visual basic Programming (10 hour)
PCC-EE 405 • CO2: Explain the principles of object-oriented programming, event-driven • 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 -
programming, and their applications in GUI and system programming. like reading and writing Excel file, Excel plotting, interfacing of USB/COM ports, development of
Nirmal Murmu • CO3: Develop basic to intermediate-level applications using programming
net based application in client/server mode.
Department of Applied Physics languages and libraries for file manipulation, data handling, and user interaction. • Module 3: Introduction to Python libraries (10 hour)
University of Calcutta • Python Types, Expressions, Strings, Lists, Tuples, Python memory model (names, mutable and
• CO4: Compare and evaluate different programming approaches, paradigms, and immutable values), List operations, Regular Expressions, Python Functions, Abstract Data types,
tools for solving computational problems effectively. Classes and Objects in Python, Exception handling, Handling files, Python
Scientific/Statistical/Machine Learning Libraries.
• CO5: Assess the efficiency, scalability, and usability of developed applications, • Module 4: Python programming (12 hour)
optimizing code performance and debugging issues effectively. • 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, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,


EVEN SEMESTER 2 EVEN SEMESTER 3 EVEN SEMESTER 4
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Lecture Plan Lecture Plan Python: Basics Object-Oriented Framework


Lecture No. Topic Key Concepts Lecture No. Topic Key Concepts
• Variables • Two basic programming paradigms:
Variables, Data Types, and Python types, expressions, Object-Oriented Programming Classes, objects, inheritance,
1 1
Operators operators, type conversions (OOPs) in Python polymorphism • Data types
2 Arrays and Flow Control
Lists, tuples, slicing, loops (for,
2
Multi-threading and Advanced File Threading basics, file operations, • Operators • Procedural
while), conditional statements Handling concurrent programming • Organizing programs around functions or blocks of statements which
Defining functions, arguments, Timers, Event Handling, and GUI Timer-based operations, GUI • Arrays manipulate data.
3 Methods and Functions 3
return values, recursion Development programming using Tkinter/PyQt
• Flow Control
Reading/writing files, handling CSV, Using OpenCV for image • Object-Oriented
4 File Handling
JSON 4
Camera Interfacing and Data
processing, real-time data • Methods • combining data and functionality and wrap it inside what is called an object.
Acquisition
acquisition
5
Introduction to Scientific NumPy, Pandas, Matplotlib for data • File Handling
Libraries processing Machine Learning and AI Basics of Scikit-learn, TensorFlow,
5 • OOPS
Applications AI-driven applications
Final Project Discussion and Developing real-world
6
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
5 EVEN SEMESTER
Implementation DEPARTMENT OF APPLIED PHYSICS,
applications, project review 6 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
475 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
476
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Object Object Object-Oriented Framework Object-Oriented Framework
• An object is an instance of a class. • A typical object consists of two parts: data and methods • Classes and objects are the two main aspects of object • Objects can store data using ordinary variables that belong
• fundamental principles of OOP: Encapsulation, Inheritance, • The instance variables and methods of an object constitutes the oriented programming. to the object.
Polymorphism, and Abstraction
object’s members • A class creates a new type. • Variables that belong to an object or class are called as
• Integers, floating-point numbers, strings, and functions • An object’s data consists of its instance variables. • Where objects are instances of the class. fields.
• function objects, we have treated these objects as passive data • 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. • Objects can also have functionality by using functions that
• Other names for instance variables include attributes and fields. belong to the class. Such functions are called methods.
• In object-oriented programming, fuse data and functions together • Methods are like functions, and they are known also as operations.
• An analogy is that we can have variables of type int which • This terminology is important because it helps us to
into software units called objects (rather than treating data as • The code that uses an object is called the object’s client
passive values and functions as active agents that manipulate translates to saying that variables that store integers are differentiate between a function which is separate by itself
data) • So, an object provides a service to its clients. variables which are instances (objects) of the int class. and a method which belongs to an object.
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 477 EVEN SEMESTER 478 EVEN SEMESTER 479 EVEN SEMESTER 480
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Object-Oriented Framework Class and Object Class and Object Creating a Class
• Remember, that fields are of two types • A class is a collection of objects class Person:
• Python's objects have a bunch of "special methods" often
• they can belong to each instance (object) of the class • Blueprint for the object pass # A new block
• or they belong to the class itself. • Contains all the attributes and behaviours called magic methods. p = Person()
• They are called instance variables and class variables respectively. class class1(): % class 1 is the name of the class
print (p)
• Objects are an instance of a class • The most common is the __init__ method
#<__main__.Person instance at 0x816a6cc>
• A class is created using the class keyword. • Entity that has state and behavior
obj = class1()
• The __init__ method is a method to specify anything that
want to happen when the object is initialized
• The fields and methods of the class are listed in an
indented block.

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 481 EVEN SEMESTER 482 EVEN SEMESTER 483 EVEN SEMESTER 484
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Fields Using a Class The self The self


name = value [Link] import class • Class methods have only one specific difference from • Although, we can give any name for this parameter, it is
• Example: 1 class Point:
• client programs must import the classes they use ordinary functions strongly recommended that we use the name self.
2 x = 0
class Point: 3 y = 0 • they have an extra variable that has to be added to the beginning • Any other name is definitely frowned upon.
x = 0
y = 0 point_main.py of the parameter list
# main 1 from Point import * • but we do not give a value for this parameter when we call the • There are many advantages to using a standard name
p1 = Point() 2 • any reader of our program will immediately recognize that it is the
p1.x = 2 3 # main method.
p1.y = -5
4 p1 = Point() • this particular variable refers to the object itself, object variable i.e. the self and even specialized IDEs (Integrated
• can be declared directly inside class (as shown here) 5 p1.x = 7 Development Environments such as Boa Constructor) can help us
6 p1.y = -3 • and by convention, it is given the name self.
or in constructors (more common)
7 ...
if we use this particular name.
• Python does not really have encapsulation or private fields 8
• relies on caller to "be nice" and not mess with objects' contents 9 # Python objects are dynamic (can add fields any time!)
10 [Link] = "Tyler Durden"
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 485 EVEN SEMESTER 486 EVEN SEMESTER 487 EVEN SEMESTER 488
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

The self Object Methods Object Methods "Implicit" Parameter (self)


• Python will automatically provide this value in the function class Person: def name(self, parameter, ..., parameter): • Java: this, implicit
parameter list. def sayHi(self): statements public void translate(int dx, int dy) {
x += dx; // this.x += dx;
print ('Hello, how are you?’ )
• For example, if we have a class called MyClass and an • self must be the first parameter to any object method }
y += dy; // this.y += dy;

instance (object) of this class called MyObject, then when p = Person()


• represents the "implicit parameter" (this in Java)
we call a method of this object as [Link](arg1, [Link]() • Python: self, explicit
arg2), this is automatically converted to # This short example can also be #written as • must access the object's fields through the self reference def translate(self, dx, dy):
[Link](MyObject, arg1, arg2). Person().sayHi() class Point:
self.x += dx
self.y += dy
def translate(self, dx, dy):
• This is what the special self is all about. self.x += dx
self.y += dy • Exercise: Write distance, set_location, and
... distance_from_origin methods.

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 489 EVEN SEMESTER 490 EVEN SEMESTER 491 EVEN SEMESTER 492
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Exercise Answer Calling Methods The __init__ method The __init__ method
[Link]
1
2
from math import * • A client can call the methods of an object in two ways: • __init__ is called immediately after an instance of the class is • Incorrect, because the object has already been constructed by the
3 class Point: • (the value of self can be an implicit or explicit parameter) created. time __init__ is called, and we already have a valid reference to the
4 x = 0 new instance of the class.
5 y = 0
1) [Link](parameters) • The __init__ method is a method to specify anything that want to
6 • But __init__ is the closest thing we're going to get in Python
7 def set_location(self, x, y):
or happen when the object is initialized to a constructor, and it fills much the same role.
8 self.x = x
9
10
self.y = y
def distance_from_origin(self): 2) [Link](object, parameters) • It would be tempting but incorrect to call this the constructor of
11 return sqrt(self.x * self.x + self.y * self.y) the class.
12 def distance(self, other):
• Tempting, because it looks like a constructor (by convention, __init__ is
13 dx = self.x - other.x • Example:
14 dy = self.y - other.y
p = Point() the first method defined for the class), acts like one (it's the first piece of
15 return sqrt(dx * dx + dy * dy)
16 def translate(self, dx, dy): [Link](1, 5) code executed in a newly created instance of the class), and even
17 self.x += dx [Link](p, 1, 5) sounds like one ("init" certainly suggests a constructor-ish nature).
18 self.y += dy
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 493 EVEN SEMESTER 494 EVEN SEMESTER 495 EVEN SEMESTER 496
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

__init__ in Python: Initializer vs


Constructors Initialization Initialization
Constructor
def __init__(self, parameter, ..., parameter): [Link] [Link] • Many programmers coming from • However, __init__ is not
statements other languages (like Java or C++) technically a constructor.
1 class Car: 1 class Student:
2 def __init__(self, brand, model): 2 def __init__(self, name, roll):
naturally assume that __init__ is Here's why:
• a constructor is a special method with the name __init__ 3 [Link] = brand 3 [Link] = name Python's constructor because: • Object Already Exists When
4 [Link] = model 4 [Link] = roll
• It's the first method typically __init__ is Called:
• Example: 5 5
6 def display(self): 6 # Creating objects defined in a class • In Python, the object is actually
class Point: 7 print(f"Car: {[Link]} {[Link]}") 7 student1 = Student("Ravi", 101) created before __init__ is called
8 8 student2 = Student("Priya", 102) • It's automatically called when • When you write obj = MyClass(),
def __init__(self, x, y):
self.x = x 9 # Creating object and calling method 9 creating a new instance Python first:
10 my_car = Car(“Mahindra", “Thar") 10 print([Link]) # Output: Ravi
self.y = y 11 my_car.display() • It handles initialization of instance • Creates the raw object in
... variables memory (this is the actual
construction)
• How would we make it possible to construct a • Its name "init" suggests • Then calls __init__ to initialize
Point() with no parameters to get (0, 0)? construction that object
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 497 EVEN SEMESTER 498 EVEN SEMESTER 499 EVEN SEMESTER 500
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Class Attributes vs Instance Attributes Class and Object Variables Class and Object Variables Example: OOPS
p1 = Point()
class Point: p2 = Point()
class Point: class Person: def howMany(self): class Parrot: # instantiate the Parrot class
def __init__(self, x=0, y=0): '''Represents a person.''' '''Prints the current population.''‘ blu = Parrot("Blu", 10)
x=0 # There will always be at least one person
print(p1.x, p1.y) self.x = x # Instance attribute population = 0 # class attribute woo = Parrot("Woo", 15)
y=0 print(p2.x, p2.y) self.y = y def __init__(self, name):
if [Link] == 1:
species = "bird"
print 'I am the only person here.'
• x = 0 and y = 0 are class p1 = Point() '''Initializes the person.''' else: # access the class attributes
attributes p2 = Point() [Link] = name print 'We have %s persons here.' % [Link] # instance attribute print("Blu is a {}".format(blu.__class__.species))

• They belong to the class itself, p1.x = 5 # Only affects p1 print ('(Initializing %s)’ % [Link]) swaroop = Person('Swaroop') def __init__(self, name, age): print("Woo is also a
{}".format(woo.__class__.species))
not individual instances • Instance Attributes:
# When this person is created, # he/she adds to the [Link]() [Link] = name
population [Link]() [Link] = age
• All instances share these • These would be created inside [Link] += 1 kalam = Person('Abdul Kalam') # access the instance attributes
same values initially __init__ (which this class doesn't
have) def sayHi(self): [Link]() print("{} is {} years old".format( [Link],
[Link]))
• Each instance would have its own '''Greets the other person. Really, that's all it does.''' [Link]()
separate copy print("{} is {} years old".format( [Link],
print ('Hi, my name is %s.' % [Link]) [Link]() [Link]))

EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
501 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
502
[Link]()
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
503 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
504
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Example: OOPS Example: OOPS with Methods Encapsulation Encapsulation


class employee(): class Parrot: # instantiate the object
• Definition: Restricting access to certain parts of an object. [Link]
def __init__(self,name,age,id,salary): # creating a function blu = Parrot("Blu", 10) 1 class BankAccount:
# instance attributes • Private Attributes: Attributes prefixed with __ (double underscore). 2 def __init__(self, owner, balance):
[Link] = name # self is an instance of a class 3 [Link] = owner
[Link] = age
def __init__(self, name, age): # call our instance methods • Data Hiding: Protecting an object's internal state by hiding 4 self.__balance = balance # Private attribute
[Link] = name print([Link]("'Happy'")) implementation details 5
[Link] = salary [Link] = age print([Link]()) 6 def get_balance(self):
[Link] = id • Controlled Access: Providing public methods to interact with private 7
8
return self.__balance

# instance method data 9 account = BankAccount(“Shyamal”, 5000)


10 print(account.get_balance()) # Output: 5000
emp1 = employee("harshit",22,1000,1234) #creating objects def sing(self, song): • Implementation Independence: Allowing internal changes without
emp2 = employee("arjun",23,2000,2234)
return "{} sings {}".format([Link], song) affecting external code
print(emp1.__dict__) #Prints dictionary
def dance(self):
return "{} is now dancing".format([Link])
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 505 EVEN SEMESTER 506 EVEN SEMESTER 507 EVEN SEMESTER 508
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Encapsulation Encapsulation Encapsulation Encapsulation
[Link]
In Python, encapsulation is implemented by using: In Python, encapsulation is implemented by using: 1 class Student:
In Python, encapsulation is implemented by using:
2 def __init__(self, name, age):
•Public Attributes: •Protected Attributes: 3 [Link] = name •Private Attributes:
4 self._age = age # Protected attribute
5
•Accessible from anywhere: Inside or outside the class. •Accessible within the class and its subclasses. 6 class GraduateStudent(Student): •Accessible only within the class.
7 def display(self):
•No special syntax is needed; the attribute is just defined normally. •By convention, prefixed with a single underscore (_). 8 print(f"Name: {[Link]}, Age: {self._age}") •Defined by prefixing the attribute name with double underscores
9
[Link] •Not truly private, but treated as a non-public variable. 10 g = GraduateStudent("Priya", 22) (__).
11 [Link]() # Output: Name: Priya, Age: 22
1 class Student: 12 print(g._age) # Output: 22 (Accessible, but not recommended)
2 def __init__(self, name): •Python uses name mangling to make them inaccessible outside the
3 [Link] = name # Public attribute
4 class.
5 s1 = Student("Rahul")
6 print([Link]) # Output: Rahul
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 509 EVEN SEMESTER 510 EVEN SEMESTER 511 EVEN SEMESTER 512
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Encapsulation OOP Methodology: Encapsulation Encapsulation Inheritance


[Link]
1 class BankAccount:
2 def __init__(self, owner, balance): • Restrict access to methods and variables • One of the major benefits of object-oriented programming
3
4
[Link] = owner
self.__balance = balance # Private attribute class Computer: c = Computer()
Attribute Type Syntax Access Level Use Case
is reuse of code
5 [Link]()
6 def display_balance(self): def __init__(self):
Public [Link]
Accessible from anywhere General-purpose • One of the ways this is achieved is through the inheritance
7 return self.__balance self.__maxprice = 900 # change the price (class, subclass, outside) variables
8 c.__maxprice = 1000 mechanism.
9 acc = BankAccount("Ravi", 1000) def sell(self): [Link]() Accessible from class and Intended for internal use
Protected self._name
10 print(acc.display_balance()) # Output: 1000 print("Selling Price: {}".format(self.__maxprice)) subclasses but not enforced • Creating a new class from an existing class (Parent-Child
11 # using setter function
12 # Trying to access directly def setMaxPrice(self, price): [Link](1000)
Private self.__name
Accessible only within the
Sensitive or critical data relationship).
13 try: self.__maxprice = price [Link]() class (with name mangling)
14 print(acc.__balance) # This will raise an AttributeError • Inheritance can be best imagined as implementing a type
15 except AttributeError as e:
16 print(e) # Output: 'BankAccount' object has no attribute '__balance' and subtype relationship between classes.
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 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
514 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
515 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
516
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Inheritance Inheritance Using Inheritance Using Inheritance


class name(superclass): [Link]
class SchoolMember: class Teacher(SchoolMember):
statements 1 class Animal: ‘’’Represents any school member.’’’ '''Represents a teacher.'‘’
2 def speak(self):
• Example: 3 print("Animal speaks")
4 def __init__(self, name, age):
class Point3D(Point): # Point3D extends Point
5 class Dog(Animal): # Inheriting from Animal class
def __init__(self, name, age, salary):
z = 0
... 6 def bark(self): [Link] = name SchoolMember.__init__(self, name, age)
7 print("Dog barks") [Link] = age [Link] = salary
8
9 dog = Dog() print ('(Initialized SchoolMember: %s)' % [Link] ) print ('(Initialized Teacher: %s)' % [Link] )
• Python also supports multiple inheritance 10 [Link]() # Output: Animal speaks
11 [Link]() # Output: Dog barks
class name(superclass, ..., superclass): def tell(self): def tell(self):
statements print ('Name:"%s" Age:"%s" ' % ([Link], [Link]), ) [Link](self)
print ('Salary:"%d"' % [Link] )
(if > 1 superclass has the same field/method, conflicts are resolved in left-to-right order)

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 517 EVEN SEMESTER 518 EVEN SEMESTER 519 EVEN SEMESTER 520
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Using Inheritance Using Inheritance Multiple Inheritance Multiple Inheritance


class Student(SchoolMember): t = Teacher('Mrs. Abraham', 40, 30000) • Python supports a limited form of multiple inheritance as • This is depth-first, left-to-right. Thus, if an attribute is not found in
'''Represents a student.'‘’ s = Student('Swaroop', 21, 75) well. DerivedClassName, it is searched in Base1, then (recursively) in the
• A class definition with multiple base classes looks as base classes of Base1, and only if it is not found there, it is searched
members = [t, s] in Base2, and so on.
def __init__(self, name, age, marks): follows:
SchoolMember.__init__(self, name, age) for member in members: • A well-known problem with multiple inheritance is a class derived
[Link]() # Works for instances of Student as well class DerivedClassName(Base1, Base2, Base3): from two classes that happen to have a common base class. While it
[Link] = marks
print ('(Initialized Student: %s)' % [Link] ) as Teacher <statement-1> 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
def tell(self): by the common base class).
<statement-N>
[Link](self)
print ('Marks:"%d"' % [Link] ) • The only rule necessary to explain the semantics is the
resolution rule used for class attribute references.
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 521 EVEN SEMESTER 522 EVEN SEMESTER 523 EVEN SEMESTER 524
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
OOP Methodology: Inheritance Example: Single Inheritance Example: Multilevel Inheritance Example: Hierarchical Inheritance
class Animal: class Animal:
def speak(self): def speak(self):
• Creating a new class for using details of an existing class class Animal:
def speak(self): print("Animal speaks") print("Animal speaks")
without modifying it print("Animal speaks")
class Dog(Animal): # Inheriting from Animal class Dog(Animal): # Inheriting from Animal
• Parent class and child class class Dog(Animal): # Inheriting from def bark(self): def bark(self):
Animal print("Dog barks") print("Dog barks")
def bark(self):
print("Dog barks") class Bulldog(Dog): # Inheriting from Dog class Cat(Animal): # Inheriting from Animal
def special(self): def meow(self):
print("Bulldog has a strong bite") print("Cat meows")
d = Dog()
b = Bulldog() c = Cat()
dog = Dog() [Link]() [Link]()
[Link]() # Output: Animal speaks (Inherited from parent class) [Link]() [Link]()
[Link]() # Output: Dog barks (Defined in child class) [Link]() [Link]()
[Link]()
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 525 EVEN SEMESTER 526 EVEN SEMESTER 527 EVEN SEMESTER 528
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Example: Multiple Inheritance Example: Hybrid Inheritance Inheritance Practice Problem


# parent class class Animal:
class Father: def speak(self):
def speak(self):
print("Father speaks")
print("Animal speaks") Concept Explanation Problem:
class Mammal(Animal): Redefining a parent class method in the Create a base class Person with attributes name and age. Create two
class Mother: Method Overriding
def cook(self): def walk(self): child class.
print("Mammal walks")
print("Mother cooks")
super() function Allows access to parent class methods. child classes Student and Teacher that inherit from Person.
c = Child()
class Child(Father, Mother): # Inheriting [Link]() class Bird(Animal):
from both Father and Mother [Link]() MRO (Method Resolution Determines the order in which base [Link] Student class should have an additional attribute marks.
def fly(self):
def play(self): [Link]() print("Bird flies") Order) classes are searched. [Link] Teacher class should have an additional attribute salary.
print("Child plays")
Use super().method_name() to call a
class Bat(Mammal, Bird): # Inheriting from Mammal and Bird Accessing Parent Class [Link] method overriding by defining a display() method in both
def echo(self): parent class method.
print("Bat uses echolocation")
b = Bat() Polymorphism in child classes that overrides the parent class method.
Achieved through method overriding.
[Link]() Inheritance
[Link]()
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, [Link]() DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 529 EVEN SEMESTER 530 EVEN SEMESTER 531 EVEN SEMESTER 532
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA [Link]() UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Polymorphism Polymorphism OOP Methodology: Polymorphism Abstraction


[Link]
• To use a common interface for multiple forms
• Having multiple forms. Same method name but different 1
2
class Shape:
def area(self): • Hiding complex details and exposing only necessary parts.
3 pass class Parrot: # common interface
implementations. 4
5 class Square(Shape): def fly(self):
def flying_test(bird):
[Link]() • Implemented using Abstract Classes.
6 def area(self, side): print("Parrot can fly")
• Achieved through Method Overloading and Method 7
8
return side * side
def swim(self):
#instantiate objects
blu = Parrot() • When you drive a car, you press the accelerator to speed
9 class Circle(Shape): print("Parrot can't swim") peggy = Penguin()
Overriding. 10 def area(self, radius):
up. You don't need to know how the engine works
11 return 3.14 * radius * radius class Penguin: # passing the object
12 flying_test(blu)
13
14
square = Square()
circle = Circle()
def fly(self): flying_test(peggy) internally. The car abstracts the complexity and provides a
print("Penguin can't fly")
15
16 print([Link](4)) # Output: 16 def swim(self): simple interface (accelerator pedal) for the user.
17 print([Link](3)) # Output: 28.26 print("Penguin can swim")

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 533 EVEN SEMESTER 534 EVEN SEMESTER 535 EVEN SEMESTER 536
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Abstraction OOP Methodology: Polymorphism Magic Methods (Dunder Methods) Magic Methods (Dunder Methods)
from abc import ABC, abstractmethod class Cat(Animal):
def sound(self):
[Link]
1 from abc import ABC, abstractmethod
# Abstract Class
class Animal(ABC):
return "Meow"
• Special methods with __ prefix and suffix (e.g., __init__, • To provide customized behavior for built-in operations.
2 @abstractmethod def habitat(self):
3 class Animal(ABC): def sound(self): return "Domestic" __str__, __repr__). • To implement operator overloading.
4 @abstractmethod pass
5 def sound(self): # Instantiate objects
6
7
pass @abstractmethod
def habitat(self):
dog = Dog()
cat = Cat()
• Enable operator overloading and customization of built-in • To make user-defined classes behave like built-in types.
8 class Dog(Animal): pass
9 def sound(self): print([Link]()) # Output: Bark behavior.
10 return "Bark" # Concrete Class (Implementing Abstract Class) print([Link]()) # Output: • To enhance code readability and efficiency.
11 class Dog(Animal): Domestic
12 dog = Dog() def sound(self): print([Link]()) # Output: Meow
13 print([Link]()) # Output: Bark return "Bark" print([Link]()) # Output:
Domestic
def habitat(self):
return "Domestic"

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 537 EVEN SEMESTER 538 EVEN SEMESTER 539 EVEN SEMESTER 540
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Magic Methods (Dunder Methods) Magic Methods (Dunder Methods) Magic Methods (Dunder Methods) Magic Methods (Dunder Methods)
• __init__() - Constructor Method • __str__() - String Representation • __add__() - Operator Overloading Magic Method Description Example Usage
• Called when an object is created. • Provides a user-friendly string representation of an object. • Enables the + operator to be customized for user-defined __new__(cls,
Creates a new instance (constructor) obj = MyClass()
[...])
• Used to initialize instance variables. • Called when print() or str() is used. classes.
[Link] __init__(self,
[Link] Initializes the instance obj = MyClass(args)
[Link] [...])
1 class Student: 1 class Point:
1 class Student: 2 def __init__(self, x, y): __del__(self) Destructor (cleanup before deletion) del obj

String Representation
2 def __init__(self, name, roll):
2 def __init__(self, name, roll): 3 [Link] = name 3 self.x = x
3 [Link] = name 4 [Link] = roll 4 self.y = y
4 [Link] = roll 5 5 def __add__(self, other): __str__(self) Informal string representation str(obj), print(obj)
5 6 def __str__(self): 6 return Point(self.x + other.x, self.y + other.y)
6 student1 = Student("Ravi", 101) 7 return f"Student(Name: {[Link]}, Roll: {[Link]})" 7 def __str__(self): __repr__(self) Official string representation repr(obj), console
7 print([Link]) 8 return f"({self.x}, {self.y})"
8
9 __format__(self,
Custom string formatting format(obj, spec)

Methods
9 student1 = Student("Ravi", 101)
10 print(student1) # Output: Student(Name: Ravi, Roll: 101) 10 p1 = Point(1, 2) format_spec)
11 p2 = Point(3, 4)
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, 12 p3 = p1 + p2 DEPARTMENT OF APPLIED PHYSICS,
__bytes__(self) Byte representation
DEPARTMENT OF APPLIED PHYSICS,
bytes(obj)
EVEN SEMESTER 541 EVEN SEMESTER 542 EVEN SEMESTER 543 EVEN SEMESTER 544
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA 13 print(p3) # Output: (4, 6)
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Magic Methods (Dunder Methods) Magic Methods (Dunder Methods) Magic Methods (Dunder Methods) Class Method
Magic Method Description Example Usage Magic Method Description Example Usage • Bound to the class and not the instance of the class
Magic Method Description Example Usage __add__(self, other) + Addition __len__(self) Returns length len(obj)

Arithmetic Operations
• Modify a class state that applies across all instances of the class.
Comparison Operators

__eq__(self, other) == Equality check __sub__(self, other) - Subtraction __getitem__(self, key) Access item by key/index obj[key]
• Defined using the @classmethod decorator.
__ne__(self, other) != Inequality check __mul__(self, other) * Multiplication __setitem__(self, key, value) Set item by key/index obj[key] = value
__truediv__(self, other) / Division (float) __delitem__(self, key) Delete item by key/index del obj[key] • Takes cls as the first argument (instead of self), which refers to the
__lt__(self, other) < Less than class itself.
__floordiv__(self, other) // Floor division Check if item exists
__gt__(self, other) > Greater than __contains__(self, item) item in obj
(in operator)
__mod__(self, other) % Modulus • Can access or modify class variables but not instance variables.
__le__(self, other) <= Less than or equal __pow__(self, other) ** Exponentiation __iter__(self) Returns iterator for x in obj
__next__(self) Next item in iteration next(obj)
• Can be called using [Link]() or [Link]().
__ge__(self, other) >= Greater than or equal __add__(self, other) + Addition
__len__(self) Returns length len(obj) • Commonly used for factory methods, where the method returns an
instance of the class.

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 545 EVEN SEMESTER 546 EVEN SEMESTER 547 EVEN SEMESTER 548
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Class Method Class Methods Class Methods Class Methods


___.py
1
2
class School:
school_name = "Green Valley High" # Class variable
Static Methods Class Methods Static Methods Class Methods Static Methods Class Methods
3 • Methods within a class that do not have • Methods that can access class-level variables class MathOperations: class Employee: class myClass: class myClass:
4 @classmethod access to instance (self) or class (cls) data. and methods, but not instance attributes
directly. @staticmethod company_name = "TechCorp" def __init__(self): count = 0
5 def change_name(cls, new_name): • Bound To: The class, not any specific object def add(x, y): self.x = x
6 cls.school_name = new_name # Modifying class variable instance. • Bound To: The class, not a specific object.
7 return x + y @classmethod def __init__(self):
8 @classmethod • Accessibility: Cannot modify or access • Accessibility: Can access and modify class @staticmethod
instance attributes or class variables. variables or call other class methods. def change_company_name(cls, self.x = x
9 def show_name(cls): # Accessing via class name def staticMethod():
10 print(f"School Name: {cls.school_name}") • Purpose: Generally used for utility functions • Purpose: Often used to define factory methods print([Link](10, 5)) new_name): return ("i am a static method“)
11 or functions that logically belong to the class or modify class state. cls.company_name = new_name # @classmethod
12 # Accessing class method using class name but don’t use or modify any instance or class-
level data. • Decorator: @classmethod Modifies class-level attribute # Notice staticMethod does not require def classMethod(cls):
13 School.show_name() # Output: School Name: Green Valley High
14 • Takes: The cls argument which refers to the the self parameter [Link] += 1
• Decorator: @staticmethod
15 # Changing the school name class itself. # Accessing via class name
16 School.change_name("Blue River Academy") • Cannot: Access any instance attributes or
class attribut • Can: Alter the class state, but not instance- Employee.change_company_name("InnovaTech") # The classMethod can access and modify
17 School.show_name() # Output: School Name: Blue River Academy specific data.
print(Employee.company_name) class variables. It takes the class name
as a required parameter

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 549 EVEN SEMESTER 550 EVEN SEMESTER 551 EVEN SEMESTER 552
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Class Methods Complete Point Class Complete Student Class String Objects
[Link] [Link]
1 from math import * 1 class Student:
2 2 school_name = "Green Valley High" # Class variable • Objects bundle data and functions together, and the data
Static Methods Static Methods
class Calculator:
3
4
class Point:
def __init__(self, x, y):
3
4 def __init__(self, name, age): that comprise a string
class Calculator: 5 self.x = x 5 [Link] = name
6 self.y = y 6 [Link] = age name = input("Please enter your name:") Please enter your name: Shyam
def addNumbers(x, y): # create addNumbers static method 7 7 Hello SHYAM, how are you?
print("Hello " + [Link]() + ", how are you?")
return x + y @staticmethod 8 def distance_from_origin(self): 8 @classmethod
9 return sqrt(self.x * self.x + self.y * self.y) 9 def set_school_name(cls, name):
# create addNumbers static method
def addNumbers(x, y):
return x + y
10
11 def distance(self, other):
10
11
cls.school_name = name # Modifying class variable • The expression [Link]() within the print statement
[Link]
staticmethod([Link])
=
12 dx = self.x - other.x 12 @staticmethod represents a method call
13 dy = self.y - other.y 13 def is_adult(age):
print('Product:',
14 return sqrt(dx * dx + dy * dy) 14 return age >= 18
print('Product:', [Link](15, 110)) 15 15
[Link](15, 110)) 16 def translate(self, dx, dy): 16 # Class Method
17 self.x += dx 17 Student.set_school_name("Blue River Academy")
18 self.y += dy 18 print(Student.school_name) # Output: Blue River Academy
19 19
20 def __str__(self): 20 # Static Method
21 return "(" + str(self.x) + ", " + str(self.y) + ")" 21 print(Student.is_adult(20)) # Output: True
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 553 EVEN SEMESTER 554 EVEN SEMESTER 555 EVEN SEMESTER 556
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
String Objects String Objects String Objects File Objects
>>> 'aBcDeFgHiJ'.upper()
'ABCDEFGHIJ’
s = "ABCDEFGHIJK“
print(s)
• The data obtain after the end of execution, are not available
>>> 'This is a sentence.'.rjust(25, '-') for i in range(len(s)): for future
'------This is a sentence.
• object is an expression that represents object
print("[", s[i], "]", sep="", end="")

>>> s = 'ABCEFGHI’
print() # Print newline • Python’s standard library has a file class to make objects
• name is a reference to a string object. >>> s
for ch in s:
that can store or append data to, and retrieve data from,
print("<", ch, ">", sep="", end="")
• The period, pronounced dot, associates an object expression 'ABCEFGHI’
print() # Print newline disk
with the method to be called >>> s.__getitem__(0)
'A’
• Formal name of the class of file objects TextIOWrapper, and
• methodname is the name of the method to execute. >>> s.__getitem__(1)
‘B’ it is found in the io module
• The parameterlist is comma-separated list of parameters to the
method
• May empty but required

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 557 EVEN SEMESTER 558 EVEN SEMESTER 559 EVEN SEMESTER 560
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

File Objects File Objects File Objects 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

• The functions and classes defined in the io module are available • Once have a file object capable of writing (opened with 'w' • Every call to the open function should have a """
create or consume files of numbers. """

to any program, and no import statement is required or 'a’), save data to the file associated with that file object corresponding call to the file object’s close method.
def load_data(filename):
""" Print the elements stored in the text file named filename. """
done = False
while not done:
• f = open('[Link]', 'r’) Default value
using the write method. # Open file to read
cmd = input('S)ave L)oad Q)uit: ')

• creates and returns a file object (literally a TextIOWrapper object) named with open('[Link]') as f: # f is a file object with open(filename) as f: # f is a file object
if cmd == 'S' or cmd == 's':

f • For a file object named f, the statement [Link]('data') for line in f: # Read each line as text
for line in f: # Read each line as text
store_data(input('Enter file name:'))

• The first argument to open is the name of the file, and the second
print(int(line)) # Convert to integer and append to the list
elif cmd == 'L' or cmd == 'l':
print([Link]()) # Remove trailing newline character
argument is a mode. f = open('[Link]’, ‘w’) f = open('[Link]', 'w') f = open('[Link]', 'r')
# No need to close the file def store_data(filename):
load_data(input('Enter filename:'))

• The open function supports the following modes:


elif cmd == 'Q' or cmd == 'q':
[Link]('data’) [Link]('data\n') """ Allows the user to store data to the text file named filename. """
done = True
• 'r' opens the file for reading; raise an exception, if the file does not exist or the user of the [Link]('compute’) [Link]('compute\n') for line in f: with open(filename, 'w') as f: # f is a file object

program does not have adequate permissions to open the file [Link]('process’) [Link]('process\n’) print([Link]()) number = 0
if __name__ == '__main__':
• 'w' opens the file for writing; creates a new file; any pre-existing data in the file [Link]() [Link]() [Link]()
while number != 999: # Loop until user provides magic number
main()
will be lost number = int(input('Please enter number (999 quits):'))

• 'a' opens the file to append data to it; new data will be appended remove the
trailing newline
if number != 999:
[Link](str(number) + '\n') # Convert integer to string to save
('\n') character
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, else: DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 561 EVEN SEMESTER 562 EVEN SEMESTER 563 EVEN SEMESTER 564
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA break # Exit loop UNIVERSITY OF CALCUTTA

Fraction Objects Operator Overloading Problem Statement: Problem Statement:


• The fractions module provides the Fraction class
• Fraction objects model mathematical rational numbers; that is, the ratio of two integers.
• operator overloading: You can define functions so that • Create a Student Management System that allows: Algorithm
• The statement, Python's built-in operators can be used with your class. • Adding student details (name, roll, marks). [Link]
• f1 = Fraction(3, 4) • See also: [Link] [Link] a base class Student with:
• Creates a Fraction object and assigns the variable f1 to the object.
• The expression Fraction(3, 4) calls a class constructor.
• Viewing details of each student. •Attributes: name, roll, marks.
• Class constructors allow clients to supply data used in the formation of a new object. Operator Class Method Operator Class Method
• Calculating grades based on marks. •Methods: __init__(), calculate_grade(), display_info().
- __neg__(self, other) == __eq__(self, other)
[Link] a subclass GraduateStudent inheriting from Student.
+ __pos__(self, other) != __ne__(self, other) • Displaying all students' data. •Additional Attribute: thesis_title.
Two attributes, __add__, addition: f1.__add__(f2) is equivalent to f1+f2
numerator and
denominator
__mul__, multiplication: f.__mul__(g) is equivalent to f * g
* __mul__(self, other) < __lt__(self, other)
• Demonstrating inheritance by creating a subclass for •Override the display_info() method to include thesis details.
/ > __gt__(self, other)
GraduateStudent.
__truediv__(self, other)
__eq__, relational quality: f.__eq__(g) is equivalent to f == g [Link] student objects and demonstrate method calls.
Unary Operators <= __le__(self, other)
__gt__, greater than: f.__gt__(g) is equivalent to f > g
- __neg__(self)
[Link] polymorphism using overridden methods.
>= __ge__(self, other)
[Link]
__sub__, subtraction: f.__sub__(g) is equivalent to f – g
__neg__, unary minus: f.__neg__() is equivalent to -f + __pos__(self)

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 565 EVEN SEMESTER 566 EVEN SEMESTER 567 EVEN SEMESTER 568
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Problem Statement: File Objects


# Base Class
File Objects Exercise
class Student: # Subclass (Inheritance Example)
def __init__(self, name, roll, marks): class GraduateStudent(Student):
Algorithm [Link] = name # Instance variable def __init__(self, name, roll, marks, thesis_title): • Problem 1: Library Management System (Encapsulation, Inheritance)
[Link] = roll # Instance variable super().__init__(name, roll, marks) # Inheriting attributes from Student
[Link] [Link] = marks # Instance variable self.thesis_title = thesis_title # New attribute for GraduateStudent • Problem Statement:
[Link] a base class Student with: # Method Overriding • Create a base class Book with attributes:
def calculate_grade(self):
•Attributes: name, roll, marks. if [Link] >= 90: def display_info(self):
• title, author, price.
super().display_info() # Calling the parent class method
•Methods: __init__(), calculate_grade(), display_info(). return 'A+'
print(f"Thesis Title: {self.thesis_title}")
elif [Link] >= 80: • Create a subclass LibraryBook that adds:
[Link] a subclass GraduateStudent inheriting from Student. return 'A'
# Creating Objects (Encapsulation)
elif [Link] >= 70: • book_id, availability_status.
•Additional Attribute: thesis_title. return 'B' student1 = Student("Ravi", 101, 85)
•Override the display_info() method to include thesis details. elif [Link] >= 60: student2 = GraduateStudent("Priya", 102, 92, "Machine Learning in Healthcare") • Implement methods to:
return 'C'
[Link] student objects and demonstrate method calls. else: # Displaying Information (Polymorphism) • Display book details.
student1.display_info()
[Link] polymorphism using overridden methods. return 'F'
student2.display_info() • Check availability status.
[Link] def display_info(self):
print(f"\nName: {[Link]}") • Borrow a book (changes availability status).
print(f"Roll Number: {[Link]}")
EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
569 EVEN
print(f"Marks: {[Link]}")
SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
570 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
571 EVEN SEMESTER
DEPARTMENT OF APPLIED PHYSICS,
572
UNIVERSITY OF CALCUTTA print(f"Grade: {self.calculate_grade()}")
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA
Special Class Methods Example: Create Bank Acc Object Handling Exception Generating Exceptions
• In addition to normal class methods, there are a number of # Python program to create Bankaccount class def withdraw(self):
amount = float(input("Enter amount to be • Python has its own exception handle routine raise ExceptionType("message")
# with both a deposit() and a withdraw()
special methods which Python classes can define. function
Withdrawn: "))
• But programmer can write its own also by using try-except
class Bank_Account:
if [Link]>=amount:
• useful when the client uses your object improperly
• Instead of being called directly by our code (like normal statement
[Link]-=amount
def __init__(self): print("\n You Withdrew:", amount) • types: ArithmeticError, AssertionError, IndexError, NameError,
methods), special methods are called for you by Python in [Link]=0
print("Hello!!! Welcome to the Deposit
else:
print("\n Insufficient balance ")
try: $ python try_except.py SyntaxError, TypeError, ValueError
particular circumstances or when specific syntax is used. & Withdrawal Machine")
text = input('Enter something --> ‘) Enter something --> # Press ctrl-d
def display(self):
except EOFError: Why did you do an EOF on me? • Example:
• We can get and set items with a syntax that doesn't include
print("\n Net Available
def deposit(self): Balance=",[Link]) $ python try_except.py
print('Why did you do an EOF on me?’) class BankAccount:
explicitly invoking methods. amount=float(input("Enter amount to be
Deposited: ")) # Driver code except KeyboardInterrupt:
Enter something --> # Press ctrl-c ...
[Link] += amount print('You cancelled the operation.’)
You cancelled the operation. def deposit(self, amount):
# creating an object of class
print("\n Amount Deposited:",amount) s = Bank_Account()
$ python try_except.py if amount < 0:
else:
Enter something --> no exceptions raise ValueError("negative amount")
# Calling functions with that class object print('You entered {0}'.format(text))
You entered no exceptions ...
[Link]()
[Link]()
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
[Link]() DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 575 EVEN SEMESTER 576 EVEN SEMESTER 577 EVEN SEMESTER 578
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Handling Exception Raising Exceptions #!/usr/bin/python


Custom Types Custom Types
• Raise exceptions using # Filename: [Link]

• A software object generally bundles together data (instance • Define a custom Circle class in Python from which we can
class ShortInputException(Exception):

the raise statement by '''A user-defined exception class.'‘’

providing the name of variables) and functionality (methods) create Circle instances (objects)
def __init__(self, length, atleast):
Exception.__init__(self)

the error/exception
[Link] = length
Clients should be able to create a Circle object with a specified center
[Link] = atleast
• The instance variables and methods of an object comprise point (a tuple of two numbers) and radius. definitions appear within

its members.
try:
the block of a class
text = input('Enter something --> ‘)
An attempt to create a circle with a negative radius should produce a definition they are
if len(text) < 3:
ValueError exception. method definitions
raise ShortInputException(len(text), 3)
# Other work can continue as usual here • The class of an object defines the object’s basic structure Clients can determine a Circle object’s radius via a get_radius method.
$ python [Link]
except EOFError:
and capabilities. Clients can determine a Circle object’s center via a get_center method.
print('Why did you do an EOF on me?’)
Enter something --> a
except ShortInputException as ex:
Clients can reposition the circle via a move method.
ShortInputException: The input was 1 long, expected at least
3 print('ShortInputException: The input was {0} Clients can increase the circle’s radius by one unit via a grow method.
long, expected at least {1}’\

.format([Link], [Link])) Clients can decrease the circle’s radius by one unit via a shrink method.
$ python [Link]
else:
At no time should the circle’s radius fall below zero
Enter something --> abc
print('No exception was raised.')
No exception was raised.

DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 579 EVEN SEMESTER 580 EVEN SEMESTER 581 EVEN SEMESTER 582
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA

Practice Program

Custom Types Custom Types Custom Types def get_circumference(self):


Example: Values and Variables

Algorithm
Concepts Covered: Assigning and manipulating values
using variables.
Python Code
class Circle:
constructor initializes
""" Represents a geometric circle object """ the center and radius """ Compute and return the circumference of the circle """ • Start # Step 2: Declare variables
age = 25 # Integer
• Declare variables with different data types (integer,
• Define a custom Circle class in Python from which we can • Define a custom Circle class in Python from which we can
instance variables of from math import pi
def __init__(self, center, radius): price = 99.99 # Float
the object with radius float, string).
return 2*pi*[Link] name = "Alice" # String
parameter is
create Circle instances (objects) create Circle instances (objects)
""" Initalize the center's center and radius """
nonnegative def move(self, pt):
• Perform arithmetic operations.
# Disallow a negative radius # Step 3: Perform operations
instance variable """ Moves the enter of the circle to point pt """
• Print the values with proper formatting. age_after_5_years = age + 5
__init__: The special name of all constructors in Python classes is __init__. It must create and initialize the __init__: The special name of all constructors in Python classes is __init__. It must create and initialize the if radius < 0:
center and radius instance variables, and it must detect an attempt to make a Circle object with a center and radius instance variables, and it must detect an attempt to make a Circle object with a
names • End price_discounted = price * 0.9
raise ValueError('Negative radius') [Link] = pt
negative radius. The client code must supply a center (a tuple consisting of two numbers) and a radius. negative radius. The client code must supply a center (a tuple consisting of two numbers) and a radius. accessor methods, or
[Link] = center getters, as they give def grow(self): # Step 4: Print output
get_radius: This method simply returns the value of the radius instance variable. This method accepts get_radius: This method simply returns the value of the radius instance variable. This method accepts
no parameters. no parameters. clients access to see """ Increases the radius of the circle """ print("Name:", name)
[Link] = radius
the state of an object print("Age after 5 years:", age_after_5_years)
get_center: This method simply returns the value of the center instance variable. This method accepts get_center: This method simply returns the value of the center instance variable. This method accepts def get_radius(self): [Link] += 1
no parameters. no parameters. Mutator methods, or
print("Discounted price:", price_discounted)
get_area: This method computes and returns the circle object’s area. This method accepts no get_area: This method computes and returns the circle object’s area. This method accepts no
""" Return the radius of the circle """ setters, because they def shrink(self): Example: Swap Two Variables Without Using a Temporary Concepts Covered: Variables, Arithmetic Operators
parameters. parameters. return [Link] allow clients to modify """ Decreases the radius of the circle; Variable
the state of an object
get_circumference: This method computes and returns the circumference. This method accepts no get_circumference: This method computes and returns the circumference. This method accepts no def get_center(self): does not affect a circle with radius zero """ Algorithm Python Code
parameters. parameters.
""" Return the coordinatess of the center """ if [Link] > 0: • Start # Step 2: Take input
move: This method repositions the Circle object’s center. The client must provide a tuple consisting of two numbers. This move: This method repositions the Circle object’s center. The client must provide a tuple consisting of two numbers. This a = int(input("Enter first number: "))
tuple represents the new coordinates of the object’s center. tuple represents the new coordinates of the object’s center. return [Link] [Link] -= 1 • Take two numbers as input (a and b). b = int(input("Enter second number: "))
grow: This method increases the Circle object’s radius by one unit. This method accepts no parameters. grow: This method increases the Circle object’s radius by one unit. This method accepts no parameters. def get_area(self):
c1 = Circle((2, 4), 5)
• Swap values using arithmetic operations (+ and -).
shrink: If the Circle object’s radius is greater than zero, this method decreases its radius by one unit. This method does shrink: If the Circle object’s radius is greater than zero, this method decreases its radius by one unit. This method does """ Compute and return the area of the circle """ • Print the swapped values. # Step 3: Swap using arithmetic operations
c2 = Circle((0, 0), 1) a = a + b
not change the radius if the radius is zero before the call. This method accepts no parameters. not change the radius if the radius is zero before the call. This method accepts no parameters. from math import pi • End b = a - b
print(c1.get_radius()) a = a - b
return pi*[Link]*[Link]
DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS, DEPARTMENT OF APPLIED PHYSICS,
EVEN SEMESTER 583 EVEN SEMESTER 584 EVEN SEMESTER 585
UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA UNIVERSITY OF CALCUTTA print(c2.get_radius())

# Step 4: Print swapped values • Start • Start Algorithm Python Code


print("After swapping: a =", a, ", b =", b) # Step 2: Create a tuple # Step 2: Create a set
• Create a tuple with values. • Create a set with unique values. set1 = {1, 2, 3, 4} • Start
Example: Convert Temperature from Celsius to Concepts Covered: Variables, Arithmetic Operators, colors = ("Red", "Green", "Blue") name = "Priya"
• Access elements using indexing. • Add a new item. set2 = {3, 4, 5, 6} • Use different print formatting methods.
Fahrenheit Data Types age = 25
• Convert tuple to a list and modify it. # Step 3: Access elements • Perform set operations (union, intersection). • Print output using format() and f-strings.
Algorithm Python Code print("First color:", colors[0]) # Step 3: Modify set
• End • End • End # Using format()
• Start [Link](5)
print("My name is {} and I am {} years
• Take temperature in Celsius as input. celsius = float(input("Enter temperature in # Step 4: Convert to list and modify old.".format(name, age))
Celsius: ")) colors_list = list(colors) # Step 4: Perform set operations
• Use the formula: colors_list.append("Yellow") union_set = [Link](set2)
# Using f-strings
• 𝐹 = ( 𝐶 × 9 / 5 ) + 32 fahrenheit = (celsius * 9/5) + 32 new_tuple = tuple(colors_list) intersection_set = [Link](set2)
print(f"My name is {name} and I am {age} years
• Print the Fahrenheit value. print("Union:", union_set) old.")
print("Temperature in Fahrenheit:", fahrenheit) print("Modified tuple:", new_tuple)
• End print("Intersection:", intersection_set) Algorithm Python Code
Dictionary Operations Concepts Covered: Creating and modifying key-value
List Operations Concepts Covered: Creating, modifying, and accessing Operators Example Concepts Covered: Arithmetic, logical, and comparison • Start
pairs. name = "Priya"
lists. operators. • Use f-strings (f"") to insert variables directly.
Algorithm Python Code marks = 95.5
Algorithm Python Code Algorithm Python Code • Print formatted output.
• Start
• Start # Step 2: Create dictionary • Start • End print(f"Student: {name}, Marks: {marks}")
# Step 2: Create a list • Create a dictionary with key-value pairs. a = 10 print(f"Next year, {name} will have {marks + 5}
• Create a list with multiple values. student = {"name": "Rohan", "age": 20, "course": • Take two numbers.
fruits = ["Apple", "Banana", "Cherry"] • Access a value using a key. "Math"} b = 5 marks.")
• Append a new item to the list. • Perform arithmetic, comparison, and logical
• Add a new key-value pair. Algorithm Python Code
• Remove an item. # Step 3: Modify list
# Step 3: Access value operations. # Arithmetic Operators
[Link]("Mango") # Add item • End print("Addition:", a + b) • Start
• Sort the list and print the updated values. print("Student Name:", student["name"]) • Print results.
[Link]("Banana") # Remove item print("Multiplication:", a * b) • Use % formatting to insert values. num = 7
• End [Link]() # Sort list • End pi = 3.14159
# Step 4: Add a new key-value pair • Print formatted output.
student["grade"] = "A" # Comparison Operators
# Step 5: Print the list print("Is a greater than b?", a > b) • End print("Integer: %d" % num) # %d for integer
print("Updated list:", fruits) print("Float: %.2f" % pi) # %.2f limits to 2
print("Updated Dictionary:", student) decimal places
Tuple Operations Concepts Covered: Immutable data structures and Set Operations
# Logical Operators
Concepts Covered: Unique values and set operations. print("Both are non-zero?", a > 0 and b > 0) Algorithm Python Code
indexing.
Algorithm Python Code Print Formatting Methods Concepts Covered: Formatting output using format(), f-strings. • Start
Algorithm Python Code
• Use :.nf inside f-strings to control decimal places. pi = 3.1415926535 • End 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) • Generate a list of squares. # List of squares
print("Dictionary of Squares:", squares_dict) squares = [x**2 for x in range(1, 6)]
• Print formatted output. print(f"Rounded to 2 decimals: {pi:.2f}")
and values are their squares. • Convert the list into a dictionary with values as
• End print(f"Rounded to 4 decimals: {pi:.4f}") Nested List Comprehension: Matrix Transposition Concepts Covered: Handling 2D lists. • Print the dictionary. cubes. # Dictionary with cubes
Algorithm Python Code Algorithm Python Code • End • Extract unique values using a set comprehension. cubes_dict = {x: x**3 for x in squares}
• Start • Start Dictionary Comprehension: Word Length Mapping Concepts Covered: Working with strings and dictionary • End # Extract unique values using set comprehension
matrix = [
• Use <, >, and ^ inside f-strings for alignment. text = "Python" • Define a 3x3 matrix. comprehension. unique_values = {v for v in cubes_dict.values()}
[1, 2, 3],
• Print formatted output. • Transpose the matrix using nested list [4, 5, 6], Algorithm Python Code
print(f"Left aligned: {text:<10}") # Left- print("Squares:", squares)
• End aligned comprehension. [7, 8, 9] • Start print("Cubes Dictionary:", cubes_dict)
]
print(f"Right aligned: {text:>10}") # Right- • Print the new matrix. • Create a dictionary where keys are words and words = ["apple", "banana", "cherry"] print("Unique Values:", unique_values)
aligned word_lengths = {word: len(word) for word in
• End # Transpose using nested list comprehension values are their lengths. words} Problem Statement: Create a Python program to manage
print(f"Center aligned: {text:^10}") # Center-
aligned
transposed_matrix = [[row[i] for row in matrix] • Print the dictionary. student records, including:
for i in range(len(matrix[0]))] • End print("Word length mapping:", word_lengths)
Algorithm Python Code Algorithm Python Code
• Start print("Transposed Matrix:", transposed_matrix) • Start
Dictionary Comprehension: Swap Keys and Values Concepts Covered: Reversing dictionaries. # Step 2: Create an empty list to store student
• Use sep="delimiter" to change default space # Using sep Example: Create a List of Even Numbers Using List Concepts Covered: List Comprehension • Create an empty list to store student records. records
separation. print("Apple", "Banana", "Cherry", sep=" | ") Comprehension Algorithm Python Code • Take multiple student inputs using a loop. students = []
• Use end="custom_end" to change newline Algorithm Python Code • Start • Store name, age, and marks in a dictionary inside a
# Using end # Step 3: Define subjects as a set
behavior. print("Hello", end="... ") • Start • Create a dictionary with some key-value pairs. original_dict = {"a": 1, "b": 2, "c": 3} list.
swapped_dict = {v: k for k, v in subjects = {"Math", "Science", "English"}
• End print("World!") • Use a list comprehension to generate even even_numbers = [num for num in range(1, 21) if • Swap keys and values using dictionary original_dict.items()} • Use operators to calculate total and percentage.
num % 2 == 0]
List & Dictionary Comprehensions Concepts Covered: Efficient list and dictionary creation. numbers from 1 to 20. print("Even numbers:", even_numbers)
comprehension. • Find the student with the highest marks using # Step 4: Take input for multiple students
• Print the new dictionary. print("Swapped dictionary:", swapped_dict) num_students = int(input("Enter number of
Algorithm Python Code • Print the list. max().
students: "))
• Start • End • End • Use a set to store unique subjects.
• Create a list of squares using list comprehension. # List Comprehension Dictionary Comprehension: Square of Numbers Concepts Covered: Dictionary comprehension. Combining Multiple Comprehensions Concepts Covered: List, dictionary, and set • Sort student names alphabetically. for _ in range(num_students):
squares = [x ** 2 for x in range(1, 6)]
Algorithm Python Code comprehension together. • Display results using formatted printing. name = input("Enter student name: ")
• Create a dictionary of squares using dictionary print("List of Squares:", squares) age = int(input("Enter age: "))
comprehension. • Start Algorithm Python Code • End
# Dictionary Comprehension squares_dict = {x: x ** 2 for x in range(1, 6)} • Start # Taking marks as dictionary inside list

Code for Python 3.x Code for Python 3.x

Operation on list
update() Updates the dictionary with the [Link](iterable)
marks = {subject: int(input(f"Enter marks Python has a set of built-in methods that you can use on dictionaries. specified key-value pairs
for {subject}: ")) for subject in subjects} # Step 9: Display student details with formatted A dictionary is a collection which is ordered, changeable and does not allow duplicates. As of
output Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries value() Returns a list of all the values in the [Link]()
# Step 5: Calculate total and percentage print("\n--- Student Records ---") are unordered. dictionary
total_marks = sum([Link]()) for student in students:
percentage = total_marks / len(subjects) # print(f"\nName: {student['name']:10} Age: Method Description Syntax
Assuming equal weight for each subject {student['age']:3} Total: {student['total']:3} 1) Create and print a dictionary:

Percentage: {student['percentage']:.2f}%") thisdict = {


clear() Removes all the elements from the [Link]() "brand": "Ford",
# Store student details in a dictionary dictionary "model": "Mustang",
student = { # Display the topper "year": 1964
}
"name": name, print("\n Topper Details ") print(thisdict)
copy() Returns a copy of the dictionary [Link]()
"age": age,
print(f" Name: {topper['name']} Percentage: 2) Get the value of the "model" key:
"marks": marks, {topper['percentage']:.2f}%") thisdict = {
"total": total_marks, fromkeys() Returns a dictionary with the specified [Link](keys, value)
"brand": "Ford",
"percentage": percentage # Display unique subjects and sorted names
keys and value "model": "Mustang",
} "year": 1964
print("\nUnique Subjects:", unique_subjects) }
get() Returns the value of the specified key [Link](keyname, value) x = thisdict["model"]
print("Sorted Student Names:", sorted_students)
[Link](student) x = [Link]("model") # Using get() function
items() Returns a list containing a tuple for [Link]() x = [Link]() # print list of keys
# Step 6: Find the student with the highest marks each key value pair
3) Add a new item to the original dictionary, and see that the keys list gets updated as
using max() well:
highest_percentage = max([student["percentage"]
keys() Returns a list containing the [Link]() car = {
for student in students]) dictionary's keys "brand": "Ford",
topper = [student for student in students if "model": "Mustang",
"year": 1964
student["percentage"] == highest_percentage][0] }
pop() Removes the element with the [Link](keyname,
specified key defaultvalue)
# Step 7: Use set comprehension to store unique x = [Link]()

subjects print(x) #before the change


unique_subjects = {sub for sub in subjects} popitem() Removes the last inserted key-value [Link]()
pair car["color"] = "white"

# Step 8: Sort student names alphabetically print(x) #after the change


sorted_students = sorted([student["name"] for setdefault() Returns the value of the specified key. [Link](keyname,
4) Update the "year" of the car by using the update() method:
If the key does not exist: insert the value)
student in students]) thisdict = {
key, with the specified value
"brand": "Ford",
"model": "Mustang",

Code for Python 3.x Code for Python 3.x Code for Python 3.x Code for Python 3.x

"year": 1964 "brand": "Ford", Operation on list 1) Create a List:


}
[Link]({"year": 2020}) # Using update "model": "Mustang", thislist = ["apple", "banana", "cherry"]
Python has a set of built-in methods that you can use on lists/arrays. print(thislist)
thisdict["year"] = 2018 "year": 1964
} 2) Print the number of items in the list:
5) Adding an item to the dictionary is done by using a new index key and assigning a Method Description Syntax
for x in thisdict: thislist = ["apple", "banana", "cherry"]
value to it:
print(len(thislist))
thisdict = { print(x)
"brand": "Ford", append() Adds an element at the end of the list [Link](elmnt) 3) Using list() constructor
"model": "Mustang", for x in thisdict:
print(thisdict[x]) thislist = list(("apple", "banana", "cherry")) # note the
"year": 1964 double round-brackets
} for x, y in [Link](): clear() Removes all the elements from the list [Link]() print(thislist)
thisdict["color"] = "red"
print(thisdict) print(x, y) 4) Print the second item of the list:
[Link]({"color": "red"}) # Using update function 8) Create a dictionary that contain three dictionaries: copy() Returns a copy of the list [Link]() thislist = ["apple", "banana", "cherry"]
print(thislist[1])
6) Remove an item: myfamily = { 5) Change the second item:
"child1" : { count() Returns the number of elements with the specified [Link](value)
thisdict = { thislist = ["apple", "banana", "cherry"]
"name" : "Ram", value
"brand": "Ford", thislist[1] = "blackcurrant"
"year" : 2004
"model": "Mustang", print(thislist)
},
"year": 1964
"child2" : {
} extend() Add the elements of a list (or any iterable), to the [Link](iterable) 6) Using the append() method to append an item:
"name" : "Shayam",
[Link]("model") end of the current list
"year" : 2007 thislist = ["apple", "banana", "cherry"]
print(thisdict)
}, [Link]("orange")
"child3" : { print(thislist)
"name" : "Jadu", index() Returns the index of the first element with the [Link](elmnt)
thisdict = { "year" : 2011 specified value 7) Insert an item as the second position:
"brand": "Ford", }
"model": "Mustang", thislist = ["apple", "banana", "cherry"]
} [Link](1, "orange")
"year": 1964
} insert() Adds an element at the specified position [Link](pos, elmnt) print(thislist)
[Link]() # popitem() method removes the last inserted 8) Add the elements of tropical to this list
item
print(thisdict) pop() Removes the element at the specified position [Link](pos) thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
[Link](tropical)
thisdict = { remove() Removes the first item with the specified value [Link](elmnt) print(thislist)
"brand": "Ford",
"model": "Mustang", 9) Remove an item:
"year": 1964 reverse() Reverses the order of the list [Link]() thislist = ["apple", "banana", "cherry"]
}
[Link]("banana")
del thisdict["model"]
print(thislist)
print(thisdict)
sort() Sorts the list [Link](reverse=True|False,
del thisdict # delete whole dictionary key=myFunc)
thislist = ["apple", "banana", "cherry"]
7) Print the keys and values using for loop
[Link](1)
thisdict = { print(thislist)

Code for Python 3.x Code for Python 3.x Code for Python 3.x Code for Python 3.x

[Link](i) Operation on tuple b)


thislist = ["apple", "banana", "cherry"] print(l1) thistuple = ("apple", "banana", "cherry")
del thislist[0] Python has a set of built-in methods that you can use on tuple. for i in range(len(thistuple)):
print(thislist) 15) Program to print duplicates from a list of integers: print(thistuple[i])
10) Clear the list content: 7) Join two tuples:
from collections import Counter Method Description Syntax
thislist = ["apple", "banana", "cherry"] tuple1 = ("a", "b" , "c")
l1 = [1,2,1,2,3,4,5,1,1,2,5,6,7,8,9,9]
[Link]() tuple2 = (1, 2, 3)
print(thislist) d = Counter(l1) count() Returns the number of times a specified value [Link](value)
print(d) occurs in a tuple tuple3 = tuple1 + tuple2
11) Create a list of squares: print(tuple3)
new_list = list([item for item in d if d[item]>1])
squares = [] 8) Return the number of times the value 5 appears in the tuple:
print(new_list) index() Searches the tuple for a specified value and [Link](value)
for x in range(10): returns the position of where it was found thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
[Link](x**2) 16) Given a List, extract all elements whose frequency is greater than K.
x = [Link](5)
# initializing list
12) Program to check if the Given List is in Ascending Order or Not 1) Create a tuple: print(x)
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
list1 = [1, 2, 3, 5, 4, 8, 7, 9] thistuple = ("apple", "banana", "cherry") 9) Search for the first occurrence of the value 8, and return its position:
# printing string print(thistuple)
temp_list = list1[:] thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
print("The original list : " + str(test_list)) 2) Print the number of items in the tuple:
[Link]()
# initializing K thistuple = ("apple", "banana", "cherry") x = [Link](8)
if temp_list == list1: print(len(thistuple))
K = 2 print(x)
print("Given List is in Ascending Order") 3) Using tuple() constructor:
res = [] 10) Test if tuple is distinct:
else: thistuple = tuple(("apple", "banana", "cherry")) # note the double
for i in test_list: # initialize tuple
print("Given List is not in Ascending Order") round-brackets
# using count() to get count of elements print(thistuple) test_tup = (1, 4, 5, 6, 1, 4)
13) Program to Find Even Numbers from a List freq = test_list.count(i) 4) Print the second item of the tuple: # printing original tuple
list2 = [2, 3, 7, 5, 10, 17, 12, 4, 1, 13] # checking if not already entered in results thistuple = ("apple", "banana", "cherry") print("The original tuple is : " + str(test_tup))
if freq > K and i not in res: print(thistuple[1]))
for i in list2: # Test if tuple is distinct
[Link](i) 5) Extract the values back into variables: unpacking
if i % 2 == 0: # Using loop
print(i) # printing results fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits res = True
print("The required elements : " + str(res)) print(green)
14) Program to Subtract a List from Another List temp = set()
print(yellow)
print(red) for ele in test_tup:
a = [1, 2, 3, 5]
6) Iterate through the items and print the values: if ele in temp:
b = [1, 2]
a) res = False
l1 = []
thistuple = ("apple", "banana", "cherry") break
for i in a: for x in thistuple:
print(x) [Link](ele)
if i not in b:
# 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))

You might also like