Python Small
Python Small
• 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.
%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
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
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']
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
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
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
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
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
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
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
✓
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
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
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
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
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
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
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
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: ")
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
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
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}
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
• 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
• 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
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
• [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)
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.
✓ ✓
• 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()
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]
• 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
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
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))
• 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
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):
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('------------------------')
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)
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
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"))
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
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
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
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
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
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
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
• 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:'))
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
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
• A software object generally bundles together data (instance • Define a custom Circle class in Python from which we can
class ShortInputException(Exception):
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
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())
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:
Code for Python 3.x Code for Python 3.x Code for Python 3.x Code for Python 3.x
Code for Python 3.x Code for Python 3.x Code for Python 3.x Code for Python 3.x