Notes Pythom Anits Mech r20 Sllbus by Phani
Notes Pythom Anits Mech r20 Sllbus by Phani
Installa on:
Keywords Description
This is a logical operator which returns true if both the operands are
and
true else returns false.
Else is used with if and elif conditional statements. The else block is
else
executed if the given condition is not true.
Keywords Description
Identifiers:
Python Identifier is the name we give to identify a variable, function,
class, module or other object. That means whenever we want to give
an entity a name, that's called identifier.
Identifier is a user-defined name given to a variable, function, class,
module, etc.
Variables
A python variable is a symbolic name that is reference or pointer to an
object. Once an object is assigned to a variable, you can refer to the
object by that name. But the data itself is s ll contained within the
object.
The most commonly used methods of construc ng a mul word
variable name are the following three examples.
1. Camel case
Ex:- mightyMechanicalEngineering
2. Pascal case - Iden cal to camel case except the first word is also
capital
Ex:- MightyMechanicalEngineering
3. Snake case – mighty_mechanical_engineering
Comments:
Single line comments
Mul line comments
Indenta on:
Indenta on means spaces at the beginning of code line.
Python uses indenta on to indicate a block of code.
In other languages the indenta on in code is only for readability, the
indenta on in python is very imp.
Python will give error if you skip the indenta on. No of spaces is upto
programmer. But it should at least one.
Note:
We should use same no of spaces for all lines in same block of code.
No of spaces is user choice. Even one space, it will work
What is Statement in Python
A Python statement is an instruction that the Python interpreter can execute.
There are different types of statements in Python language as Assignment
statements, Conditional statements, Looping statements, etc. The token character
NEWLINE is used to end a statement in Python. It signifies that each line of
a Python script contains a statement. These all help the user to get the required
output.
Constants:
In Python, constants are usually declared and assigned in a module. Here, the
module is a new file containing variables, func ons etc. which is imported to the
main file.
Inside the module constants are wri en in all CAPITAL_LETTERS and underscores
separa ng the words.
Example:
1. Create a file name as constantmechc.py
2. PI=3.14, GRAVITY=9.81
3. Create a main.py (Program File)
Import constantmechc
print(constantmechc.PI)
print(constantmechc.GRAVITY)
Literals:
Literals means a constant
Generally, literal are a nota on for represen ng a fixed value in source
code. They can also be defined as raw value or data given in variables or
constants.
#Numeric Literals
Here, 20,24.5, 2+3j are considered as literals.
Python has different types of literals
1. String literals
2. Numeric Literals
3. Boolean Literals
4. Literal Collec ons
5. Special literals
6. Complex Literals
DATA Types:
For user defined modules refer constants topic, which is already discussed
above.
>>>help(math) to get more details about the math module in python
>>>import sys
>>>sys.path
>>>import from math as mt
>>>mt.pi
Operators: Operator is used to perform opera ons on data
Types of operators:
Arithme c operators,
Comparison operators,
Logical operators,
Bitwise operators,
Assignment operators,
Iden ty operators,
Membership operators
Assignment Operator:
Arithme c operators:
It is used to perform the mathema cal opera ons.
+ is for addi on
- is for subtrac on
* is for mul plica on
/ is for division
// floor division
% modula on
Arithme c – Assignment Operators:
Rela onal Operators: Rela onal operator checks a condi on and return
Boolean value. (True/False) < (Less than), > (Greater Than)
10<5
False
5<10
True
Logical Operators: A logical operator checks mul ple condi ons at a me and
return bool value. (True or False)
‘and’ logical operator: It will return True, when all the given condi on are
True otherwise it returns False.
‘or’ logical operator: It will return True, when at least one condi on is True
within given condi ons. Otherwise, it will return False.
Bitwise operators:
In Python, bitwise operators are used to perform bitwise calculations on
integers. The integers are first converted into binary and then operations are
performed on each bit or corresponding pair of bits, hence the name bitwise
operators. The result is then returned in decimal format.
Bitwise
~ NOT
inverts individual bits ~x
Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a & b = 1010
&
0100
= 0000
= 0 (Decimal)
Bitwise or operator Returns 1 if either of the bit is 1 else 0.
Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a | b = 1010
|
0100
= 1110
= 14 (Decimal)
Name Space and Scope:
What is Scope?
1. Local Scope:
Contains names defined inside the current func on.
2. Global Scope:
Contains names defined at the top level of the script or module
3. Enclosing Scope:
Contains names defined inside any and all enclosed func on.
4. Built-In Scope:
Contains names built in to the python language.
Modifying the global variable in local scope:
We can’t modify global variable inside the local scope:
PYTHON PROGRAMMING
UNIT-II:
Flow control & Collections: If, If...else, if...elif...else,
Nested if, for loop, while loop, Break, Continue and Pass.
Numbers, Decimal, Fractions, Mathematics, List, Tuple,
String, Set and Dictionary. Data types manipulations
(create, Index, Negative indexing, Slicing, change or add
elements, delete or remove elements, Methods,
Comprehension, Membership Test, Iteration, Operations
and Built in Functions)
Learning Outcome: At the end of this Unit the student will be able to
• Implement Flow control statements required real world problems.
• Manipulate python programs by using the python data structures like lists,
dictionaries, tuples, strings and sets.
1. Conditional Statement:
What we can do by using conditional statement?
Ans: Using conditional statements, we can execute single statement or
multiple statements based on the condition.
2. if else:
<syntax>
if <condition>: #condition True – execute statement-1, skip else
statement-1 #condition False – skip stm-1, exe else stm-2
else:
statement-2
3. if elif
<syntax>
if <condition-1>:
Statement-1 is executed
elif <condition-2>:
Statement-2 is executed
elif <condition-3>:
Statement-3 is executed
else:
Statement-2 is executed
1. Write a python program to display list of even numbers and number of even numbers and sum
of even numbers within given range.
2. Write a python program to check given number is prime number or not.
What is prime number: A number which is divisible by 1 and itself is called as prime number.
3. Write a python program to print list of prime numbers upto given range.
4. Write a python program to print list of prime numbers upto given range in reverse order.
5. Write a python program to print odd numbers upto given range. In reverse order
Write a python program to display prime numbers in the range of 2-100
While loop:
Using while loop we can execute a set of statements as long as a condition.
While loop will execute as per given no of iterations after last iteration else part will execute.
If while loop is terminated by break then else part will not execute.
➢ Using break statement, we can stop the loop even if the while condition is true.
➢ Using continue statement, we can stop the current iteration and continue with the
next.
➢ Using else statement, we can run a block of code once when the condition is no longer
as true.
➢ Pass: Using pass we can pass from one block to another block.
Which we will use in functions.
while <condition>:
#logic
else:
#logic
Sum of even no and odd no program
The pop() method removes and returns the last item if the index is not provided. This helps us
implement lists as stacks (First in, Last out, FILO data structures). And if we have to empty the
whole list, we can use the clear() method.
Tuple:
A tuple in python is similar to a list. The difference between the two is that we
cannot change the elements of a tuple once it is assigned whereas we can change
the elements of a list.
Creating a tuple: A tuple is created by placing all the items (elements) inside
parentheses ( ), separated by commas. The parentheses are optional; however, it is
a good practice to use them.
A tuple can have any number of items and they may be of different types (integers,
float, list, string, etc.,).
Having one element within parentheses is not enough. We will need a trailing
comma to indicate that it is, in fact, a tuple.
We can also use + operator to combine two tuples. This is called concatenation.
We can also repeat the elements in a tuple for a given number of times using *
operator.
Both + and * operations result in a new tuple.
Advantages of Tuple over list:
Since tuples are quite similar to lists, both of them are used in similar situations.
However, there are certain advantages of implementing a tuple over a list. Below
listed are some of the main advantages.
➢ We generally use tuples for different data types and lists for similar data
types.
➢ Since tuples are immutable, iterating through a tuple is faster than with list.
So there is a slight performance boost.
➢ Tuples that contain immutable elements can be used as a key for a dictionary.
With lists, this is not possible.
➢ If you have data that doesn’t change, implementing it as tuple will guarantee
that it remains write-protected.
Python Dictionary:
Python Dictionary is ordered collection of items. Each item of a dictionary has a
key/value pair.
Dictionaries are optimized to retrieve values when the key is known.
Creating Python Dictionary:
Creating a dictionary is as simple as placing items inside curly braces { } separated
by commas.
An item has a key and a corresponding value that is expressed as a pair (key:value).
While the values can be of any data type and can repeat, keys must be of immutable
type (string, number or tuple with immutable elements) and must be unique.
Function Description
all() Return True if all keys of the dictionary are True (or if the dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.
Method Description
get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).
items() Return a new object of the dictionary's items in (key, value) format.
pop(key[,d]) Removes the item with the key and returns its value or d if key is not found. If d is
not provided and the key is not found, it raises KeyError.
popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the
dictionary is empty.
setdefault(key[,d]) Returns the corresponding value if the key is in the dictionary. If not, inserts the
key with a value of d and returns d (defaults to None).
update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing
keys.
Sets:
A set is an unordered collection of items. Every set element is unique (no duplicates) and must
be immutable (cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union, intersection, symmetric
difference, etc.
Creating Python Sets
A set is created by placing all the items (elements) inside curly braces { }, separated by comma,
or by using the built-in-set ( ) function.
It can have any number of items and they may of different types (integer, float, tuple, string etc.).
But a set cannot have mutable elements like lists, sets, or dictionaries as its elements.
Python Set operations:
Method Description
add() Adds an element to the set
clear() Removes all elements from the set
copy() Returns a copy of the set
difference() Returns the difference of two or more sets as a new set
difference_update() Removes all elements of another set from this set
discard() Removes an element from the set if it is a member. (Do nothing if the element is
not in set)
intersection() Returns the intersection of two sets as a new set
intersection_update() Updates the set with the intersection of itself and another
isdisjoint() Returns True if two sets have a null intersection
issubset() Returns True if another set contains this set
issuperset() Returns True if this set contains another set
pop() Removes and returns an arbitrary set element. Raises KeyError if the set is empty
remove() Removes an element from the set. If the element is not a member, raises a KeyError
symmetric_difference() : Returns the symmetric difference of two sets as a new set
symmetric_difference_update() : Updates a set with the symmetric difference of itself and another
union() Returns the union of sets in a new set,
Updates the set with the union of itself and others
Built-in Functions with Set
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used
with sets to perform different tasks.
Function Description
all() Returns True if all elements of the set are true (or if the set is empty).
any() Returns True if any element of the set is true. If the set is empty, returns False.
enumerate() Returns an enumerate object. It contains the index and value for all the items of the set as
a pair.
len() Returns the length (the number of items) in the set.
max() Returns the largest item in the set.
min() Returns the smallest item in the set.
sorted() Returns a new sorted list from elements in the set(does not sort the set itself).
sum() Returns the sum of all elements in the set.
Python Frozenset
Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed
once assigned. While tuples are immutable lists, frozensets are immutable sets.
Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand,
frozensets are hashable and can be used as keys to a dictionary.
Frozensets can be created using the frozenset() function.
This data type supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(),
issuperset(), symmetric_difference() and union(). Being immutable, it does not have methods that
add or remove elements.
Strings in Python:
A string is a sequence of characters. A character is simply a symbol. For example, the English
language has 26 characters.
Computers don’t not deal with characters; they deal with numbers(binary). Even though you may
see character on your screen, internally it is stored and manipulated as a combination of 0s and
1s.
This conversion of character to a number is called encoding, and the reverse process is decoding.
ASCII and Unicode are some of the popular encodings used.
In python, a string is a sequence of Unicode characters. Unicode was introduced to include every
character in all languages and bring uniformity in encoding. You can learn about Unicode from
python Unicode.
How to create a string in python:
Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple
quotes can be used in Python but generally used to represent multiline strings and docstrings.
Python Decimal
In Python, numbers that contain decimal points are always treated as double-precision floating-
point numbers. Decimal points have a smaller range than floats, but more precision.
Decimal modules have a precision that can be adjusted to any size necessary for a given problem,
unlike hardware-based binary floating points. By default, precision is set to 28 places. There are
some values that cannot be accurately represented by the float data type. If the 0.1 value is stored
in a float variable (binary floating-point value), we get only an approximation. In the same
way, 1/3 cannot be exactly represented in a decimal floating point.
Importing the Decimal class from the decimal module is the first statement. Next, we create two
variables called "i" and "j", each containing some values. A value is stored in the variable "k" when
i and j are divided by each other. Once the numbers have been converted to decimal types, the
process is repeated.
A round( ) function returns a floating point number with the specified number of decimals as
a rounded version of the original number. In the default case, the function returns the nearest
integer, since the number of decimals is 0.
Rounding Description
ROUND_CEILING This will round towards Infinity
ROUND_DOWN This rounds the value towards zero
ROUND_FLOOR This will round towards Infinity
ROUND_HALF_DOWN This will round to the nearest value going towards zero
ROUND_HALF_EVEN The value is rounded to the nearest even integer
ROUND_HALF_UP This will round to nearest value going away from zero
ROUND_UP This will round values away from zero
Whenever the last number is either zero or five, the number is
ROUND_05UP
rounded away from zero
Important Function in Python Decimal Module
a. exp() Function
It's pretty straightforward to follow the code sample. Numbers are rounded off with a precision
of two digits. Changing the rounding method is done via the "rounding" object (part of the
main context).
The exp() function is used to calculate the exponent value of a decimal point number, e.g. x^2
b. sqrt() Function
Sqrt() is a function that calculates and returns the square root value of the decimal number that
has been passed to it.
Syntax: decimal.Decimal(decimal-number).sqrt()
The "compare" method in the decimal module allows you to compare two
decimal-type objects. Its usage is illustrated in the following examples.
In order to compare two decimal-type objects, you must supply the other number as
an argument. Depending on the numbers being compared, a value of 0, 1, or -1 will be
returned. If the value is 0, both numbers are equal, if it is 1, the first number is greater
than the second, and if it is -1, the first number is less.
The logarithmic functions
There are some logarithmic functions in the Decimal module. Here we are
discussing about two of them. The first one is the ln() method. This method is
used to find the natural logarithm of the decimal number.
Another method is log10() method. This method is used to find the logarithmic
value where base is 10.
Example Code
#Perform ln() and log10() methods
import decimal
my_dec = decimal.Decimal(25.36)
print(my_dec)
#Find logarithmic value with base e
print('ln(x) is: ' + str(my_dec.ln()))
#Find logarithmic value with base 10
print('log(x) is: ' + str(my_dec.log10()))
Output
25.3599999999999994315658113919198513031005859375
ln(x) is: 3.233173129569025152000878282
log(x) is: 1.404149249209695070459909761
The fma() method is known as the fused multiplication and add. If we use fma(x,
y) It will compute the (number * x) + y. In this case the (number*x) part is not
rounded off.
Example Code
#Perform as_tuple() and fma() methods
import decimal
my_dec1 = decimal.Decimal(5.3)
print(my_dec1)
my_dec2 = decimal.Decimal(-9.23)
print(my_dec2)
#Show decimal as tuple
print('\nmy_dec1 as tuple: ' + str(my_dec1.as_tuple()))
print('\nmy_dec2 as tuple: ' + str(my_dec2.as_tuple()))
#Perform Fused Multiply and Add
print('\n(x*5)+8 is: ' + str(my_dec1.fma(5, 8)))
Output
5.29999999999999982236431605997495353221893310546875
-9.230000000000000426325641456060111522674560546875
Example Code
#Perform copy_abs(), copy_negate() and copy_sign()
import decimal
my_dec = decimal.Decimal(-25.36)
print(my_dec)
#copy the absolute value
temp_dec = my_dec.copy_abs()
print('Absolute is: ' + str(temp_dec))
#copy the negative value
my_dec = decimal.Decimal(7.26)
temp_dec = my_dec.copy_negate()
print('Negate of 7.26 is: ' + str(temp_dec))
#copy the sign value from second argument to first one
my_dec = decimal.Decimal(-25.36)
temp_dec = my_dec.copy_sign(decimal.Decimal(12.5))
print('Copy sign from second argument: ' + str(temp_dec))
Output
-25.3599999999999994315658113919198513031005859375
Absolute is: 25.3599999999999994315658113919198513031005859375
Negate of 7.26 is: -7.2599999999999997868371792719699442386627197265625
Copy sign from second argument:
25.3599999999999994315658113919198513031005859375
Example Code
#Perform max() and min() methods
import decimal
my_dec1 = decimal.Decimal(5.3)
print(my_dec1)
my_dec2 = decimal.Decimal(-9.23)
print(my_dec2)
#Show Minimum and Maximum
print('Minumum: ' + str(my_dec1.min(my_dec2)))
print('Maximum: ' + str(my_dec2.max(my_dec1)))
Output
5.29999999999999982236431605997495353221893310546875
-9.230000000000000426325641456060111522674560546875
Minumum: -9.230000000000000426325641456
Maximum: 5.299999999999999822364316060
Sources:
https://www.tutorialspoint.com/
https://www.geeksforgeeks.org/python-programming-language/
https://www.w3schools.com/python/
PYTHON PROGRAMMING
UNIT-III:
Functions: Function, Function argument, Recursion,
Anonymous / Lambda functions, Global, Local and
Nonlocal variables, Global keyword, Modules and
Packages.
Learning Outcome: At the end of this Unit the student will be able to
• Resolve real world problems using python functions.
• Familiarize the usage of Modules and packages to enhance the problem
solving.
Example to define a func on without parameters and not returning any value.
Returning mul ple values from a func ons:
In any programming language using a single func on we can return a single value but
in python we have a special feature called with the help of single func on we can
return mul ple values.
Ex:
Note: The number of arguments and the posi on of the argument must be matched. If we change the order
then result may be changed and if we change the number of arguments then we will get error.
Keyword Arguments:
Default Arguments:
We can pass any number of arguments to a func on such type of arguments are called as variable length
arguments.
Here x and y are the arguments and x+y is the expression that gets evaluated and
returned.
Key points:
1. Lambda func ons have no name.
2. Lambda func ons can take any number of arguments.
3. Lambda func on can return just one value in the form of an expression.
4. It always contains an expression which is returned but not return keyword.
5. They are one line version of a func on and hence cannot contain mul ple
expressions.
6. They cannot access variables other than those in their parameters.
7. Lambda func on cannot even access global variables.
Program: To find smaller of two numbers using lambda func on
In the aforemen oned code, the regular func on increment accepts a value in y. It
then passes y to a lambda func on. The lambda func on increments its value and
finally the regular func on returns the incremented value to the earlier.
You can use a lambda func on without assigning it to a variable. This is shown below.
Program: That uses a lambda func on to find the sum of first 10 natural numbers
In the above code, we have assigned a variable x to a lambda expression and then invoked the
lambda func on with empty parentheses (without arguments)
You can call a lambda func on from another lambda func on. In such a case, the lamba
funciton is said to be a nested func on. However, use of nested lambda func on must be
avoided.
Global keyword:
Built in Scope: print(“Hi”) #already defined func on in python
type()
LEGB Rule:
L means Local
E means Enclosed
G means Global
B means Built-In
Name Space in Python:
A name space is a collec on of currently defined symbolic names along with
informa on about the object that each name references.
Python Modules:
Modules are pre-wri en pieces of code that are used to perform common tasks like
genera ng random numbers, performing mathema cal opera ons, etc.
Module is a file that contains code to perform a task.
It allows you to reuse or more func ons in your programs.
A module may contain variables, func ons, classes, etc.,
Module is a file with a .py extension that has defini ons of all func ons and
variables that you would like to use even in other programs. (xxxx.py file)
The standard library modules
In the above code, we import the sys module (short of system) using the import
statement to use its func onality related to the Python interpreter and its environment.
A module imported in a program must be located and loaded into memory before it
can be used. Python first searches for the modules in the current working directory.
The from and import statements:
A module may contain defini on for many variables and func ons. When you import
a module, you can use any variable or func on defined in that module. But if you
want to use only selected variable or func ons, then you can use the from… import
statement.
Name of moule:
Every module has a name. You can find the name of a module by using the __name__
a ribute of the module.
First create a file named as main.py in python local library.
Write a set of instruc ons of a code in terms of func ons.
Import a module that named as main by using the syntax from main import *
Packages in Python:
A package is a hierarchical file directory structure that has modules and other packages
within it. Like modules, you can very easily create packages in Python.
Key points to remember:
Packages are searched for in the path specified by sys.path.
__init__.py file can be an empty file and may also be used to execute ini aliza on code
for the package or set the __all__ variable.
The import statement first checks if the item is defined in the package. If it is unable to
find it, an ImportError excep on is raised.
UNIT-IV
Learning Outcome:
At the end of this Unit the student will be able to
• Design object‐oriented programs with Python classes.
• Usage of inheritance, encapsulation, inheritance and
polymorphism for reusability.
1. What is OOPS?
Ans: OOPs stands for Object Oriented programming in system. It is a latest program
approach.
2. How many programming approaches we have?
Ans: Programming approaches are 2 types
1. Procedural Oriented approach
2. Object oriented approach
3. What is meant by procedural oriented approach?
Ans: In procedural oriented approach program is a collec on of procedures or
methods or func ons.
Example:
M1()
{
Logic
}
M2()
{
Logic
}
Main() #ini ally func on execu on is star ng from main() step-1
{
M1() #step2 will execute
M2() #step3 will execute
}
A programming language which will follow above approach that is called as
procedural oriented programming language.
Ex: C-Language.
class MyClass:
#states
#behaviours
What is state?
Ans: A field which is represen ng a value is called as state.
Sates are two types: 1. Variable 2. Constant
What is variable?
Ans: A field which represent some value but value can be changes is called as
variable.
What is Constant?
Ans: A field which represent some value but value can’t be changed is called as
constant.
In python we have 3 types of variables.
1. Local variable
2. Instance Variable
3. Sta c Variable.
What is local variable?
Ans: A variable which is declare with in the method is called as local variable.
What is behaviour?
Ans: A block which represent some func onality (logic) is called as behaviour.
Types of methods:
1. Instance method
2. Sta c method
3. Class method
Instance method Class method Sta c Method
Bound to the object of a
Bound to the class Bound to the class
class
It can modify an object It can’t modify a class or
It can modify a class state
state object state
Can access and modify Can’t access or modify
Can access only class
both class and instance the class and instance
variable
variables. variables
For Example:
Human being is a class -> Anil and Rani are objects of human being class
Employee is a class -> Gupta and Phani are objects of employee class
Car is a class -> Your car and my car are objects.
What is Instance?
Ans: Instance is nothing but physical representa on, finally we can say that object is
a physical representa on of a class.
Because of inheritance super class member can accessed by sub class but not vice-versa.
1. Single Inheritance:
Inheri ng from one class to another class is called as single inheritance.
Before going for inheritance, the following example we have to understand.
1. How to access instance method within the class?
We don’t require to create object; we can access by using self-keyword. Here self is
nothing but current class object.
2. How to call instance method outside the class
With the help of object.
3. How to access sta c method within the class.
In Python when you are accessing sta c method within the class are outside the class, we
should access with the help of class name.
If two methods are having same name with different arguments list then those
methods are called as overloaded methods.
In the above example is working for addi on opera on only 2 no’s and 3 no’s but it
is not working for other combina on. This type of method overloading is not allowed
in python.
Operator Overloading:
We can use the same operator for mul ple purpose which is nothing but operator
overloading.
Example: ‘ + ‘ operator can be used for arithme c addi on and string concatena on.
Overriding:
We have two types of method overriding
1. Method overriding
2. Constructor overriding
Method Overriding:
Reimplemen ng super class method within the sub class with the
same and same signature is called as method overriding.
Constructor Overriding:
Implemen ng the super class constructor and sub class constructor with
the same signature is called as constructor overriding.
Observa on:
When we execute the below statement. “DC ()” it will go to DC class and
it will try to invoke the DC class constructor. But within the DC class we
have ‘’’-‘’’ comment DC class constructor. But due to inheritance BC class
constructor will inherit to DC class which will execute.
UNIT-V:
Advanced topics: Iterators, Building Your Own Iterator, Infinite
Iterators, Generators, Generator Expression, Closure Function,
Decorators, @property decorator, Getters and Setters, RegEx,
Match object, datetime, Files (Open, Read, Write, Close) and File
Methods,
Learning Outcome:
At the end of this Unit the student will be able to
• Interpret the advantages of advanced concepts like iterators,
generator, decorators and regular expressions.
• Identify the commonly used operation involved in files for I/O
processing.
Iterators:
What are the iterators?
An iterator in python refers to an object that we can iterate upon.
The iterator consists of countable values, and it is possible to traverse
through these values, one by one.
With these 2 methods, the iterator is able to compute the next value in
the itera on.
Advantage of iterator: once we got the value of ‘i ‘it will not repeat
again.
Generators:
**Conclusion:
Generator func on allows you to declare a func on that
behaves like an iterator.
They make an iterator in a fast, easy and clean way.
Python generator is simple way of crea ng iterators.
The work done by iterators are automa cally handled by
generators.
Generator is a func on that return an object (iterator)
which we can iterate over (one value at a me)
Closures:
Func on within the func on called nested func on
Inner() func on outside of the func on body thrown an error.
Func on name with parenthesis is execu ng that func on defini on,
If it removes, we will return the func on reference to ‘a’ variable
So that, it means we executed this inner func on body outside its
Scope, this is the local func on (inner) we executed it outside that
func on. But, we know that we can’t call a func on outside its scope then
how we are ge ng this output.
This technique is called as Closure.
Here, func on ‘ a ‘ and inner are the same func on and we are
execu ng this func on outside its scope, this technique is called
as closure.
“The technique by which some data get a ached to the code is
called as closure” in python.
Closure:
Func on object that remembers values in the enclosing scope
even if they are not present in memory.
A er calling outer() func on ; we are calling a(), it is poin ng
towards the func on inner, we called that and we go the result
even though we finished the execu on of this outer func on then
also the message “Hi Welcome” is remembered and it is printed,
this technique is called as closure.
When do we have a closure?
What are the criteria needed to create a closure in python.
1. Nested func on
2. Nested func on must refer values in enclosing scope.
3. Enclosing func on must return nested func on.
What are the advantages of closures in python.
1. Can avoid global values
2. Data hiding
3. Implement decorators
Date and Time Module:
It will give 7 fields like Year, Month, Day, Hours, Minutes, Seconds and Micro
Seconds.
For example: 2023 11 15 10 30 40 000500
datetime ----- Module
datetime ----- class
now( ) ----- method
import datetime
datetime.datetime.now( )
Creating date: using constructor (datetime( ))
datetime( ) in the parenthesis we will pass 7 fields.
datetime.datetime(2023,11,15,10,30,40,000500)
x = datetime.datetime(2023,11,15,10,30,40,000500)
print(x) -> will get the output
strftime (parameter) --- formatting Date and Time fields
Here the parameter is a single parameter is nothing but formatting parameter.
Parameters in strftime(“Formating parameter”)
Type of parameter representation Symbol of argument Example
2 digit %y 23
Year
4 digit %Y 2023
short %b Jun
Month
full %B June
short %a Mon
Day
full %A Monday
%H 24 hrs format
Hours %I 12 hrs format
%p (AM/PM)
Minutes %M 0-59
Seconds %S 0-59
000000 to
Micro-Seconds %f
999999
Files (Open, Read, Write, Close) and File Methods:
r - read mode
*only for reading the content
*File pointer point at the beginning of the file.
* File should exist before opening in read mode
fp=open(“mechd.txt”, “r”)
mechd.txt
Welcome to the Python
Class.
w- write mode
*only for writing the content
*File pointer point at the beginning of the file.
1) If the file exists the file is opened and pointer points at
Beginning and data will be overwritten.
2) If the file doesn’t exist then new file will be created with
given file name.
fp=open(“mechd.txt”, “w”)
mechd.txt
Welcome to the Python
Class.
a - append mode
1) To append and write the data
2) File exist --- file pointer points at the end and the
content in file
3) File does’t exist --- New file will be created and file
pointer points at beginning.
fp=open(“mechd.txt”, “a”)
mechd.txt
Welcome to the Python
Class.
Access Modes:
r - Reading
w - Writing
a - Appending/writing
All these for TEXT files
r+ - Reading and writing
w+ - Reading and Writing
a+ - Reading Appending
Access Modes:
rb - Reading
wb - Writing
ab - Appending/writing
All these for BINARY files
rb+ - Reading and writing
wb+ - Reading and Writing
ab+ - Reading Appending
f1.write(string)
f1.writelines(list)
f1.read(bit positions)
mechd.txt
Welcome to the Python
Class.
.
Example: E-Mail: sphani.me@anits edu.in
def setX(self,a):
self.x=a
Note: setter name should be same as instance variable name
but instance variable name should be small case like: x
Setter name should be upper case like: X