Python Durga.pdf

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA

Overview

Download & View Python Durga.pdf as PDF for free.

More details

Language Fundamentals Introduction 

Python is a general purpose high level programming language.

Python was developed by Guido Van Rossam in 1989 while working at National Research Institute at Netherlands.

But officially Python was made available to public in 1991. The official Date of Birth for Python is : Feb 20th 1991.

Python is recommended as first programming language for beginners.

Eg1: To print Helloworld: Java: 1) public class HelloWorld 2) < 3) p s v main(String[] args) 4) < 5) SOP("Hello world"); 6) >7) > C: 1) #include 2) void main() 3) < 4) print("Hello world"); 5) >Python: print("Hello World")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

#include void main()

Python: 1) a=10 2) b=20 3) print("The Sum:",(a+b)) The name Python was selected from the TV Show "The Complete Monty Python's Circus", which was broadcasted in BBC from 1969 to 1974. Guido developed Python language by taking almost all programming features from different languages 1. Functional Programming Features from C 2. Object Oriented Programming Features from C++ 3. Scripting Language Features from Perl and Shell Script

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

4. Modular Programming Features from Modula-3 Most of syntax in Python Derived from C and ABC languages. Where we can use Python: We can use everywhere. The most common important application areas are 1. For developing Desktop Applications 2. For developing web Applications 3. For developing database Applications 4. For Network Programming 5. For developing games 6. For Data Analysis Applications 7. For Machine Learning 8. For developing Artificial Intelligence Applications 9. For IOT . Note: Internally Google and Youtube use Python coding NASA and Nework Stock Exchange Applications developed by Python. Top Software companies like Google, Microsoft, IBM, Yahoo using Python.

Features of Python: 1. Simple and easy to learn: Python is a simple programming language. When we read Python program,we can feel like reading english statements. The syntaxes are very simple and only 30+ kerywords are available. When compared with other languages, we can write programs with very less number of lines. Hence more readability and simplicity. We can reduce development and cost of the project.

2. Freeware and Open Source: We can use Python software without any licence and it is freeware. Its source code is open,so that we can we can customize based on our requirement. Eg: Jython is customized version of Python to work with Java Applications.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

3. High Level Programming language: Python is high level programming language and hence it is programmer friendly language. Being a programmer we are not required to concentrate low level activities like memory management and security etc..

4. Platform Independent: Once we write a Python program,it can run on any platform without rewriting once again. Internally PVM is responsible to convert into machine understandable form.

5. Portability: Python programs are portable. ie we can migrate from one platform to another platform very easily. Python programs will provide same results on any paltform.

6. Dynamically Typed: In Python we are not required to declare type for variables. Whenever we are assigning the value, based on value, type will be allocated automatically.Hence Python is considered as dynamically typed language. But Java, C etc are Statically Typed Languages b'z we have to provide type at the beginning only. This dynamic typing nature will provide more flexibility to the programmer.

7. Both Procedure Oriented and Object Oriented: Python language supports both Procedure oriented (like C, pascal etc) and object oriented (like C++,Java) features. Hence we can get benefits of both like security and reusability etc

8. Interpreted: We are not required to compile Python programs explcitly. Internally Python interpreter will take care that compilation. If compilation fails interpreter raised syntax errors. Once compilation success then PVM (Python Virtual Machine) is responsible to execute.

9. Extensible: We can use other language programs in Python. The main advantages of this approach are:

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

1. We can use already existing legacy non-Python code 2. We can improve performance of the application

10. Embedded: We can use Python programs in any other language programs. i.e we can embedd Python programs anywhere.

11. Extensive Library: Python has a rich inbuilt library. Being a programmer we can use this library directly and we are not responsible to implement the functionality. etc.

Limitations of Python: 1. Performance wise not up to the mark b'z it is interpreted language. 2. Not using for mobile Applications

Flavors of Python: 1.CPython: It is the standard flavor of Python. It can be used to work with C lanugage Applications 2. Jython or JPython: It is for Java Applications. It can run on JVM 3. IronPython: It is for C#.Net platform 4.PyPy: The main advantage of PyPy is performance will be improved because JIT compiler is available inside PVM. 5.RubyPython For Ruby Platforms 6. AnacondaPython It is specially designed for handling large volume of data processing. .

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Python Versions: Python 1.0V introduced in Jan 1994 Python 2.0V introduced in October 2000 Python 3.0V introduced in December 2008 Note: Python 3 won't provide backward compatibility to Python2 i.e there is no guarantee that Python2 programs will run in Python3. Current versions Python 3.6.1

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Identifiers A name in Python program is called identifier. It can be class name or function name or module name or variable name. a = 10

Rules to define identifiers in Python: 1. The only allowed characters in Python are   

alphabet symbols(either lower case or upper case) digits(0 to 9) underscore symbol(_)

By mistake if we are using any other symbol like $ then we will get syntax error.  

cash = 10 √ ca$h =20 

2. Identifier should not starts with digit  

3. Identifiers are case sensitive. Of course Python language is case sensitive language.    

total=10 TOTAL=999 print(total) #10 print(TOTAL) #999

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Identifier: 1. Alphabet Symbols (Either Upper case OR Lower case) 2. If Identifier is start with Underscore (_) then it indicates it is private. 3. Identifier should not start with Digits. 4. Identifiers are case sensitive. 5. We cannot use reserved words as identifiers Eg: def=10  6. There is no length limit for Python identifiers. But not recommended to use too lengthy identifiers. 7. Dollor ($) Symbol is not allowed in Python.

Q. Which of the following are valid Python identifiers? 1) 2) 3) 4) 5) 6) 7)

123total  total123 √ java2share √ ca$h  _abc_abc_ √ def  if 

Note: 1. If identifier starts with _ symbol then it indicates that it is private 2. If identifier starts with __(two under score symbols) indicating that strongly private identifier. 3.If the identifier starts and ends with two underscore symbols then the identifier is language defined special name,which is also known as magic methods. Eg: __add__

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Reserved Words In Python some words are reserved to represent some meaning or functionality. Such type of words are called Reserved words. There are 33 reserved words available in Python.      

True,False,None and, or ,not,is if,elif,else while,for,break,continue,return,in,yield try,except,finally,raise,assert import,from,as,class,def,pass,global,nonlocal,lambda,del,with

Note: 1. All Reserved words in Python contain only alphabet symbols. 2. Except the following 3 reserved words, all contain only lower case alphabet symbols.   

True False None

Eg: a= true  a=True √ >>> import keyword >>> keyword.kwlist ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Data Types Data Type represent the type of data present inside a variable. In Python we are not required to specify the type explicitly. Based on value provided,the type will be assigned automatically.Hence Python is Dynamically Typed Language. Python contains the following inbuilt data types 1. int 2. float 3.complex 4.bool 5.str 6.bytes 7.bytearray 8.range 9.list 10.tuple 11.set 12.frozenset 13.dict 14.None 10 a = 10 a = 20

Note: Python contains several inbuilt functions 1.type() to check the type of variable 2. id() to get address of object

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

3. print() to print the value In Python everything is object

int data type: We can use int data type to represent whole numbers (integral values) Eg: a=10 type(a) #int Note: In Python2 we have long data type to represent very large integral values. But in Python3 there is no long type explicitly and we can represent long values also by using int type only. We can represent int values in the following ways 1. Decimal form 2. Binary form 3. Octal form 4. Hexa decimal form

1. Decimal form(base-10): It is the default number system in Python The allowed digits are: 0 to 9 Eg: a =10

2. Binary form(Base-2): The allowed digits are : 0 & 1 Literal value should be prefixed with 0b or 0B Eg: a = 0B1111 a =0B123 a=b111

3. Octal Form(Base-8): The allowed digits are : 0 to 7 Literal value should be prefixed with 0o or 0O.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: a=0o123 a=0o786

4. Hexa Decimal Form(Base-16): The allowed digits are : 0 to 9, a-f (both lower and upper cases are allowed) Literal value should be prefixed with 0x or 0X Eg: a =0XFACE a=0XBeef a =0XBeer Note: Being a programmer we can specify literal values in decimal, binary, octal and hexa decimal forms. But PVM will always provide values only in decimal form. a=10 b=0o10 c=0X10 d=0B10 print(a)10 print(b)8 print(c)16 print(d)2

Base Conversions Python provide the following in-built functions for base conversions

1.bin(): We can use bin() to convert from any base to binary Eg: 1) 2) 3) 4) 5) 6)

>>> bin(15) '0b1111' >>> bin(0o11) '0b1001' >>> bin(0X10) '0b10000'

2. oct(): We can use oct() to convert from any base to octal

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

>>> oct(10) '0o12' >>> oct(0B1111) '0o17' >>> oct(0X123) '0o443'

3. hex(): We can use hex() to convert from any base to hexa decimal Eg: 1) 2) 3) 4) 5) 6)

>>> hex(100) '0x64' >>> hex(0B111111) '0x3f' >>> hex(0o12345) '0x14e5'

float data type: We can use float data type to represent floating point values (decimal values) Eg: f=1.234 type(f) float We can also represent floating point values by using exponential form (scientific notation) Eg: f=1.2e3 print(f) 1200.0 instead of 'e' we can use 'E' The main advantage of exponential form is we can represent big values in less memory. ***Note: We can represent int values in decimal, binary, octal and hexa decimal forms. But we can represent float values only by using decimal form. Eg: 1) 2) 3)

>>> f=0B11.01 File "", line 1 f=0B11.01 nd

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

4) 5) 6) 7) 8) 9) 10) 11)

^ SyntaxError: invalid syntax >>> f=0o123.456 SyntaxError: invalid syntax >>> f=0X123.456 SyntaxError: invalid syntax

Complex Data Type: A complex number is of the form j2 = -1 j=

a + bj Real Part

a and b contain intergers or floating point values Eg: 3+5j 10+5.5j 0.5+0.1j In the real part if we use int value then we can specify that either by decimal,octal,binary or hexa decimal form. But imaginary part should be specified only by using decimal form. 1) 2) 3) 4) 5)

>>> a=0B11+5j >>> a (3+5j) >>> a=3+0B11j SyntaxError: invalid syntax

Even we can perform operations on complex type values. 1) 2) 3) 4) 5) 6) 7)

>>> a=10+1.5j >>> b=20+2.5j >>> c=a+b >>> print(c) (30+4j) >>> type(c)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Note: Complex data type has some inbuilt attributes to retrieve the real part and imaginary part c=10.5+3.6j c.real==>10.5 c.imag==>3.6 We can use complex type generally in scientific Applications and electrical engineering Applications.

4.bool data type: We can use this data type to represent boolean values. The only allowed values for this data type are: True and False Internally Python represents True as 1 and False as 0 b=True type(b) =>bool Eg: a=10 b=20 c=a
Slicing of Strings: slice means a piece [ ] operator is called slice operator,which can be used to retrieve parts of String. In Python Strings follows zero based index. The index can be either +ve or -ve. +ve index means forward direction from Left to Right -ve index means backward direction from Right to Left

1) 2) 3) 4) 5) 6) 7) 8)

>>> s="durga" >>> s[0] 'd' >>> s[1] 'u' >>> s[-1] 'a' >>> s[40]

IndexError: string index out of range

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16)

>>> s[1:40] 'urga' >>> s[1:] 'urga' >>> s[:4] 'durg' >>> s[:] 'durga' >>>

>>> s*3 'durgadurgadurga' >>> len(s) 5

Note: 1. In Python the following data types are considered as Fundamental Data types     

int float complex bool str

2. In Python,we can represent char values also by using str type and explicitly char type is not available. Eg: 1) >>> c='a' 2) >>> type(c) 3)

3. long Data Type is available in Python2 but not in Python3. In Python3 long values also we can represent by using int type only. 4. In Python we can present char Value also by using str Type and explicitly char Type is not available.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Type Casting We can convert one type value to another type. This conversion is called Typecasting or Type coersion. The following are various inbuilt functions for type casting. 1. int() 2. float() 3. complex() 4. bool() 5. str()

1.int(): We can use this function to convert values from other types to int Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16)

>>> int(123.987) 123 >>> int(10+5j) TypeError: can't convert complex to int >>> int(True) 1 >>> int(False) 0 >>> int("10") 10 >>> int("10.5") ValueError: invalid literal for int() with base 10: '10.5' >>> int("ten") ValueError: invalid literal for int() with base 10: 'ten' >>> int("0B1111") ValueError: invalid literal for int() with base 10: '0B1111'

Note: 1. We can convert from any type to int except complex type. 2. If we want to convert str type to int type, compulsary str should contain only integral value and should be specified in base-10

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

2. float(): We can use float() function to convert other type values to float type. 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16)

>>> float(10) 10.0 >>> float(10+5j) TypeError: can't convert complex to float >>> float(True) 1.0 >>> float(False) 0.0 >>> float("10") 10.0 >>> float("10.5") 10.5 >>> float("ten") ValueError: could not convert string to float: 'ten' >>> float("0B1111") ValueError: could not convert string to float: '0B1111'

Note: 1. We can convert any type value to float type except complex type. 2. Whenever we are trying to convert str type to float type compulsary str should be either integral or floating point literal and should be specified only in base-10.

3.complex(): We can use complex() function to convert other types to complex type.

Form-1: complex(x) We can use this function to convert x into complex number with real part x and imaginary part 0. Eg: 1) complex(10)==>10+0j 2) complex(10.5)===>10.5+0j 3) complex(True)==>1+0j 4) complex(False)==>0j 5) complex("10")==>10+0j 6) complex("10.5")==>10.5+0j 7) complex("ten") 8) ValueError: complex() arg is a malformed string

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Form-2: complex(x,y) We can use this method to convert x and y into complex number such that x will be real part and y will be imaginary part. Eg: complex(10,-2)==>10-2j complex(True,False)==>1+0j

4. bool(): We can use this function to convert other type values to bool type. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12)

bool(0)==>False bool(1)==>True bool(10)===>True bool(10.5)===>True bool(0.178)==>True bool(0.0)==>False bool(10-2j)==>True bool(0+1.5j)==>True bool(0+0j)==>False bool("True")==>True bool("False")==>True bool("")==>False

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

5. str(): We can use this method to convert other type values to str type Eg: 1) 2) 3) 4) 5) 6) 7) 8)

>>> str(10) '10' >>> str(10.5) '10.5' >>> str(10+5j) '(10+5j)' >>> str(True) 'True'

Fundamental Data Types vs Immutability: All Fundamental Data types are immutable. i.e once we creates an object,we cannot perform any changes in that object. If we are trying to change then with those changes a new object will be created. This non-chageable behaviour is called immutability.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

In Python if a new object is required, then PVM wont create object immediately. First it will check is any object available with the required content or not. If available then existing object will be reused. If it is not available then only a new object will be created. The advantage of this approach is memory utilization and performance will be improved. But the problem in this approach is,several references pointing to the same object,by using one reference if we are allowed to change the content in the existing object then the remaining references will be effected. To prevent this immutability concept is required. According to this once creates an object we are not allowed to change content. If we are trying to change with those changes a new object will be created. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9)

>>> a=10 >>> b=10 >>> a is b True >>> id(a) 1572353952 >>> id(b) 1572353952 >>>

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

bytes Data Type: bytes data type represens a group of byte numbers just like an array. Eg: 1) x = [10,20,30,40] 2) b = bytes(x) 3) type(b)==>bytes 4) print(b[0])==> 10 5) print(b[-1])==> 40 6) >>> for i in b : print(i) 7) 8) 10 9) 20 10) 30 11) 40

Conclusion 1: The only allowed values for byte data type are 0 to 256. By mistake if we are trying to provide any other values then we will get value error.

Conclusion 2: Once we creates bytes data type value, we cannot change its values,otherwise we will get TypeError. Eg: 1) >>> x=[10,20,30,40] 2) >>> b=bytes(x) 3) >>> b[0]=100 4) TypeError: 'bytes' object does not support item assignment

bytearray Data type: bytearray is exactly same as bytes data type except that its elements can be modified. Eg 1: 1) 2) 3) 4)

x=[10,20,30,40] b = bytearray(x) for i in b : print(i) 10

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

5) 6) 7) 8) 9) 10) 11) 12) 13)

20 30 40 b[0]=100 for i in b: print(i) 100 20 30 40

Eg 2: 1) >>> x =[10,256] 2) >>> b = bytearray(x) 3) ValueError: byte must be in range(0, 256)

list data type: If we want to represent a group of values as a single entity where insertion order required to preserve and duplicates are allowed then we should go for list data type. 1. insertion order is preserved 2. heterogeneous objects are allowed 3. duplicates are allowed 4. Growable in nature 5. values should be enclosed within square brackets. Eg: 1) list=[10,10.5,'durga',True,10] 2) print(list) # [10,10.5,'durga',True,10]

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13)

list=[10,20,30,40] >>> list[0] 10 >>> list[-1] 40 >>> list[1:3] [20, 30] >>> list[0]=100 >>> for i in list:print(i) . 100 20 30

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

list is growable in nature. i.e based on our requirement we can increase or decrease the size. 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

>>> list=[10,20,30] >>> list.append("durga") >>> list [10, 20, 30, 'durga'] >>> list.remove(20) >>> list [10, 30, 'durga'] >>> list2=list*2 >>> list2 [10, 30, 'durga', 10, 30, 'durga']

Note: An ordered, mutable, heterogenous collection of eleemnts is nothing but list, where duplicates also allowed.

tuple data type: tuple data type is exactly same as list data type except that it is immutable.i.e we cannot chage values. Tuple elements can be represented within parenthesis. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9)

t=(10,20,30,40) type(t) t[0]=100 TypeError: 'tuple' object does not support item assignment >>> t.append("durga") AttributeError: 'tuple' object has no attribute 'append' >>> t.remove(10) AttributeError: 'tuple' object has no attribute 'remove'

Note: tuple is the read only version of list

range Data Type: range Data Type represents a sequence of numbers. The elements present in range Data type are not modifiable. i.e range Data type is immutable.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Form-1: range(10) generate numbers from 0 to 9 Eg: r=range(10) for i in r : print(i)

Form-2: range(10,20) generate numbers from 10 to 19 r = range(10,20) for i in r : print(i)

Form-3: range(10,20,2) 2 means increment value r = range(10,20,2) for i in r : print(i) 10,12,14,16,18 We can access elements present in the range Data Type by using index. r=range(10,20) r[0]==>10 r[15]==>IndexError: range object index out of range We cannot modify the values of range data type Eg: r[0]=100 TypeError: 'range' object does not support item assignment We can create a list of values with range data type Eg: 1) >>> l = list(range(10)) 2) >>> l 3) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

set Data Type: If we want to represent a group of values without duplicates where order is not important then we should go for set Data Type.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

1. insertion order is not preserved 2. duplicates are not allowed 3. heterogeneous objects are allowed 4. index concept is not applicable 5. It is mutable collection 6. Growable in nature Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12)

s= s # s[0] ==>TypeError: 'set' object does not support indexing set is growable in nature, based on our requirement we can increase or decrease the size. >>> s.add(60) >>> s >>> s.remove(100) >>> s

frozenset Data Type: It is exactly same as set except that it is immutable. Hence we cannot use add or remove functions. 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17)

>>> s= >>> fs=frozenset(s) >>> type(fs) >>> fs frozenset() >>> for i in fs:print(i) . 40 10 20 30 >>> fs.add(70) AttributeError: 'frozenset' object has no attribute 'add' >>> fs.remove(10) AttributeError: 'frozenset' object has no attribute 'remove'

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

dict Data Type: If we want to represent a group of values as key-value pairs then we should go for dict data type. Eg: d= Duplicate keys are not allowed but values can be duplicated. If we are trying to insert an entry with duplicate key then old value will be replaced with new value. Eg: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

>>> d= >>> d[101]='sunny' >>> d We can create empty dictionary as follows d= < >We can add key-value pairs as follows d['a']='apple' d['b']='banana' print(d)

Note: dict is mutable and the order wont be preserved. Note: 1. In general we can use bytes and bytearray data types to represent binary information like images,video files etc 2. In Python2 long data type is available. But in Python3 it is not available and we can represent long values also by using int type only. 3. In Python there is no char data type. Hence we can represent char values also by using str type.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Summary of Datatypes in Python3 Datatype Int

Description Is Immutable We can use to represent the Immutable whole/integral numbers

We can use to represent the Immutable decimal/floating point numbers We can use to represent the Immutable complex numbers

We can use to represent the Immutable logical values(Only allowed values are True and False)

To represent sequence of Immutable Characters

To represent a sequence of Immutable byte values from 0-255

To represent a sequence of Mutable byte values from 0-255

To represent a range of Immutable values

To represent an ordered Mutable collection of objects

To represent an ordered Immutable collections of objects

To represent an unordered Mutable collection of unique objects

Example >>> a=10 >>> type(a) >>> b=10.5 >>> type(b) >>> c=10+5j >>> type(c) >>> c.real 10.0 >>> c.imag 5.0 >>> flag=True >>> flag=False >>> type(flag) >>> s='durga' >>> type(s) >>> s="durga" >>> s='''Durga Software Solutions . Ameerpet''' >>> type(s) >>> list=[1,2,3,4] >>> b=bytes(list) >>> type(b) >>> list=[10,20,30] >>> ba=bytearray(list) >>> type(ba) >>> r=range(10) >>> r1=range(0,10) >>> r2=range(0,10,2) >>> l=[10,11,12,13,14,15] >>> type(l) >>> t=(1,2,3,4,5) >>> type(t) >>> s= >>> type(s)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

To represent an unordered Immutable collection of unique objects

To represent a group of key Mutable value pairs

None Data Type: None means Nothing or No value associated. If the value is not available,then to handle such type of cases None introduced. It is something like null value in Java. Eg: def m1(): a=10 print(m1()) None

Escape Characters: In String literals we can use esacpe characters to associate a special meaning. 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15)

>>> s="durga\nsoftware" >>> print(s) durga software >>> s="durga\tsoftware" >>> print(s) durga software >>> s="This is " symbol" File "", line 1 s="This is " symbol" ^ SyntaxError: invalid syntax >>> s="This is \" symbol" >>> print(s) This is " symbol

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

The following are various important escape characters in Python 1) 2) 3) 4) 5) 6) 7) 8) 9)

\n==>New Line \t===>Horizontal tab \r ==>Carriage Return \b===>Back space \f===>Form Feed \v==>Vertical tab \'===>Single quote \"===>Double quote \\===>back slash symbol .

Constants: Constants concept is not applicable in Python. But it is convention to use only uppercase characters if we don’t want to change value. MAX_VALUE=10 It is just convention but we can change the value.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Operators Operator is a symbol that performs certain operations. Python provides the following set of operators 1. Arithmetic Operators 2. Relational Operators or Comparison Operators 3. Logical operators 4. Bitwise oeprators 5. Assignment operators 6. Special operators

1. Arithmetic Operators: + ==>Addition - ==>Subtraction * ==>Multiplication / ==>Division operator % ===>Modulo operator // ==>Floor Division operator ** ==>Exponent operator or power operator Eg: test.py: 1) 2) 3) 4) 5) 6) 7) 8) 9)

a=10 b=2 print('a+b=',a+b) print('a-b=',a-b) print('a*b=',a*b) print('a/b=',a/b) print('a//b=',a//b) print('a%b=',a%b) print('a**b=',a**b)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Output: 1) 2) 3) 4) 5) 6) 7) 8)

Python test.py or py test.py a+b= 12 a-b= 8 a*b= 20 a/b= 5.0 a//b= 5 a%b= 0 a**b= 100

1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

a+b= 12.5 a-b= 8.5 a*b= 21.0 a/b= 5.25 a//b= 5.0 a%b= 0.5 a**b= 110.25

Note: / operator always performs floating point arithmetic. Hence it will always returns float value. But Floor division (//) can perform both floating point and integral arithmetic. If arguments are int type then result is int type. If atleast one argument is float type then result is float type.

Note: We can use +,* operators for str type also. If we want to use + operator for str type then compulsory both arguments should be str type only otherwise we will get error. 1) 2) 3) 4)

>>> "durga"+10 TypeError: must be str, not int >>> "durga"+"10" 'durga10'

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

If we use * operator for str type then compulsory one argument should be int and other argument should be str type. 2*"durga" "durga"*2 2.5*"durga" ==>TypeError: can't multiply sequence by non-int of type 'float' "durga"*"durga"==>TypeError: can't multiply sequence by non-int of type 'str' +====>String concatenation operator * ===>String multiplication operator

Note: For any number x, x/0 and x%0 always raises "ZeroDivisionError" 10/0 10.0/0 .

Relational Operators: >,>=, b is ",a>b) print("a >= b is ",a>=b) print("a b is False a >= b is False a b is ",a>b) print("a >= b is ",a>=b) print("a True) False print(True>=True) True print(10 >True) True print(False > True) False

a=10 b=20 if(a>b): print("a is greater than b") else: print("a is not greater than b")

a > b is False a >= b is True a 'durga') TypeError: '>' not supported between instances of 'int' and 'str'

Outputa is not greater than b

Note: Chaining of relational operators is possible. In the chaining, if all comparisons returns True then only result is True. If atleast one comparison returns False then the result is False Eg: 1) 2) 3) 4)

10 True 10 True 10 True 10 50 ==>False

equality operators: == , != We can apply these operators for any type even for incompatible types also 1) >>> 10==20 2) False 3) >>> 10!= 20

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

4) 5) 6) 7) 8) 9) 10) 11) 12)

True >>> 10==True False >>> False==False True >>> "durga"=="durga" True >>> 10=="durga" False

Note: Chaining concept is applicable for equality operators. If atleast one comparison returns False then the result is False. otherwise the result is True. Eg: 1) 2) 3) 4)

>>> 10==20==30==40 False >>> 10==10==10==10 True

Logical Operators: and, or ,not We can apply for all types.

For boolean types behaviour: and ==>If both arguments are True then only result is True or ====>If atleast one arugemnt is True then result is True not ==>complement True and False ==>False True or False ===>True not False ==>True

For non-boolean types behaviour: 0 means False non-zero means True empty string is always treated as False

x and y: ==>if x is evaluates to false return x otherwise return y

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: 10 and 20 0 and 20 If first argument is zero then result is zero otherwise result is y

x or y: If x evaluates to True then result is x otherwise result is y 10 or 20 ==> 10 0 or 20 ==> 20

not x: If x is evalutates to False then result is True otherwise False not 10 ==>False not 0 ==>True Eg: 1) 2) 3) 4) 5) 6) 7)

"durga" and "durgasoft" ==>durgasoft "" and "durga" ==>"" "durga" and "" ==>"" "" or "durga" ==>"durga" "durga" or ""==>"durga" not ""==>True not "durga" ==>False

Bitwise Operators: We can apply these operators bitwise. These operators are applicable only for int and boolean types. By mistake if we are trying to apply for any other type then we will get Error. &,|,^,~, > print(4&5) ==>valid print(10.5 & 5.6) ==> TypeError: unsupported operand type(s) for &: 'float' and 'float' print(True & True) ==>valid

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

& ==> If both bits are 1 then only result is 1 otherwise result is 0 | ==> If atleast one bit is 1 then result is 1 otherwise result is 0 ^ ==>If bits are different then only result is 1 otherwise result is 0 ~ ==>bitwise complement operator 1==>0 & 0==>1 Bitwise Left shift >> ==>Bitwise Right Shift print(4&5) ==>4 print(4|5) ==>5 print(4^5) ==>1 Operator

If both bits are 1 then only result is 1 otherwise result is 0

If atleast one bit is 1 then result is 1 otherwise result is 0

If bits are different then only result is 1 otherwise result is 0

bitwise complement operator i.e 1 means 0 and 0 means 1

Bitwise Left shift Operator

Note: The most significant bit acts as sign bit. 0 value represents +ve number where as 1 represents -ve value. positive numbers will be repesented directly in the memory where as -ve numbers will be represented indirectly in 2's complement form.

Shift Operators: 40

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

>> Right Shift operator After shifting the empty cells we have to fill with sign bit.( 0 for +ve and 1 for -ve) print(10>>2) ==>2 0

We can apply bitwise operators for boolean types also print(True & False) ==>False print(True | False) ===>True print(True ^ False) ==>True print(~True) ==>-2 print(True 4 print(True>>2) ==>0

Assignment Operators: We can use assignment operator to assign value to the variable. Eg: x=10 We can combine asignment operator with some other operator to form compound assignment operator. Eg: x+=10 ====> x = x+10

The following is the list of all possible compound assignment operators in Python += -= *= /= %= //= **= &= |= ^=

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: 1) x=10 2) x&=5 3) print(x) ==>0

Ternary Operator: Syntax: x = firstValue if condition else secondValue If condition is True then firstValue will be considered else secondValue will be considered.

Eg 1: 1) a,b=10,20 2) x=30 if a
Eg 2: Read two numbers from the keyboard and print minimum value 1) 2) 3) 4)

a=int(input("Enter First Number:")) b=int(input("Enter Second Number:")) min=a if a
Output: Enter First Number:10 Enter Second Number:30 Minimum Value: 10

Note: Nesting of ternary operator is possible.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Q. Program for minimum of 3 numbers 1) 2) 3) 4) 5)

a=int(input("Enter First Number:")) b=int(input("Enter Second Number:")) c=int(input("Enter Third Number:")) min=a if a
Q. Program for maximum of 3 numbers 1) 2) 3) 4) 5)

a=int(input("Enter First Number:")) b=int(input("Enter Second Number:")) c=int(input("Enter Third Number:")) max=a if a>b and a>c else b if b>c else c print("Maximum Value:",max)

Eg: 1) a=int(input("Enter First Number:")) 2) b=int(input("Enter Second Number:")) 3) print("Both numbers are equal" if a==b else "First Number is Less than Second Number" if a
Output: D:\python_classes>py test.py Enter First Number:10 Enter Second Number:10 Both numbers are equal D:\python_classes>py test.py Enter First Number:10 Enter Second Number:20 First Number is Less than Second Number D:\python_classes>py test.py Enter First Number:20 Enter Second Number:10 First Number Greater than Second Number

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Special operators: Python defines the following 2 special operators 1. Identity Operators 2. Membership operators

1. Identity Operators We can use identity operators for address comparison. 2 identity operators are available 1. is 2. is not r1 is r2 returns True if both r1 and r2 are pointing to the same object r1 is not r2 returns True if both r1 and r2 are not pointing to the same object Eg: 1) 2) 3) 4) 5) 6)

a=10 b=10 print(a is b) x=True y=True print( x is y)

a="durga" b="durga" print(id(a)) print(id(b)) print(a is b)

list1=["one","two","three"] list2=["one","two","three"] print(id(list1)) print(id(list2)) print(list1 is list2) False print(list1 is not list2) True print(list1 == list2) True

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Note: We can use is operator for address comparison where as == operator for content comparison.

2. Membership operators: We can use Membership operators to check whether the given object present in the given collection.(It may be String,List,Set,Tuple or Dict) in  Returns True if the given object present in the specified Collection not in  Retruns True if the given object not present in the specified Collection Eg: 1) 2) 3) 4) 5)

x="hello learning Python is very easy. " print('h' in x) True print('d' in x) False print('d' not in x) True print('Python' in x) True

list1=["sunny","bunny","chinny","pinny"] print("sunny" in list1) True print("tunny" in list1) False print("tunny" not in list1) True

Operator Precedence: If multiple operators present then which operator will be evaluated first is decided by operator precedence. Eg: print(3+10*2)  23 print((3+10)*2)  26 The following list describes operator precedence in Python ()  Parenthesis **  exponential operator ~,-  Bitwise complement operator,unary minus operator *,/,%,//  multiplication,division,modulo,floor division +,-  addition,subtraction >  Left and Right Shift &  bitwise And

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

^  Bitwise X-OR |  Bitwise OR >,>=, Relational or Comparison operators =,+=,-=,*=. ==>Assignment operators is , is not  Identity Operators in , not in  Membership operators not  Logical not and  Logical and or  Logical or Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15)

a=30 b=20 c=10 d=5 print((a+b)*c/d) 100.0 print((a+b)*(c/d)) 100.0 print(a+(b*c)/d) 70.0

3/2*4+3+(10/5)**3-2 3/2*4+3+2.0**3-2 3/2*4+3+8.0-2 1.5*4+3+8.0-2 6.0+3+8.0-2 15.0

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Mathematical Functions (math Module) A Module is collection of functions, variables and classes etc. math is a module that contains several functions to perform mathematical operations If we want to use any module in Python, first we have to import that module. import math Once we import a module then we can call any function of that module. import math print(math.sqrt(16)) print(math.pi) 4.0 3.141592653589793 We can create alias name by using as keyword. import math as m Once we create alias name, by using that we can access functions and variables of that module import math as m print(m.sqrt(16)) print(m.pi) We can import a particular member of a module explicitly as follows from math import sqrt from math import sqrt,pi If we import a member explicitly then it is not required to use module name while accessing. from math import sqrt,pi print(sqrt(16)) print(pi) print(math.pi)  NameError: name 'math' is not defined

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

important functions of math module: ceil(x) floor(x) pow(x,y) factorial(x) trunc(x) gcd(x,y) sin(x) cos(x) tan(x) .

important variables of math module: pi3.14 e===>2.71 inf ==>infinity nan ==>not a number

Q. Write a Python program to find area of circle pi*r**2 from math import pi r=16 print("Area of Circle is :",pi*r**2) OutputArea of Circle is : 804.247719318987

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Input And Output Statements Reading dynamic input from the keyboard: In Python 2 the following 2 functions are available to read dynamic input from the keyboard. 1. raw_input() 2. input()

1. raw_input(): This function always reads the data from the keyboard in the form of String Format. We have to convert that string type to our required type by using the corresponding type casting methods. Eg: x=raw_input("Enter First Number:") print(type(x)) It will always print str type only for any input type

2. input(): input() function can be used to read data directly in our required format.We are not required to perform type casting. x=input("Enter Value) type(x) 10 ===> int "durga"===>str 10.5===>float True==>bool ***Note: But in Python 3 we have only input() method and raw_input() method is not available. Python3 input() function behaviour exactly same as raw_input() method of Python2. i.e every input value is treated as str type only. raw_input() function of Python 2 is renamed as input() function in Python3

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9)

>>> type(input("Enter value:")) Enter value:10 Enter value:10.5 Enter value:True

Q. Write a program to read 2 numbers from the keyboard and print sum. 1) 2) 3) 4) 5) 6) 7) 8) 9)

x=input("Enter First Number:") y=input("Enter Second Number:") i = int(x) j = int(y) print("The Sum:",i+j) Enter First Number:100 Enter Second Number:200 The Sum: 300

----------------------------------------------------1) x=int(input("Enter First Number:")) 2) y=int(input("Enter Second Number:")) 3) print("The Sum:",x+y)

Q. Write a program to read Employee data from the keyboard and print that data. 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12)

eno=int(input("Enter Employee No:")) ename=input("Enter Employee Name:") esal=float(input("Enter Employee Salary:")) eaddr=input("Enter Employee Address:") married=bool(input("Employee Married ?[True|False]:")) print("Please Confirm Information") print("Employee No :",eno) print("Employee Name :",ename) print("Employee Salary :",esal) print("Employee Address :",eaddr) print("Employee Married ? :",married)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23) 24)

D:\Python_classes>py test.py Enter Employee No:100 Enter Employee Name:Sunny Enter Employee Salary:1000 Enter Employee Address:Mumbai Employee Married ?[True|False]:True Please Confirm Information Employee No : 100 Employee Name : Sunny Employee Salary : 1000.0 Employee Address : Mumbai Employee Married ? : True

How to read multiple values from the keyboard in a single line: 1) 2) 3) 4) 5) 6)

a,b= [int(x) for x in input("Enter 2 numbers :").split()] print("Product is :", a*b) D:\Python_classes>py test.py Enter 2 numbers :10 20 Product is : 200

Note: split() function can take space as seperator by default

.But we can pass

anything as seperator. Q. Write a program to read 3 float numbers from the keyboard with , seperator and print their sum. 1) 2) 3) 4) 5) 6)

a,b,c= [float(x) for x in input("Enter 3 float numbers :").split(',')] print("The Sum is :", a+b+c) D:\Python_classes>py test.py Enter 3 float numbers :10.5,20.6,20.1 The Sum is : 51.2

eval(): eval Function take a String and evaluate the Result. Eg: x = eval(“10+20+30”) print(x) Output: 60 Eg: x = eval(input(“Enter Expression”)) Enter Expression: 10+2*3/4 Output11.5

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

eval() can evaluate the Input to list, tuple, set, etc based the provided Input. Eg: Write a Program to accept list from the keynboard on the display 1) l = eval(input(“Enter List”)) 2) print (type(l)) 3) print(l)

Command Line Arguments  

argv is not Array it is a List. It is available sys Module. The Argument which are passing at the time of execution are called Command Line Arguments.

Eg: D:\Python_classes py test.py 10 20 30 Command Line Arguments Within the Python Program this Command Line Arguments are available in argv. Which is present in SYS Module. test.py

Note: argv[0] represents Name of Program. But not first Command Line Argument. argv[1] represent First Command Line Argument. Program: To check type of argv from sys import argv print(type(argv)) D:\Python_classes\py test.py

Write a Program to display Command Line Arguments 1) 2) 3) 4) 5) 6) 7) 8) 9)

from sys import argv print(“The Number of Command Line Arguments:”, len(argv)) print(“The List of Command Line Arguments:”, argv) print(“Command Line Arguments one by one:”) for x in argv: print(x) D:\Python_classes>py test.py 10 20 30 The Number of Command Line Arguments: 4

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

10) 11) 12) 13) 14) 15)

The List of Command Line Arguments: [‘test.py’, ‘10’,’20’,’30’] Command Line Arguments one by one: test.py 10 20 30

1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

from sys import argv sum=0 args=argv[1:] for x in args : n=int(x) sum=sum+n print("The Sum:",sum) D:\Python_classes>py test.py 10 20 30 40 The Sum: 100

Note1: usually space is seperator between command line arguments. If our command line argument itself contains space then we should enclose within double quotes(but not single quotes) Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11)

from sys import argv print(argv[1]) D:\Python_classes>py test.py Sunny Leone Sunny D:\Python_classes>py test.py 'Sunny Leone' 'Sunny D:\Python_classes>py test.py "Sunny Leone" Sunny Leone

Note2: Within the Python program command line arguments are available in the String form. Based on our requirement,we can convert into corresponding type by using type casting methods. Eg: 1) from sys import argv 2) print(argv[1]+argv[2]) 3) print(int(argv[1])+int(argv[2]))

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

4) 5) D:\Python_classes>py test.py 10 20 6) 1020 7) 30

Note3: If we are trying to access command line arguments with out of range index then we will get Error. Eg: 1) from sys import argv 2) print(argv[100]) 3) 4) D:\Python_classes>py test.py 10 20 5) IndexError: list index out of range

Note: In Python there is argparse module to parse command line arguments and display some help messages whenever end user enters wrong input. input() raw_input() command line arguments

output statements: We can use print() function to display output.

Form-1: print() without any argument Just it prints new line character

Form-2: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

print(String): print("Hello World") We can use escape characters also print("Hello \n World") print("Hello\tWorld") We can use repetetion operator (*) in the string print(10*"Hello") print("Hello"*10) We can use + operator also print("Hello"+"World")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Note: If both arguments are String type then + operator acts as concatenation operator. If one argument is string type and second is any other type like int then we will get Error If both arguments are number type then + operator acts as arithmetic addition operator.

Note: 1) print("Hello"+"World") 2) print("Hello","World") 3) 4) HelloWorld 5) Hello World

Form-3: print() with variable number of arguments: 1. a,b,c=10,20,30 2. print("The Values are :",a,b,c) 3. 4. OutputThe Values are : 10 20 30

By default output values are seperated by space.If we want we can specify seperator by using "sep" attribute 1. 2. 3. 4. 5. 6. 7.

a,b,c=10,20,30 print(a,b,c,sep=',') print(a,b,c,sep=':') D:\Python_classes>py test.py 10,20,30 10:20:30

Form-4:print() with end attribute: 1. print("Hello") 2. print("Durga") 3. print("Soft")

Output: 1. Hello 2. Durga 3. Soft

If we want output in the same line with space

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

1. print("Hello",end=' ') 2. print("Durga",end=' ') 3. print("Soft")

Output: Hello Durga Soft

Note: The default value for end attribute is \n,which is nothing but new line character. Form-5: print(object) statement: We can pass any object (like list,tuple,set etc)as argument to the print() statement. Eg: 1. 2. 3. 4.

l=[10,20,30,40] t=(10,20,30,40) print(l) print(t)

Form-6: print(String,variable list): We can use print() statement with String and any number of arguments. Eg: 1. 2. 3. 4. 5. 6.

s="Durga" a=48 s1="java" s2="Python" print("Hello",s,"Your Age is",a) print("You are teaching",s1,"and",s2)

Output: 1) Hello Durga Your Age is 48 2) You are teaching java and Python

Form-7: print(formatted string): %i====>int %d====>int %f=====>float %s======>String type

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Syntax: print("formatted string" %(variable list)) Eg 1: 1) 2) 3) 4) 5) 6) 7) 8) 9)

a=10 b=20 c=30 print("a value is %i" %a) print("b value is %d and c value is %d" %(b,c)) Output a value is 10 b value is 20 and c value is 30

Eg 2: 1) s="Durga" 2) list=[10,20,30,40] 3) print("Hello %s . The List of Items are %s" %(s,list)) 4) 5) Output Hello Durga . The List of Items are [10, 20, 30, 40]

Form-8: print() with replacement operator <> Eg: 1) 2) 3) 4) 5)

name="Durga" salary=10000 gf="Sunny" print("Hello your salary is and Your Friend is waiting".format(name,salary,gf)) print("Hello your salary is and Your Friend is waiting".format(x=name,y=salary,z= gf))

6) 7) Output 8) Hello Durga your salary is 10000 and Your Friend Sunny is waiting 9) Hello Durga your salary is 10000 and Your Friend Sunny is waiting

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Flow Control Flow control describes the order in which statements will be executed at runtime.

1) if 2) if-elif 3) if-elif-else

1) break 2) continue 3) pass

I. Conditional Statements 1) if if condition : statement or if condition : statement-1 statement-2 statement-3 If condition is true then statements will be executed.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13)

name=input("Enter Name:") if name=="durga" : print("Hello Durga Good Morning") print("How are you. ") D:\Python_classes>py test.py Enter Name:durga Hello Durga Good Morning How are you. D:\Python_classes>py test.py Enter Name:Ravi How are you.

2) if-else: if condition : Action-1 else : Action-2 if condition is true then Action-1 will be executed otherwise Action-2 will be executed. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16)

name=input("Enter Name:") if name=="durga" : print("Hello Durga Good Morning") else: print("Hello Guest Good Moring") print("How are you. ") D:\Python_classes>py test.py Enter Name:durga Hello Durga Good Morning How are you. D:\Python_classes>py test.py Enter Name:Ravi Hello Guest Good Moring How are you.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

3) if-elif-else: Syntax: if condition1: Action-1 elif condition2: Action-2 elif condition3: Action-3 elif condition4: Action-4 . else: Default Action Based condition the corresponding action will be executed. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22)

brand=input("Enter Your Favourite Brand:") if brand=="RC" : print("It is childrens brand") elif brand=="KF": print("It is not that much kick") elif brand=="FO": print("Buy one get Free One") else : print("Other Brands are not recommended")

D:\Python_classes>py test.py Enter Your Favourite Brand:RC It is childrens brand D:\Python_classes>py test.py Enter Your Favourite Brand:KF It is not that much kick D:\Python_classes>py test.py Enter Your Favourite Brand:KALYANI Other Brands are not recommended

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Note: 1. else part is always optional Hence the following are various possible syntaxes. 1. if 2. if - else 3. if-elif-else 4.if-elif 2. There is no switch statement in Python Q. Write a program to find biggest of given 2 numbers from the commad prompt? 1) n1=int(input("Enter First Number:")) 2) n2=int(input("Enter Second Number:")) 3) if n1>n2: 4) print("Biggest Number is:",n1) 5) else : 6) print("Biggest Number is:",n2) 7) 8) D:\Python_classes>py test.py 9) Enter First Number:10 10) Enter Second Number:20 11) Biggest Number is: 20 Q. Write a program to find biggest of given 3 numbers from the commad prompt? 1) n1=int(input("Enter First Number:")) 2) n2=int(input("Enter Second Number:")) 3) n3=int(input("Enter Third Number:")) 4) if n1>n2 and n1>n3: 5) print("Biggest Number is:",n1) 6) elif n2>n3: 7) print("Biggest Number is:",n2) 8) else : 9) print("Biggest Number is:",n3) 10) 11) D:\Python_classes>py test.py 12) Enter First Number:10 13) Enter Second Number:20 14) Enter Third Number:30 15) Biggest Number is: 30 16) 17) D:\Python_classes>py test.py 18) Enter First Number:10

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

19) Enter Second Number:30 20) Enter Third Number:20 21) Biggest Number is: 30 Q. Write a program to find smallest of given 2 numbers? Q. Write a program to find smallest of given 3 numbers? Q. Write a program to check whether the given number is even or odd? Q. Write a program to check whether the given number is in between 1 and 100? 1) n=int(input("Enter Number:")) 2) if n>=1 and n ZERO 2) 1 ==>ONE 3) 4) n=int(input("Enter a digit from o to 9:")) 5) if n==0 : 6) print("ZERO") 7) elif n==1: 8) print("ONE") 9) elif n==2: 10) print("TWO") 11) elif n==3: 12) print("THREE") 13) elif n==4: 14) print("FOUR") 15) elif n==5: 16) print("FIVE") 17) elif n==6: 18) print("SIX") 19) elif n==7: 20) print("SEVEN") 21) elif n==8: 22) print("EIGHT") 23) elif n==9: 24) print("NINE") 25) else: 26) print("PLEASE ENTER A DIGIT FROM 0 TO 9")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

II. Iterative Statements If we want to execute a group of statements multiple times then we should go for Iterative statements. Python supports 2 types of iterative statements. 1. for loop 2. while loop

1) for loop: If we want to execute some action for every element present in some sequence(it may be string or collection)then we should go for for loop. Syntax: for x in sequence : body where sequence can be string or any collection. Body will be executed for every element present in the sequence. Eg 1: To print characters present in the given string 1) s="Sunny Leone" 2) for x in s : 3) print(x) 4) 5) Output 6) S 7) u 8) n 9) n 10) y 11) 12) L 13) e 14) o 15) n 16) e

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg 2: To print characters present in string index wise: 1) s=input("Enter some String: ") 2) i=0 3) for x in s : 4) print("The character present at ",i,"index is :",x) 5) i=i+1 6) 7) 8) D:\Python_classes>py test.py 9) Enter some String: Sunny Leone 10) The character present at 0 index is : S 11) The character present at 1 index is : u 12) The character present at 2 index is : n 13) The character present at 3 index is : n 14) The character present at 4 index is : y 15) The character present at 5 index is : 16) The character present at 6 index is : L 17) The character present at 7 index is : e 18) The character present at 8 index is : o 19) The character present at 9 index is : n 20) The character present at 10 index is : e Eg 3: To print Hello 10 times 1) for x in range(10) : 2) print("Hello") Eg 4: To display numbers from 0 to 10 1)

for x in range(11) : print(x)

Eg 5: To display odd numbers from 0 to 20 1) 2) 3)

for x in range(21) : if (x%2!=0): print(x)

Eg 6: To display numbers from 10 to 1 in descending order 1) 2)

for x in range(10,0,-1) : print(x)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg 7: To print sum of numbers presenst inside list 1) list=eval(input("Enter List:")) 2) sum=0; 3) for x in list: 4) sum=sum+x; 5) print("The Sum Enter number:")) sum=0 i=1 while i py test.py 8) 0 9) 1 10) 2 11) 3 12) 4 13) 5 14) 6 15) processing is enough..plz break Eg: 1) cart=[10,20,600,60,70] 2) for item in cart: 3) if item>500: 4) print("To place this order insurence must be required") 5) break 6) print(item) 7) 8) D:\Python_classes>py test.py 9) 10 10) 20 11) To place this order insurence must be required

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

2) continue: We can use continue statement to skip current iteration and continue next iteration. Eg 1: To print odd numbers in the range 0 to 9 1) for i in range(10): 2) if i%2==0: 3) continue 4) print(i) 5) 6) D:\Python_classes>py test.py 7) 1 8) 3 9) 5 10) 7 11) 9 Eg 2: 1) cart=[10,20,500,700,50,60] 2) for item in cart: 3) if item>=500: 4) print("We cannot process this item :",item) 5) continue 6) print(item) 7) 8) Output 9) D:\Python_classes>py test.py 10) 10 11) 20 12) We cannot process this item : 500 13) We cannot process this item : 700 14) 50 15) 60 Eg 3: 1) numbers=[10,20,0,5,0,30] 2) for n in numbers: 3) if n==0: 4) print("Hey how we can divide with zero..just skipping") 5) continue 6) print("100/<> = <>".format(n,100/n)) 7)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

8) Output 9) 10) 100/10 = 10.0 11) 100/20 = 5.0 12) Hey how we can divide with zero..just skipping 13) 100/5 = 20.0 14) Hey how we can divide with zero..just skipping 15) 100/30 = 3.3333333333333335

loops with else block: Inside loop execution,if break statement not executed ,then only else part will be executed. else means loop without break Eg: 1) cart=[10,20,30,40,50] 2) for item in cart: 3) if item>=500: 4) print("We cannot process this order") 5) break 6) print(item) 7) else: 8) print("Congrats . all items processed successfully") 9) 10) Output 11) 10 12) 20 13) 30 14) 40 15) 50 16) Congrats . all items processed successfully Eg: 1) cart=[10,20,600,30,40,50] 2) for item in cart: 3) if item>=500: 4) print("We cannot process this order") 5) break 6) print(item) 7) else: 8) print("Congrats . all items processed successfully")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

9) 10) Output 11) D:\Python_classes>py test.py 12) 10 13) 20 14) We cannot process this order Q. What is the difference between for loop and while loop in Python? We can use loops to repeat code execution Repeat code for every item in sequence ==>for loop Repeat code as long as condition is true ==>while loop Q. How to exit from the loop? by using break statement Q. How to skip some iterations inside loop? by using continue statement. Q. When else part will be executed wrt loops? If loop executed without break

3) pass statement: pass is a keyword in Python. In our programming syntactically if block is required which won't do anything then we can define that empty block with pass keyword. pass |- It is an empty statement |- It is null statement |- It won't do anything Eg: if True: SyntaxError: unexpected EOF while parsing if True: pass ==>valid def m1(): SyntaxError: unexpected EOF while parsing

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

use case of pass: Sometimes in the parent class we have to declare a function with empty body and child class responsible to provide proper implementation. Such type of empty body we can define by using pass keyword. (It is something like abstract method in java) Eg: def m1(): pass Eg: 1) for i in range(100): 2) if i%9==0: 3) print(i) 4) else:pass 5) 6) D:\Python_classes>py test.py 7) 0 8) 9 9) 18 10) 27 11) 36 12) 45 13) 54 14) 63 15) 72 16) 81 17) 90 18) 99

del statement: del is a keyword in Python. After using a variable, it is highly recommended to delete that variable if it is no longer required,so that the corresponding object is eligible for Garbage Collection. We can delete variable by using del keyword. Eg: 1) x=10 2) print(x) 3) del x

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

After deleting a variable we cannot access that variable otherwise we will get NameError. Eg: 1) x=10 2) del x 3) print(x) NameError: name 'x' is not defined.

Note: We can delete variables which are pointing to immutable objects.But we cannot delete the elements present inside immutable object. Eg: 1) 2) 3) 4)

s="durga" print(s) del s==>valid del s[0] ==>TypeError: 'str' object doesn't support item deletion

Difference between del and None: In the case del, the variable will be removed and we cannot access that variable(unbind operation) 1) s="durga" 2) del s 3) print(s) ==>NameError: name 's' is not defined. But in the case of None assignment the variable won't be removed but the corresponding object is eligible for Garbage Collection(re bind operation). Hence after assigning with None value,we can access that variable.

1) s="durga" 2) s=None 3) print(s) # None

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

String Data Type The most commonly used object in any project and in any programming language is String only. Hence we should aware complete information about String data type.

What is String? Any sequence of characters within either single quotes or double quotes is considered as a String.

Syntax: s='durga' s="durga"

Note: In most of other languges like C, C++,Java, a single character with in single quotes is treated as char data type value. But in Python we are not having char data type.Hence it is treated as String only.

Eg: >>> ch='a' >>> type(ch)

How to define multi-line String literals: We can define multi-line String literals by using triple single or double quotes.

Eg: >>> s='''durga software solutions''' We can also use triple quotes to use single quotes or double quotes as symbol inside String literal.

Eg: s='This is ' single quote symbol' ==>invalid s='This is \' single quote symbol' ==>valid s="This is ' single quote symbol"====>valid s='This is " double quotes symbol' ==>valid s='The "Python Notes" by 'durga' is very helpful' ==>invalid s="The "Python Notes" by 'durga' is very helpful"==>invalid s='The \"Python Notes\" by \'durga\' is very helpful' ==>valid s='''The "Python Notes" by 'durga' is very helpful''' ==>valid

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

How to access characters of a String: We can access characters of a string by using the following ways. 1. By using index 2. By using slice operator

1. By using index: Python supports both +ve and -ve index. +ve index means left to right(Forward direction) -ve index means right to left(Backward direction)

Eg: s='durga' diagram

Eg: >>> s='durga' >>> s[0] 'd' >>> s[4] 'a' >>> s[-1] 'a' >>> s[10] IndexError: string index out of range

Note: If we are trying to access characters of a string with out of range index then we will get error saying : IndexError

Q. Write a program to accept some string from the keyboard and display its characters by index wise(both positive and nEgative index) test.py: 1) s=input("Enter Some String:") 2) i=0 3) for x in s: 4) print("The character present at positive index <> and at nEgative index <> is <>".format(i,i -len(s),x)) 5) i=i+1

Output: D:\python_classes>py test.py Enter Some String:durga

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

The character present at positive index 0 and at nEgative index -5 The character present at positive index 1 and at nEgative index -4 The character present at positive index 2 and at nEgative index -3 The character present at positive index 3 and at nEgative index -2 The character present at positive index 4 and at nEgative index -1

is d is u is r is g is a

2. Accessing characters by using slice operator: Syntax: s[bEginindex:endindex:step] bEginindex:From where we have to consider slice(substring) endindex: We have to terminate the slice(substring) at endindex-1 step: incremented value

Note: If we are not specifying bEgin index then it will consider from bEginning of the string. If we are not specifying end index then it will consider up to end of the string The default value for step is 1

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17)

>>> s="Learning Python is very very easy. " >>> s[1:7:1] 'earnin' >>> s[1:7] 'earnin' >>> s[1:7:2] 'eri' >>> s[:7] 'Learnin' >>> s[7:] 'g Python is very very easy. ' >>> s[::] 'Learning Python is very very easy. ' >>> s[:] 'Learning Python is very very easy. ' >>> s[::-1] '. ysae yrev yrev si nohtyP gninraeL'

Behaviour of slice operator: s[bEgin:end:step] step value can be either +ve or –ve if +ve then it should be forward direction(left to right) and we have to consider bEgin to end-1 if -ve then it should be backward direction(right to left) and we have to consider bEgin to end+1

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

***Note: In the backward direction if end value is -1 then result is always empty. In the forward direction if end value is 0 then result is always empty.

In forward direction: default value for bEgin: 0 default value for end: length of string default value for step: +1

In backward direction: default value for bEgin: -1 default value for end: -(length of string+1)

Note: Either forward or backward direction, we can take both +ve and -ve values for bEgin and end index.

Mathematical Operators for String: We can apply the following mathematical operators for Strings. 1. + operator for concatenation 2. * operator for repetition print("durga"+"soft") #durgasoft print("durga"*2) #durgadurga

Note: 1. To use + operator for Strings, compulsory both arguments should be str type 2. To use * operator for Strings, compulsory one argument should be str and other argument should be int

len() in-built function: We can use len() function to find the number of characters present in the string.

Eg: s='durga' print(len(s)) #5

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Q. Write a program to access each character of string in forward and backward direction by using while loop? 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12)

s="Learning Python is very easy . " n=len(s) i=0 print("Forward direction") while i =-n: print(s[i],end=' ') i=i-1

Alternative ways: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12)

s="Learning Python is very easy . " print("Forward direction") for i in s: print(i,end=' ') print("Forward direction") for i in s[::]: print(i,end=' ') print("Backward direction") for i in s[::-1]: print(i,end=' ')

Checking Membership: We can check whether the character or string is the member of another string or not by using in and not in operators s='durga' print('d' in s) #True print('z' in s) #False

Program: 1) 2) 3) 4) 5)

s=input("Enter main string:") subs=input("Enter sub string:") if subs in s: print(subs,"is found in main string") else:

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

print(subs,"is not found in main string")

Output: D:\python_classes>py test.py Enter main string:durgasoftwaresolutions Enter sub string:durga durga is found in main string D:\python_classes>py test.py Enter main string:durgasoftwaresolutions Enter sub string:python python is not found in main string

Comparison of Strings: We can use comparison operators ( ,>=) and equality operators(==,!=) for strings. Comparison will be performed based on alphabetical order.

Eg: 1) 2) 3) 4) 5) 6) 7) 8)

Output: D:\python_classes>py test.py Enter first string:durga Enter Second string:durga Both strings are equal D:\python_classes>py test.py Enter first string:durga Enter Second string:ravi First String is less than Second String D:\python_classes>py test.py Enter first string:durga Enter Second string:anil First String is greater than Second String

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Removing spaces from the string: We can use the following 3 methods 1. rstrip()===>To remove spaces at right hand side 2. lstrip()===>To remove spaces at left hand side 3. strip() ==>To remove spaces both sides

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

city=input("Enter your city Name:") scity=city.strip() if scity=='Hyderabad': print("Hello Hyderbadi..Adab") elif scity=='Chennai': print("Hello Madrasi. Vanakkam") elif scity=="Bangalore": print("Hello Kannadiga. Shubhodaya") else: print("your entered city is invalid")

Finding Substrings: We can use the following 4 methods

For forward direction: find() index()

For backward direction: rfind() rindex()

1. find(): s.find(substring) Returns index of first occurrence of the given substring. If it is not available then we will get -1

Eg: 1) s="Learning Python is very easy"

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

print(s.find("Python")) #9 print(s.find("Java")) # -1 print(s.find("r"))#3 print(s.rfind("r"))#21

Note: By default find() method can search total string. We can also specify the boundaries to search. s.find(substring,bEgin,end) It will always search from bEgin index to end-1 index

s="durgaravipavanshiva" print(s.find('a'))#4 print(s.find('a',7,15))#10 print(s.find('z',7,15))#-1

index() method: index() method is exactly same as find() method except that if the specified substring is not available then we will get ValueError.

Eg: 1) 2) 3) 4) 5) 6) 7) 8)

s=input("Enter main string:") subs=input("Enter sub string:") try: n=s.index(subs) except ValueError: print("substring not found") else: print("substring found")

Output: D:\python_classes>py test.py Enter main string:learning python is very easy Enter sub string:python substring found D:\python_classes>py test.py Enter main string:learning python is very easy Enter sub string:java substring not found

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Q. Program to display all positions of substring in a given main string 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13)

s=input("Enter main string:") subs=input("Enter sub string:") flag=False pos=-1 n=len(s) while True: pos=s.find(subs,pos+1,n) if pos==-1: break print("Found at position",pos) flag=True if flag==False: print("Not Found")

Output: D:\python_classes>py test.py Enter main string:abbababababacdefg Enter sub string:a Found at position 0 Found at position 3 Found at position 5 Found at position 7 Found at position 9 Found at position 11 D:\python_classes>py test.py Enter main string:abbababababacdefg Enter sub string:bb Found at position 1

Counting substring in the given String: We can find the number of occurrences of substring present in the given string by using count() method. 1. s.count(substring) ==> It will search through out the string 2. s.count(substring, bEgin, end) ===> It will search from bEgin index to end-1 index

s="abcabcabcabcadda" print(s.count('a')) print(s.count('ab')) print(s.count('a',3,7))

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Replacing a string with another string: s.replace(oldstring,newstring) inside s, every occurrence of oldstring will be replaced with newstring.

Eg1: s="Learning Python is very difficult" s1=s.replace("difficult","easy") print(s1)

Output: Learning Python is very easy

Eg2: All occurrences will be replaced s="ababababababab" s1=s.replace("a","b") print(s1)

Q. String objects are immutable then how we can change the content by using replace() method. Once we creates string object, we cannot change the content.This non changeable behaviour is nothing but immutability. If we are trying to change the content by using any method, then with those changes a new object will be created and changes won't be happend in existing object. Hence with replace() method also a new object got created but existing object won't be changed.

Eg: s="abab" s1=s.replace("a","b") print(s,"is available at :",id(s)) print(s1,"is available at :",id(s1))

Output: abab is available at : 4568672 bbbb is available at : 4568704

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

In the above example, original object is available and we can see new object which was created because of replace() method.

Splitting of Strings: We can split the given string according to specified seperator by using split() method. l=s.split(seperator) The default seperator is space. The return type of split() method is List

Eg1: 1) s="durga software solutions" 2) l=s.split() 3) for x in l: 4) print(x)

Output: durga software solutions

Eg2: 1) s="22-02-2018" 2) l=s.split('-') 3) for x in l: 4) print(x)

Output: 22 02 2018

Joining of Strings: We can join a group of strings(list or tuple) wrt the given seperator. s=seperator.join(group of strings)

Eg: t=('sunny','bunny','chinny') s='-'.join(t) print(s) Output: sunny-bunny-chinny

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg2: l=['hyderabad','singapore','london','dubai'] s=':'.join(l) print(s) hyderabad:singapore:london:dubai

Changing case of a String: We can change case of a string by using the following 4 methods. 1. upper()===>To convert all characters to upper case 2. lower() ===>To convert all characters to lower case 3. swapcase()===>converts all lower case characters to upper case and all upper case characters to lower case 4. title() ===>To convert all character to title case. i.e first character in every word should be upper case and all remaining characters should be in lower case. 5. capitalize() ==>Only first character will be converted to upper case and all remaining characters can be converted to lower case

Eg: s='learning Python is very Easy' print(s.upper()) print(s.lower()) print(s.swapcase()) print(s.title()) print(s.capitalize())

Output: LEARNING PYTHON IS VERY EASY learning python is very easy LEARNING pYTHON IS VERY eASY Learning Python Is Very Easy Learning python is very easy

Checking starting and ending part of the string: Python contains the following methods for this purpose 1. s.startswith(substring) 2. s.endswith(substring)

Eg: s='learning Python is very easy' print(s.startswith('learning')) print(s.endswith('learning')) print(s.endswith('easy'))

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Output: True False True

To check type of characters present in a string: Python contains the following methods for this purpose. 1) 2) 3) 4) 5) 6) 7)

isalnum(): Returns True if all characters are alphanumeric( a to z , A to Z ,0 to9 ) isalpha(): Returns True if all characters are only alphabet symbols(a to z,A to Z) isdigit(): Returns True if all characters are digits only( 0 to 9) islower(): Returns True if all characters are lower case alphabet symbols isupper(): Returns True if all characters are upper case aplhabet symbols istitle(): Returns True if string is in title case isspace(): Returns True if string contains only spaces

Eg: print('Durga786'.isalnum()) #True print('durga786'.isalpha()) #False print('durga'.isalpha()) #True print('durga'.isdigit()) #False print('786786'.isdigit()) #True print('abc'.islower()) #True print('Abc'.islower()) #False print('abc123'.islower()) #True print('ABC'.isupper()) #True print('Learning python is Easy'.istitle()) #False print('Learning Python Is Easy'.istitle()) #True print(' '.isspace()) #True

Demo Program: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14)

s=input("Enter any character:") if s.isalnum(): print("Alpha Numeric Character") if s.isalpha(): print("Alphabet character") if s.islower(): print("Lower case alphabet character") else: print("Upper case alphabet character") else: print("it is a digit") elif s.isspace(): print("It is space character") else:

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

print("Non Space Special Character")

D:\python_classes>py test.py Enter any character:7 Alpha Numeric Character it is a digit D:\python_classes>py test.py Enter any character:a Alpha Numeric Character Alphabet character Lower case alphabet character D:\python_classes>py test.py Enter any character:$ Non Space Special Character D:\python_classes>py test.py Enter any character:A Alpha Numeric Character Alphabet character Upper case alphabet character

Formatting the Strings: We can format the strings with variable values by using replacement operator <> and format() method.

Eg: name='durga' salary=10000 age=48 print("<> 's salary is <> and his age is <>".format(name,salary,age)) print(" 's salary is and his age is ".format(name,salary,age)) print(" 's salary is and his age is ".format(z=age,y=salary,x=name))

Output: durga 's salary is 10000 and his age is 48 durga 's salary is 10000 and his age is 48 durga 's salary is 10000 and his age is 48

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Important Programs rEgarding String Concept Q1. Write a program to reverse the given String input: durga output:agrud

1st Way: s=input("Enter Some String:") print(s[::-1])

2nd Way: s=input("Enter Some String:") print(''.join(reversed(s)))

3rd Way: s=input("Enter Some String:") i=len(s)-1 target='' while i>=0: target=target+s[i] i=i-1 print(target)

Q2. Program to reverse order of words. 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12)

input: Learning Python is very Easy output: Easy Very is Python Learning s=input("Enter Some String:") l=s.split() l1=[] i=len(l)-1 while i>=0: l1.append(l[i]) i=i-1 output=' '.join(l1) print(output)

Output: Enter Some String:Learning Python is very easy!! easy. very is Python Learning

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Q3. Program to reverse internal content of each word. input: Durga Software Solutions output:agruD erawtfoS snoituloS 1) 2) 3) 4) 5) 6) 7) 8) 9)

s=input("Enter Some String:") l=s.split() l1=[] i=0 while i The corresponding character ord(character)===>The corresponding unicode value

Q8. Write a program to perform the following activity input: a4k3b2 output:aeknbd 1) s=input("Enter Some String:") 2) output='' 3) for x in s: 4) if x.isalpha(): 5) output=output+x 6) previous=x 7) else: 8) output=output+chr(ord(previous)+int(x)) 9) print(output)

Q9. Write a program to remove duplicate characters from the given input string? input: ABCDABBCDABBBCCCDDEEEF output: ABCDEF 1) 2) 3) 4) 5) 6) 7)

s=input("Enter Some String:") l=[] for x in s: if x not in l: l.append(x) output=''.join(l) print(output)

Q10. Write a program to find the number of occurrences of each character present in the given String? input: ABCABCABBCDE output: A-3,B-4,C-3,D-1,E-1 1) s=input("Enter the Some String:") 2) d=<> 3) for x in s: 4) if x in d.keys(): 5) d[x]=d[x]+1 6) else: 7) d[x]=1

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

8) for k,v in d.items(): 9) print("<> = <> Times".format(k,v))

Formatting the Strings: We can format the strings with variable values by using replacement operator <> and format() method. The main objective of format() method to format string into meaningful output form.

Case- 1: Basic Formatting for default, positional and keyword arguments name='durga' salary=10000 age=48 print("<> 's salary is <> and his age is <>".format(name,salary,age)) print(" 's salary is and his age is ".format(name,salary,age)) print(" 's salary is and his age is ".format(z=age,y=salary,x=name))

Output: durga 's salary is 10000 and his age is 48 durga 's salary is 10000 and his age is 48 durga 's salary is 10000 and his age is 48

Case-2: Formatting Numbers d--->Decimal IntEger f----->Fixed point number(float).The default precision is 6 b-->Binary format o--->Octal Format x-->Hexa Decimal Format(Lower case) X-->Hexa Decimal Format(Upper case)

Eg-1: print("The intEger number is: <>".format(123)) print("The intEger number is: ".format(123)) print("The intEger number is: ".format(123)) print("The intEger number is: ".format(123))

Output: The intEger number is: 123 The intEger number is: 123 The intEger number is: 123 The intEger number is: 00123

Eg-2: print("The float number is: <>".format(123.4567)) print("The float number is: ".format(123.4567))

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

print("The float number is: ".format(123.4567)) print("The float number is: ".format(123.4567)) print("The float number is: ".format(123.45)) print("The float number is: ".format(786786123.45))

Output: The float number is: 123.4567 The float number is: 123.456700 The float number is: 123.457 The float number is: 0123.457 The float number is: 0123.450 The float number is: 786786123.450

Note: Total positions should be minimum 8. After decimal point exactly 3 digits are allowed.If it is less then 0s will be placed in the last positions If total number is 8 positions then all intEgral digits will be considered. The extra digits we can take only 0

Note: For numbers default alignment is Right Alignment(>) Eg-3: Print Decimal value in binary, octal and hexadecimal form print("Binary Form:".format(153)) print("Octal Form:".format(153)) print("Hexa decimal Form:".format(154)) print("Hexa decimal Form:".format(154))

Output: Binary Form:10011001 Octal Form:231 Hexa decimal Form:9a Hexa decimal Form:9A

Note: We can represent only int values in binary, octal and hexadecimal and it is not possible for float values.

Note: It takes an intEger argument and assigns a minimum width of 5. It takes a float argument and assigns a minimum width of 8 including "." and after decimal point excatly 3 digits are allowed with round operation if required The blank places can be filled with 0. In this place only 0 allowed.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Case-3: Number formatting for signed numbers While displaying positive numbers,if we want to include + then we have to write

Using plus for -ve numbers there is no use and for -ve numbers - sign will come automatically. print("int value with sign:".format(123)) print("int value with sign:".format(-123)) print("float value with sign:".format(123.456)) print("float value with sign:".format(-123.456))

Output: int value with sign:+123 int value with sign:-123 float value with sign:+123.456000 float value with sign:-123.456000

Case-4: Number formatting with alignment ,^ and = are used for alignment Left Alignment to the remaining space ^===>Center alignment to the remaining space >===> Right alignment to the remaining space = ===>Forces the signed(+) (-) to the left most position

Note: Default Alignment for numbers is Right Alignment. Ex: 1) 2) 3) 4) 5) 6) 7) 8) 9)

print("".format(12)) print("".format(12)) print("05d>".format(12)) print("".format(12)) print("".format(-12)) print("".format(12.23456)) print("".format(-12.23456))

Output: 12 12 12000 12 00012 12 -12

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Case-5: String formatting with format() Similar to numbers, we can format String values also with format() method. s.format(string)

print("".format(12)) print("".format("rat")) print("5>".format("rat")) print("".format("durgasoftware")) print("".format("durgasoftware")) print("".format("durgasoftware"))

Output: dur dur dur dur *dur*

Case-7: Formatting dictionary members using format() 1) person= 2) print("'s age is: ".format(p=person))

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Output: durga's age is: 48 Note: p is alias name of dictionary person dictionary we are passing as keyword argument More convinient way is to use **person

Output: durga's age is: 48

Case-8: Formatting class members using format() Eg: 1) class Person: 2) age=48 3) name="durga" 4) print("'s age is :".format(p=Person()))

Output: durga's age is :48

Eg: 1) class Person: 2) def __init__(self,name,age): 3) self.name=name 4) self.age=age 5) print("'s age is :".format(p=Person('durga',48))) 6) print("'s age is :".format(p=Person('Ravi',50)))

Note: Here Person object is passed as keyword argument. We can access by using its reference variable in the template string

Case-9: Dynamic Formatting using format() 1) 2) 3) 4) 5)

string=">" print(string.format('cat',fill='*',align='^',width=5)) print(string.format('cat',fill='*',align='^',width=6)) print(string.format('cat',fill='*',align=' ',width=6))

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Output: *cat* *cat** cat*** ***cat

Case-10: Dynamic Float format template 1) num=".f>" 2) print(num.format(123.236,align=' ',width=8,precision=2))

Output: 123.24 123.24

Case-11: Formatting Date values 1) 2) 3) 4)

import datetime #datetime formatting date=datetime.datetime.now() print("It's now:".format(date))

Output: It's now:09/03/2018 12:36:26 Case-12: Formatting complex numbers 1) complexNumber=1+2j 2) print("Real Part: and Imaginary Part:".format(complexNumber))

Output: Real Part:1.0 and Imaginary Part:2.0

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

List Data Structure If we want to represent a group of individual objects as a single entity where insertion order preserved and duplicates are allowed, then we should go for List. insertion order preserved. duplicate objects are allowed heterogeneous objects are allowed. List is dynamic because based on our requirement we can increase the size and decrease the size. In List the elements will be placed within square brackets and with comma seperator. We can differentiate duplicate elements by using index and we can preserve insertion order by using index. Hence index will play very important role. Python supports both positive and negative indexes. +ve index means from left to right where as negative index means right to left [10,"A","B",20, 30, 10] -6 10 0

List objects are mutable.i.e we can change the content.

Creation of List Objects: 1. We can create empty list object as follows. 1) 2) 3) 4) 5) 6)

list=[] print(list) print(type(list)) []

2. If we know elements already then we can create list as follows list=[10,20,30,40]

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

3. With dynamic input: 1) 2) 3) 4) 5) 6) 7) 8)

list=eval(input("Enter List:")) print(list) print(type(list)) D:\Python_classes>py test.py Enter List:[10,20,30,40] [10, 20, 30, 40]

4. With list() function: 1) 2) 3) 4) 5) 6) 7)

l=list(range(0,10,2)) print(l) print(type(l))

s="durga" l=list(s) print(l)

D:\Python_classes>py test.py [0, 2, 4, 6, 8]

D:\Python_classes>py test.py ['d', 'u', 'r', 'g', 'a']

5. with split() function: 1) 2) 3) 4) 5) 6) 7) 8)

s="Learning Python is very very easy . " l=s.split() print(l) print(type(l)) D:\Python_classes>py test.py ['Learning', 'Python', 'is', 'very', 'very', 'easy', '. ']

Note: Sometimes we can take list inside another list,such type of lists are called nested lists. [10,20,[30,40]]

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Accessing elements of List: We can access elements of the list either by using index or by using slice operator(:)

1. By using index: List follows zero based index. ie index of first element is zero. List supports both +ve and -ve indexes. +ve index meant for Left to Right -ve index meant for Right to Left list=[10,20,30,40] -4 10 0

print(list[0]) ==>10 print(list[-1]) ==>40 print(list[10]) ==>IndexError: list index out of range

2. By using slice operator: Syntax: list2= list1[start:stop:step] start ==>it indicates the index where slice has to start default value is 0 stop ===>It indicates the index where slice has to end default value is max allowed index of list ie length of the list step ==>increment value default value is 1 Eg: 1) 2) 3) 4) 5) 6)

n=[1,2,3,4,5,6,7,8,9,10] print(n[2:7:2]) print(n[4::2]) print(n[3:7]) print(n[8:2:-2]) print(n[4:100])

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

7) 8) 9) 10) 11) 12) 13) 14)

Output D:\Python_classes>py test.py [3, 5, 7] [5, 7, 9] [4, 5, 6, 7] [9, 7, 5] [5, 6, 7, 8, 9, 10]

List vs mutability: Once we creates a List object,we can modify its content. Hence List objects are mutable. Eg: 1) 2) 3) 4) 5) 6) 7) 8)

n=[10,20,30,40] print(n) n[1]=777 print(n) D:\Python_classes>py test.py [10, 20, 30, 40] [10, 777, 30, 40]

Traversing the elements of List: The sequential access of each element in the list is called traversal.

1. By using while loop: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17)

n=[0,1,2,3,4,5,6,7,8,9,10] i=0 while i py test.py 0 1 2 3 4 5 6 7 8 9

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

2. By using for loop: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16)

n=[0,1,2,3,4,5,6,7,8,9,10] for n1 in n: print(n1) D:\Python_classes>py test.py 0 1 2 3 4 5 6 7 8 9 10

3. To display only even numbers: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12)

n=[0,1,2,3,4,5,6,7,8,9,10] for n1 in n: if n1%2==0: print(n1) D:\Python_classes>py test.py 0 2 4 6 8 10

4. To display elements by index wise: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

l=["A","B","C"] x=len(l) for i in range(x): print(l[i],"is available at positive index: ",i,"and at negative index: ",i-x) Output D:\Python_classes>py test.py A is available at positive index: 0 and at negative index: -3 B is available at positive index: 1 and at negative index: -2 C is available at positive index: 2 and at negative index: -1

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Important functions of List: I. To get information about list: 1. len(): returns the number of elements present in the list Eg: n=[10,20,30,40] print(len(n))==>4

2. count(): It returns the number of occurrences of specified item in the list 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12)

n=[1,2,2,2,2,3,3] print(n.count(1)) print(n.count(2)) print(n.count(3)) print(n.count(4)) Output D:\Python_classes>py test.py 1 4 2 0

3. index() function: returns the index of first occurrence of the specified item. Eg: 1) 2) 3) 4) 5)

n=[1,2,2,2,2,3,3] print(n.index(1)) print(n.index(2)) print(n.index(3)) print(n.index(4))

==>0 ==>1 ==>5 ==>ValueError: 4 is not in list

Note: If the specified element not present in the list then we will get ValueError.Hence before index() method we have to check whether item present in the list or not by using in operator. print( 4 in n)==>False

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

II. Manipulating elements of List: 1. append() function: We can use append() function to add item at the end of the list. Eg: 1) 2) 3) 4) 5) 6) 7) 8)

list=[] list.append("A") list.append("B") list.append("C") print(list) D:\Python_classes>py test.py ['A', 'B', 'C']

Eg: To add all elements to list upto 100 which are divisible by 10 1) 2) 3) 4) 5) 6) 7) 8) 9)

list=[] for i in range(101): if i%10==0: list.append(i) print(list)

D:\Python_classes>py test.py [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

2. insert() function: To insert item at specified index position 1) 2) 3) 4) 5) 6)

n=[1,2,3,4,5] n.insert(1,888) print(n)

n=[1,2,3,4,5] n.insert(10,777) n.insert(-10,999) print(n)

D:\Python_classes>py test.py [1, 888, 2, 3, 4, 5]

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

6) D:\Python_classes>py test.py 7) [999, 1, 2, 3, 4, 5, 777]

Note: If the specified index is greater than max index then element will be inserted at last position. If the specified index is smaller than min index then element will be inserted at first position.

Differences between append() and insert() append() In List when we add any element it will come in last i.e. it will be last element.

insert() In List we can insert any element in particular index number

3. extend() function: To add all items of one list to another list l1.extend(l2) all items present in l2 will be added to l1 Eg: 1) 2) 3) 4) 5) 6) 7)

order1=["Chicken","Mutton","Fish"] order2=["RC","KF","FO"] order1.extend(order2) print(order1)

order=["Chicken","Mutton","Fish"] order.extend("Mushroom") print(order)

D:\Python_classes>py test.py ['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']

D:\Python_classes>py test.py ['Chicken', 'Mutton', 'Fish', 'M', 'u', 's', 'h', 'r', 'o', 'o', 'm']

4. remove() function: We can use this function to remove specified item from the list.If the item present multiple times then only first occurrence will be removed.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

n=[10,20,10,30] n.remove(10) print(n) D:\Python_classes>py test.py [20, 10, 30]

If the specified item not present in list then we will get ValueError 1) 2) 3) 4) 5)

n=[10,20,10,30] n.remove(40) print(n) ValueError: list.remove(x): x not in list

Note: Hence before using remove() method first we have to check specified element present in the list or not by using in operator.

5. pop() function: It removes and returns the last element of the list. This is only function which manipulates list and returns some element. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9)

n=[10,20,30,40] print(n.pop()) print(n.pop()) print(n) D:\Python_classes>py test.py 40 30 [10, 20]

If the list is empty then pop() function raises IndexError Eg: 1) n=[] 2) print(n.pop()) ==> IndexError: pop from empty list

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Note: 1. pop() is the only function which manipulates the list and returns some value 2. In general we can use append() and pop() functions to implement stack datastructure by using list,which follows LIFO(Last In First Out) order. In general we can use pop() function to remove last element of the list. But we can use to remove elements based on index. n.pop(index)===>To remove and return element present at specified index. n.pop()==>To remove and return last element of the list 1) 2) 3) 4)

n=[10,20,30,40,50,60] print(n.pop()) #60 print(n.pop(1)) #20 print(n.pop(10)) ==>IndexError: pop index out of range

Differences between remove() and pop() remove() 1) We can use to remove special element from the List. 2) It can’t return any value. 3) If special element not available then we get VALUE ERROR.

pop() 1) We can use to remove last element from the List. 2) It returned removed element. 3) If List is empty then we get Error.

Note: List objects are dynamic. i.e based on our requirement we can increase and decrease the size. append(),insert() ,extend() ===>for increasing the size/growable nature remove(), pop() ======>for decreasing the size /shrinking nature

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

III. Ordering elements of List: 1. reverse(): We can use to reverse() order of elements of list. 1) 2) 3) 4) 5) 6)

n=[10,20,30,40] n.reverse() print(n) D:\Python_classes>py test.py [40, 30, 20, 10]

2. sort() function: In list by default insertion order is preserved. If want to sort the elements of list according to default natural sorting order then we should go for sort() method. For numbers ==>default natural sorting order is Ascending Order For Strings ==> default natural sorting order is Alphabetical Order 1) 2) 3) 4) 5) 6) 7)

n=[20,5,15,10,0] n.sort() print(n) #[0,5,10,15,20] s=["Dog","Banana","Cat","Apple"] s.sort() print(s) #['Apple','Banana','Cat','Dog']

Note: To use sort() function, compulsory list should contain only homogeneous elements. otherwise we will get TypeError Eg: 1) n=[20,10,"A","B"] 2) n.sort() 3) print(n) 4) 5) TypeError: ' [10,20,30,40] n.sort(reverse=True) print(n) ===>[40,30,20,10] n.sort(reverse=False) print(n) ==>[10,20,30,40]

Aliasing and Cloning of List objects: The process of giving another reference variable to the existing list is called aliasing. Eg: 1) x=[10,20,30,40] 2) y=x 3) print(id(x)) 4) print(id(y))

The problem in this approach is by using one reference variable if we are changing content,then those changes will be reflected to the other reference variable. 1) 2) 3) 4)

x=[10,20,30,40] y=x y[1]=777 print(x) ==>[10,777,30,40]

To overcome this problem we should go for cloning. The process of creating exactly duplicate independent object is called cloning. We can implement cloning by using slice operator or by using copy() function

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

1. By using slice operator: 1) 2) 3) 4) 5)

x=[10,20,30,40] y=x[:] y[1]=777 print(x) ==>[10,20,30,40] print(y) ==>[10,777,30,40]

2. By using copy() function: 1) 2) 3) 4) 5)

x=[10,20,30,40] y=x.copy() y[1]=777 print(x) ==>[10,20,30,40] print(y) ==>[10,777,30,40]

Q. Difference between = operator and copy() function = operator meant for aliasing copy() function meant for cloning

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Using Mathematical operators for List Objects: We can use + and * operators for List objects.

1. Concatenation operator(+): We can use + to concatenate 2 lists into a single list 1) 2) 3) 4)

a=[10,20,30] b=[40,50,60] c=a+b print(c) ==>[10,20,30,40,50,60]

Note: To use + operator compulsory both arguments should be list objects,otherwise we will get TypeError. Eg: c=a+40 c=a+[40]

==>TypeError: can only concatenate list (not "int") to list ==>valid

2. Repetition Operator(*): We can use repetition operator * to repeat elements of list specified number of times Eg: 1) x=[10,20,30] 2) y=x*3 3) print(y)==>[10,20,30,10,20,30,10,20,30]

Comparing List objects We can use comparison operators for List objects. Eg: 1. 2. 3. 4. 5. 6.

x=["Dog","Cat","Rat"] y=["Dog","Cat","Rat"] z=["DOG","CAT","RAT"] print(x==y) True print(x==z) False print(x != z) True

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Note: Whenever we are using comparison operators(==,!=) for List objects then the following should be considered 1. The number of elements 2. The order of elements 3. The content of elements (case sensitive)

Note: When ever we are using relatational operators( ,>=) between List objects,only first element comparison will be performed. Eg: 1. 2. 3. 4. 5. 6.

x=[50,20,30] y=[40,50,60,100,200] print(x>y) True print(x>=y) True print(x y) False print(x>=y) False print(x py test.py [10, 20, 30, 40] []

Nested Lists: Sometimes we can take one list inside another list. Such type of lists are called nested lists. Eg: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14.

n=[10,20,[30,40]] print(n) print(n[0]) print(n[2]) print(n[2][0]) print(n[2][1]) Output D:\Python_classes>py test.py [10, 20, [30, 40]] 10 [30, 40] 30 40

Note: We can access nested list elements by using index just like accessing multi dimensional array elements.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Nested List as Matrix: In Python we can represent matrix by using nested lists. 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22)

n=[[10,20,30],[40,50,60],[70,80,90]] print(n) print("Elements by Row wise:") for r in n: print(r) print("Elements by Matrix style:") for i in range(len(n)): for j in range(len(n[i])): print(n[i][j],end=' ') print() Output D:\Python_classes>py test.py [[10, 20, 30], [40, 50, 60], [70, 80, 90]] Elements by Row wise: [10, 20, 30] [40, 50, 60] [70, 80, 90] Elements by Matrix style: 10 20 30 40 50 60 70 80 90

List Comprehensions: It is very easy and compact way of creating list objects from any iterable objects(like list,tuple,dictionary,range etc) based on some condition. Syntax: list=[expression for item in list if condition] Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

s=[ x*x for x in range(1,11)] print(s) v=[2**x for x in range(1,6)] print(v) m=[x for x in s if x%2==0] print(m) Output D:\Python_classes>py test.py [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

11) [2, 4, 8, 16, 32] 12) [4, 16, 36, 64, 100]

words=["Balaiah","Nag","Venkatesh","Chiranjeevi"] l=[w[0] for w in words] print(l)

1) 2) 3) 4) 5) 6) 7) 8)

num1=[10,20,30,40] num2=[30,40,50,60] num3=[ i for i in num1 if i not in num2] print(num3) [10,20]

1) 2) 3) 4) 5) 6) 7) 8) 9)

words="the quick brown fox jumps over the lazy dog".split() print(words) l=[[w.upper(),len(w)] for w in words] print(l)

common elements present in num1 and num2 num4=[i for i in num1 if i in num2] print(num4) [30, 40]

Output ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog'] [['THE', 3], ['QUICK', 5], ['BROWN', 5], ['FOX', 3], ['JUMPS', 5], ['OVER', 4], ['THE', 3], ['LAZY', 4], ['DOG', 3]]

Q. Write a program to display unique vowels present in the given word? 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12)

vowels=['a','e','i','o','u'] word=input("Enter the word to search for vowels: ") found=[] for letter in word: if letter in vowels: if letter not in found: found.append(letter) print(found) print("The number of different vowels present in",word,"is",len(found))

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

13) Enter the word to search for vowels: durgasoftwaresolutions 14) ['u', 'a', 'o', 'e', 'i'] 15) The number of different vowels present in durgasoftwaresolutions is 5

list out all functions of list and write a program to use these functions

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Tuple Data Structure 1. Tuple is exactly same as List except that it is immutable. i.e once we creates Tuple object,we cannot perform any changes in that object. Hence Tuple is Read Only version of List. 2. If our data is fixed and never changes then we should go for Tuple. 3. Insertion Order is preserved 4. Duplicates are allowed 5. Heterogeneous objects are allowed. 6. We can preserve insertion order and we can differentiate duplicate objects by using index. Hence index will play very important role in Tuple also. Tuple support both +ve and -ve index. +ve index means forward direction(from left to right) and -ve index means backward direction(from right to left) 7. We can represent Tuple elements within Parenthesis and with comma seperator. Parenethesis are optional but recommended to use. Eg: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

t=10,20,30,40 print(t) print(type(t)) Output (10, 20, 30, 40) t=() print(type(t)) # tuple

Note: We have to take special care about single valued tuple.compulsary the value should ends with comma,otherwise it is not treated as tuple. Eg: 1. 2. 3. 4. 5. 6. 7.

t=(10) print(t) print(type(t)) Output 10

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: 1. 2. 3. 4. 5. 6. 7.

t=(10,) print(t) print(type(t)) Output (10,)

Q. Which of the following are valid tuples? 1. t=() 2. t=10,20,30,40 3. t=10 4. t=10, 5. t=(10) 6. t=(10,) 7.t=(10,20,30,40)

Tuple creation: 1. t=() creation of empty tuple

2. t=(10,) t=10, creation of single valued tuple ,parenthesis are optional,should ends with comma

3. t=10,20,30 t=(10,20,30) creation of multi values tuples & parenthesis are optional

4. By using tuple() function: 1. list=[10,20,30] 2. t=tuple(list) 3. print(t) 4. 5. t=tuple(range(10,20,2)) 6. print(t)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Accessing elements of tuple: We can access either by index or by slice operator

1. By using index: 1. 2. 3. 4.

t=(10,20,30,40,50,60) print(t[0]) #10 print(t[-1]) #60 print(t[100]) IndexError: tuple index out of range

2. By using slice operator: 1. 2. 3. 4. 5. 6. 7. 8. 9.

t=(10,20,30,40,50,60) print(t[2:5]) print(t[2:100]) print(t[::2]) Output (30, 40, 50) (30, 40, 50, 60) (10, 30, 50)

Tuple vs immutability: Once we creates tuple,we cannot change its content. Hence tuple objects are immutable. Eg: t=(10,20,30,40) t[1]=70

TypeError: 'tuple' object does not support item assignment

Mathematical operators for tuple: We can apply + and * operators for tuple

1. Concatenation Operator(+): 1. 2. 3. 4.

t1=(10,20,30) t2=(40,50,60) t3=t1+t2 print(t3) # (10,20,30,40,50,60)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

2. Multiplication operator or repetition operator(*) 1. t1=(10,20,30) 2. t2=t1*3 3. print(t2) #(10,20,30,10,20,30,10,20,30)

Important functions of Tuple: 1. len() To return number of elements present in the tuple Eg: t=(10,20,30,40) print(len(t)) #4

2. count() To return number of occurrences of given element in the tuple Eg: t=(10,20,10,10,20) print(t.count(10)) #3

3. index() returns index of first occurrence of the given element. If the specified element is not available then we will get ValueError. Eg: t=(10,20,10,10,20) print(t.index(10)) #0 print(t.index(30)) ValueError: tuple.index(x): x not in tuple

4. sorted() To sort elements based on default natural sorting order 1. 2. 3. 4. 5. 6. 7. 8.

t=(40,10,30,20) t1=sorted(t) print(t1) print(t) Output [10, 20, 30, 40] (40, 10, 30, 20)

We can sort according to reverse of default natural sorting order as follows

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

t1=sorted(t,reverse=True) print(t1) [40, 30, 20, 10]

5. min() and max() functions: These functions return min and max values according to default natural sorting order. Eg: 1. t=(40,10,30,20) 2. print(min(t)) #10 3. print(max(t)) #40

6. cmp(): It compares the elements of both tuples. If both tuples are equal then returns 0 If the first tuple is less than second tuple then it returns -1 If the first tuple is greater than second tuple then it returns +1 Eg: 1. 2. 3. 4. 5. 6.

t1=(10,20,30) t2=(40,50,60) t3=(10,20,30) print(cmp(t1,t2)) # -1 print(cmp(t1,t3)) # 0 print(cmp(t2,t3)) # +1

Note: cmp() function is available only in Python2 but not in Python 3

Tuple Packing and Unpacking: We can create a tuple by packing a group of variables. Eg: a=10 b=20 c=30 d=40 t=a,b,c,d print(t) #(10, 20, 30, 40) Here a,b,c,d are packed into a tuple t. This is nothing but tuple packing.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Tuple unpacking is the reverse process of tuple packing We can unpack a tuple and assign its values to different variables Eg: 1. 2. 3. 4. 5. 6.

t=(10,20,30,40) a,b,c,d=t print("a=",a,"b=",b,"c=",c,"d Enter Tuple of Numbers:")) l=len(t) sum=0 for x in t: sum=sum+x print("The Sum=",sum) print("The Average durga") print(s) print('d' in s) print('z' in s) Output True False

Set Comprehension: Set comprehension is possible. s= print(s) #

set objects won't support indexing and slicing: Eg: s= print(s[0]) ==>TypeError: 'set' object does not support indexing print(s[1:3]) ==>TypeError: 'set' object is not subscriptable

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Q.Write a program to eliminate duplicates present in the list? Approach-1: 1. 2. 3. 4. 5. 6. 7. 8.

l=eval(input("Enter List of values: ")) s=set(l) print(s) Output D:\Python_classes>py test.py Enter List of values: [10,20,30,10,20,40]

Approach-2: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

l=eval(input("Enter List of values: ")) l1=[] for x in l: if x not in l1: l1.append(x) print(l1) Output D:\Python_classes>py test.py Enter List of values: [10,20,30,10,20,40] [10, 20, 30, 40]

Q. Write a program to print different vowels present in the given word? 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

w=input("Enter word to search for vowels: ") s=set(w) v= d=s.intersection(v) print("The different vowel present in",w,"are",d) Output D:\Python_classes>py test.py Enter word to search for vowels: durga The different vowel present in durga are

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Dictionary Data Structure We can use List,Tuple and Set to represent a group of individual objects as a single entity. If we want to represent a group of objects as key-value pairs then we should go for Dictionary. Eg: rollno----name phone number--address ipaddress---domain name Duplicate keys are not allowed but values can be duplicated. Hetrogeneous objects are allowed for both key and values. insertion order is not preserved Dictionaries are mutable Dictionaries are dynamic indexing and slicing concepts are not applicable

Note: In C++ and Java Dictionaries are known as "Map" where as in Perl and Ruby it is known as "Hash"

How to create Dictionary? d=<> or d=dict() we are creating empty dictionary. We can add entries as follows d[100]="durga" d[200]="ravi" d[300]="shiva" print(d) # If we know data in advance then we can create dictionary as follows d= d=

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

How to access data from the dictionary? We can access data by using keys. d= print(d[100]) #durga print(d[300]) #shiva If the specified key is not available then we will get KeyError print(d[400]) # KeyError: 400 We can prevent this by checking whether key is already available or not by using has_key() function or by using in operator. d.has_key(400) ==> returns 1 if key is available otherwise returns 0 But has_key() function is available only in Python 2 but not in Python 3. Hence compulsory we have to use in operator. if 400 in d: print(d[400])

Q. Write a program to enter name and percentage marks in a dictionary and display information on the screen 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20)

rec=<> n=int(input("Enter number of students: ")) i=1 while i py test.py Enter number of students: 3 Enter Student Name: durga Enter % of Marks of Student: 60% Enter Student Name: ravi Enter % of Marks of Student: 70% Enter Student Name: shiva

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

21) Enter % of Marks of Student: 80% 22) Name of Student % of marks 23) durga 60% 24) ravi 70 % 25) shiva 80%

How to update dictionaries? d[key]=value If the key is not available then a new entry will be added to the dictionary with the specified key-value pair If the key is already available then old value will be replaced with new value. Eg: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

How to delete elements from dictionary? del d[key] It deletes entry associated with the specified key. If the key is not available then we will get KeyError Eg: 1. 2. 3. 4. 5. 6. 7. 8.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

d.clear() To remove all entries from the dictionary Eg: 1. 2. 3. 4. 5. 6. 7. 8.

del d To delete total dictionary.Now we cannot access d Eg: 1. 2. 3. 4. 5. 6. 7. 8.

Important functions of dictionary: 1. dict(): To create a dictionary d=dict() ===>It creates empty dictionary d=dict() ==>It creates dictionary with specified elements d=dict([(100,"durga"),(200,"shiva"),(300,"ravi")])==>It creates dictionary with the given list of tuple elements

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

2. len() Returns the number of items in the dictionary

3. clear(): To remove all elements from the dictionary

4. get(): To get the value associated with the key d.get(key) If the key is available then returns the corresponding value otherwise returns None.It wont raise any error. d.get(key,defaultvalue) If the key is available then returns the corresponding value otherwise returns default value. Eg: d= print(d[100]) ==>durga print(d[400]) ==>KeyError:400 print(d.get(100)) ==durga print(d.get(400)) ==>None print(d.get(100,"Guest")) ==durga print(d.get(400,"Guest")) ==>Guest

3. pop(): d.pop(key) It removes the entry associated with the specified key and returns the corresponding value If the specified key is not available then we will get KeyError Eg: 1) 2) 3) 4) 5) 6)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

4. popitem(): It removes an arbitrary item(key-value) from the dictionaty and returns it. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9)

If the dictionary is empty then we will get KeyError d=<> print(d.popitem()) ==>KeyError: 'popitem(): dictionary is empty'

5. keys(): It returns all keys associated eith dictionary Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

d= print(d.keys()) for k in d.keys(): print(k) Output dict_keys([100, 200, 300]) 100 200 300

6. values(): It returns all values

associated with the dictionary

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

d= print(d.values()) for v in d.values(): print(v) Output dict_values(['durga', 'ravi', 'shiva']) durga ravi shiva

7. items(): It returns list of tuples representing key-value pairs. [(k,v),(k,v),(k,v)] Eg: 1. 2. 3. 4. 5. 6. 7. 8.

d= for k,v in d.items(): print(k,"--",v) Output 100 -- durga 200 -- ravi 300 -- shiva

8. copy(): To create exactly duplicate dictionary(cloned copy) d1=d.copy();

9. setdefault(): d.setdefault(k,v) If the key is already available then this function returns the corresponding value. If the key is not available then the specified key-value will be added as new item to the dictionary.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

10. update(): d.update(x) All items present in the dictionary x will be added to dictionary d

Q. Write a program to take dictionary from the keyboard and print the sum of values? 1. 2. 3. 4. 5. 6. 7. 8.

d=eval(input("Enter dictionary:")) s=sum(d.values()) print("Sum Enter any word: ") d=<> for x in word: d[x]=d.get(x,0)+1 for k,v in d.items(): print(k,"occurred ",v," times") Output D:\Python_classes>py test.py Enter any word: mississippi m occurred 1 times i occurred 4 times s occurred 4 times

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

14. p occurred 2 times

Q. Write a program to find number of occurrences of each vowel present in the given string? 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15.

word=input("Enter any word: ") vowels= d=<> for x in word: if x in vowels: d[x]=d.get(x,0)+1 for k,v in sorted(d.items()): print(k,"occurred ",v," times") Output D:\Python_classes>py test.py Enter any word: doganimaldoganimal a occurred 4 times i occurred 2 times o occurred 2 times

Q. Write a program to accept student name and marks from the keyboard and creates a dictionary. Also display student marks by taking student name as input? 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23)

n=int(input("Enter the number of students: ")) d=<> for i in range(n): name=input("Enter Student Name: ") marks=input("Enter Student Marks: ") d[name]=marks while True: name=input("Enter Student Name to get Marks: ") marks=d.get(name,-1) if marks== -1: print("Student Not Found") else: print("The Marks of",name,"are",marks) option=input("Do you want to find another student marks[Yes|No]") if option=="No": break print("Thanks for using our application") Output D:\Python_classes>py test.py Enter the number of students: 5 Enter Student Name: sunny Enter Student Marks: 90

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

24) 25) 26) 27) 28) 29) 30) 31) 32) 33) 34) 35) 36) 37) 38)

Enter Student Name: banny Enter Student Marks: 80 Enter Student Name: chinny Enter Student Marks: 70 Enter Student Name: pinny Enter Student Marks: 60 Enter Student Name: vinny Enter Student Marks: 50 Enter Student Name to get Marks: sunny The Marks of sunny are 90 Do you want to find another student marks[Yes|No]Yes Enter Student Name to get Marks: durga Student Not Found Do you want to find another student marks[Yes|No]No Thanks for using our application

Dictionary Comprehension: Comprehension concept applicable for dictionaries also. 1. 2. 3. 4. 5. 6. 7. 8.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

FUNCTIONS If a group of statements is repeatedly required then it is not recommended to write these statements everytime seperately.We have to define these statements as a single unit and we can call that unit any number of times based on our requirement without rewriting. This unit is nothing but function. The main advantage of functions is code Reusability. Note: In other languages functions are known as methods,procedures,subroutines etc Python supports 2 types of functions 1. Built in Functions 2. User Defined Functions

1. Built in Functions: The functions which are coming along with Python software automatically,are called built in functions or pre defined functions Eg: id() type() input() eval() etc..

2. User Defined Functions: The functions which are developed by programmer explicitly according to business requirements ,are called user defined functions.

Syntax to create user defined functions: def function_name(parameters) : """ doc string""" -------return value

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Note: While creating functions we can use 2 keywords 1. def (mandatory) 2. return (optional) Eg 1: Write a function to print Hello

test.py: 1) 2) 3) 4) 5)

def wish(): print("Hello Good Morning") wish() wish() wish()

Parameters Parameters are inputs to the function. If a function contains parameters,then at the time of calling,compulsory we should provide values otherwise,otherwise we will get error. Eg: Write a function to take name of the student as input and print wish message by name. 1. 2. 3. 4. 5. 6. 7. 8. 9.

def wish(name): print("Hello",name," Good Morning") wish("Durga") wish("Ravi")

D:\Python_classes>py test.py Hello Durga Good Morning Hello Ravi Good Morning

Eg: Write a function to take number as input and print its square value 1. 2. 3. 4. 5. 6. 7. 8.

def squareIt(number): print("The Square of",number,"is", number*number) squareIt(4) squareIt(5) D:\Python_classes>py test.py The Square of 4 is 16 The Square of 5 is 25

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Return Statement: Function can take input values as parameters and executes business logic, and returns output to the caller with return statement.

Q. Write a function to accept 2 numbers as input and return sum. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

def add(x,y): return x+y result=add(10,20) print("The sum is",result) print("The sum is",add(100,200))

D:\Python_classes>py test.py The sum is 30 The sum is 300

If we are not writing return statement then default return value is None Eg: 1. 2. 3. 4. 5. 6. 7. 8.

def f1(): print("Hello") f1() print(f1()) Output Hello Hello None

Q. Write a function to check whether the given number is even or odd? 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.

def even_odd(num): if num%2==0: print(num,"is Even Number") else: print(num,"is Odd Number") even_odd(10) even_odd(15) Output D:\Python_classes>py test.py 10 is Even Number 15 is Odd Number

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Q. Write a function to find factorial of given number? 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15)

def fact(num): result=1 while num>=1: result=result*num num=num-1 return result for i in range(1,5): print("The Factorial of",i,"is :",fact(i)) Output D:\Python_classes>py test.py The Factorial of 1 is : 1 The Factorial of 2 is : 2 The Factorial of 3 is : 6 The Factorial of 4 is : 24

Returning multiple values from a function: In other languages like C,C++ and Java, function can return atmost one value. But in Python, a function can return any number of values. Eg 1: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11)

def sum_sub(a,b): sum=a+b sub=a-b return sum,sub x,y=sum_sub(100,50) print("The Sum is :",x) print("The Subtraction is :",y) Output The Sum is : 150 The Subtraction is : 50

Eg 2: 1) def calc(a,b): 2) sum=a+b 3) sub=a-b 4) mul=a*b 5) div=a/b 6) return sum,sub,mul,div 7) t=calc(100,50) 8) print("The Results are")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

9) 10) 11) 12) 13) 14) 15) 16) 17)

for i in t: print(i) Output The Results are 150 50 5000 2.0

Types of arguments def f1(a,b): ---------------f1(10,20) a,b are formal arguments where as 10,20 are actual arguments There are 4 types are actual arguments are allowed in Python. 1. positional arguments 2. keyword arguments 3. default arguments 4. Variable length arguments

1. positional arguments: These are the arguments passed to function in correct positional order. def sub(a,b): print(a-b) sub(100,200) sub(200,100) The number of arguments and position of arguments must be matched. If we change the order then result may be changed. If we change the number of arguments then we will get error.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

2. keyword arguments: We can pass argument values by keyword i.e by parameter name. Eg: 1. 2. 3. 4. 5. 6. 7. 8.

def wish(name,msg): print("Hello",name,msg) wish(name="Durga",msg="Good Morning") wish(msg="Good Morning",name="Durga") Output Hello Durga Good Morning Hello Durga Good Morning

Here the order of arguments is not important but number of arguments must be matched. Note: We can use both positional and keyword arguments simultaneously. But first we have to take positional arguments and then keyword arguments,otherwise we will get syntaxerror. def wish(name,msg): print("Hello",name,msg) wish("Durga","GoodMorning") ==>valid wish("Durga",msg="GoodMorning") ==>valid wish(name="Durga","GoodMorning") ==>invalid SyntaxError: positional argument follows keyword argument

3. Default Arguments: Sometimes we can provide default values for our positional arguments. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9)

def wish(name="Guest"): print("Hello",name,"Good Morning") wish("Durga") wish() Output Hello Durga Good Morning Hello Guest Good Morning

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

If we are not passing any name then only default value will be considered. ***Note: After default arguments we should not take non default arguments def wish(name="Guest",msg="Good Morning"): ===>Valid def wish(name,msg="Good Morning"): ===>Valid def wish(name="Guest",msg): ==>Invalid SyntaxError: non-default argument follows default argument

4. Variable length arguments: Sometimes we can pass variable number of arguments to our function,such type of arguments are called variable length arguments. We can declare a variable length argument with * symbol as follows def f1(*n): We can call this function by passing any number of arguments including zero number. Internally all these values represented in the form of tuple. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16)

def sum(*n): total=0 for n1 in n: total=total+n1 print("The Sum A",30,"B") Output 10 10 20 30 40 10 A 30 B

Note: After variable length argument,if we are taking any other arguments then we should provide values as keyword arguments. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

def f1(*s,n1): for s1 in s: print(s1) print(n1) f1("A","B",n1=10) Output A B 10

f1("A","B",10) ==>Invalid TypeError: f1() missing 1 required keyword-only argument: 'n1'

Note: We can declare key word variable length arguments also. For this we have to use **. def f1(**n):

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

We can call this function by passing any number of keyword arguments. Internally these keyword arguments will be stored inside a dictionary. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14)

def display(**kwargs): for k,v in kwargs.items(): print(k,"=",v) display(n1=10,n2=20,n3=30) display(rno=100,name="Durga",marks=70,subject="Java") Output n1 = 10 n2 = 20 n3 = 30 rno = 100 name = Durga marks = 70 subject = Java

Case Study: def f(arg1,arg2,arg3=4,arg4=8): print(arg1,arg2,arg3,arg4)

2. f(10,20,30,40) ===>10 20 30 40 3. f(25,50,arg4=100) ==>25 50 4 100 4. f(arg4=2,arg1=3,arg2=4)===>3 4 4 2 5. f()===>Invalid TypeError: f() missing 2 required positional arguments: 'arg1' and 'arg2' 6. f(arg3=10,arg4=20,30,40) ==>Invalid SyntaxError: positional argument follows keyword argument [After keyword arguments we should not take positional arguments] 7. f(4,5,arg2=6)==>Invalid TypeError: f() got multiple values for argument 'arg2' 8. f(4,5,arg3=5,arg5=6)==>Invalid TypeError: f() got an unexpected keyword argument 'arg5'

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Note: Function vs Module vs Library: 1. A group of lines with some name is called a function 2. A group of functions saved to a file , is called Module 3. A group of Modules is nothing but Library Function

Library Module 1

Types of Variables Python supports 2 types of variables. 1. Global Variables 2. Local Variables

1. Global Variables The variables which are declared outside of function are called global variables. These variables can be accessed in all functions of that module. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13)

a=10 # global variable def f1(): print(a) def f2(): print(a) f1() f2() Output 10 10

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

2. Local Variables: The variables which are declared inside a function are called local variables. Local variables are available only for the function in which we declared it.i.e from outside of function we cannot access. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11)

def f1(): a=10 print(a) # valid def f2(): print(a)

f1() f2() NameError: name 'a' is not defined

global keyword: We can use global keyword for the following 2 purposes: 1. To declare global variable inside function 2. To make global variable available to the function so that we can perform required modifications Eg 1: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14)

a=10 def f1(): a=777 print(a) def f2(): print(a) f1() f2() Output 777 10

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg 2: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15)

a=10 def f1(): global a a=777 print(a) def f2(): print(a) f1() f2() Output 777 777

Eg 3: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11)

def f1(): a=10 print(a) def f2(): print(a) f1() f2() NameError: name 'a' is not defined

Eg 4: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14)

def f1(): global a a=10 print(a) def f2(): print(a) f1() f2() Output 10 10

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Note: If global variable and local variable having the same name then we can access global variable inside a function as follows 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11)

a=10 #global variable def f1(): a=777 #local variable print(a) print(globals()['a']) f1()

Recursive Functions A function that calls itself is known as Recursive Function. Eg: factorial(3)=3*factorial(2) =3*2*factorial(1) =3*2*1*factorial(0) =3*2*1*1 =6 factorial(n)= n*factorial(n-1) The main advantages of recursive functions are: 1. We can reduce length of the code and improves readability 2. We can solve complex problems very easily.

Q. Write a Python Function to find factorial of given number with recursion. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

def factorial(n): if n==0: result=1 else: result=n*factorial(n-1) return result print("Factorial of 4 is :",factorial(4)) print("Factorial of 5 is :",factorial(5)) Output

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

11) Factorial of 4 is : 24 12) Factorial of 5 is : 120

Anonymous Functions: Sometimes we can declare a function without any name,such type of nameless functions are called anonymous functions or lambda functions. The main purpose of anonymous function is just for instant use(i.e for one time usage)

Normal Function: We can define by using def keyword. def squareIt(n): return n*n

lambda Function: We can define by using lambda keyword lambda n:n*n

Syntax of lambda Function: lambda argument_list : expression

Note: By using Lambda Functions we can write very concise code so that readability of the program will be improved.

Q. Write a program to create a lambda function to find square of given number? 1) 2) 3) 4) 5) 6) 7)

s=lambda n:n*n print("The Square of 4 is :",s(4)) print("The Square of 5 is :",s(5)) Output The Square of 4 is : 16 The Square of 5 is : 25

Q. Lambda function to find sum of 2 given numbers 1) s=lambda a,b:a+b 2) print("The Sum of 10,20 is:",s(10,20))

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

print("The Sum of 100,200 is:",s(100,200)) Output The Sum of 10,20 is: 30 The Sum of 100,200 is: 300

Q. Lambda Function to find biggest of given values. 1) 2) 3) 4) 5) 6) 7)

s=lambda a,b:a if a>b else b print("The Biggest of 10,20 is:",s(10,20)) print("The Biggest of 100,200 is:",s(100,200)) Output The Biggest of 10,20 is: 20 The Biggest of 100,200 is: 200

Note: Lambda Function internally returns expression value and we are not required to write return statement explicitly.

Note: Sometimes we can pass function as argument to another function. In such cases lambda functions are best choice. We can use lambda functions very commonly with filter(),map() and reduce() functions,b'z these functions expect function as argument.

filter() function: We can use filter() function to filter values from the given sequence based on some condition. filter(function,sequence) where function argument is responsible to perform conditional check sequence can be list or tuple or string.

Q. Program to filter only even numbers from the list by using filter() function?

without lambda Function: 1) def isEven(x): 2) if x%2==0: 3) return True 4) else:

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

5) return False 6) l=[0,5,10,15,20,25,30] 7) l1=list(filter(isEven,l)) 8) print(l1) #[0,10,20,30]

with lambda Function: 1) 2) 3) 4) 5)

l=[0,5,10,15,20,25,30] l1=list(filter(lambda x:x%2==0,l)) print(l1) #[0,10,20,30] l2=list(filter(lambda x:x%2!=0,l)) print(l2) #[5,15,25]

map() function: For every element present in the given sequence,apply some functionality and generate new element with the required modification. For this requirement we should go for map() function. Eg: For every element present in the list perform double and generate new list of doubles.

Syntax: map(function,sequence) The function can be applied on each element of sequence and generates new sequence.

Eg: Without lambda 1) l=[1,2,3,4,5] 2) def doubleIt(x): 3) return 2*x 4) l1=list(map(doubleIt,l)) 5) print(l1) #[2, 4, 6, 8, 10]

with lambda 1) l=[1,2,3,4,5] 2) l1=list(map(lambda x:2*x,l)) 3) print(l1) #[2, 4, 6, 8, 10]

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg 2: To find square of given numbers 1. l=[1,2,3,4,5] 2. l1=list(map(lambda x:x*x,l)) 3. print(l1) #[1, 4, 9, 16, 25]

We can apply map() function on multiple lists also.But make sure all list should have same length. Syntax: map(lambda x,y:x*y,l1,l2)) x is from l1 and y is from l2 Eg: 1. 2. 3. 4.

l1=[1,2,3,4] l2=[2,3,4,5] l3=list(map(lambda x,y:x*y,l1,l2)) print(l3) #[2, 6, 12, 20]

reduce() function: reduce() function reduces sequence of elements into a single element by applying the specified function. reduce(function,sequence) reduce() function present in functools module and hence we should write import statement. Eg: 1) 2) 3) 4)

from functools import * l=[10,20,30,40,50] result=reduce(lambda x,y:x+y,l) print(result) # 150

Eg: 1) result=reduce(lambda x,y:x*y,l) 2) print(result) #12000000

Eg: 1) from functools import * 2) result=reduce(lambda x,y:x+y,range(1,101)) 3) print(result) #5050

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

In Python every thing is treated as object. Even functions also internally treated as objects only.

Eg: 1) def f1(): 2) print("Hello") 3) print(f1) 4) print(id(f1))

Function Aliasing: For the existing function we can give another name, which is nothing but function aliasing.

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9)

def wish(name): print("Good Morning:",name) greeting=wish print(id(wish)) print(id(greeting)) greeting('Durga') wish('Durga')

Output 4429336 4429336 Good Morning: Durga Good Morning: Durga

Note: In the above example only one function is available but we can call that function by using either wish name or greeting name. If we delete one name still we can access that function by using alias name

Eg: 1) def wish(name): 2) print("Good Morning:",name)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

3) 4) 5) 6) 7) 8) 9) 10) 11)

greeting=wish greeting('Durga') wish('Durga') del wish #wish('Durga') ==>NameError: name 'wish' is not defined greeting('Pavan')

Output Good Morning: Durga Good Morning: Durga Good Morning: Pavan

Nested Functions: We can declare a function inside another function, such type of functions are called Nested functions.

Eg: 1) def outer(): 2) print("outer function started") 3) def inner(): 4) print("inner function execution") 5) print("outer function calling inner function") 6) inner() 7) outer() 8) #inner() ==>NameError: name 'inner' is not defined

Output outer function started outer function calling inner function inner function execution In the above example inner() function is local to outer() function and hence it is not possible to call directly from outside of outer() function.

Note: A function can return another function. Eg: 1) def outer(): 2) print("outer function started") 3) def inner(): 4) print("inner function execution")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

print("outer function returning inner function") return inner f1=outer() f1() f1() f1()

Output outer function started outer function returning inner function inner function execution inner function execution inner function execution

Q. What is the differenece between the following lines? f1 = outer f1 = outer()  

In the first case for the outer() function we are providing another name f1(function aliasing). But in the second case we calling outer() function,which returns inner function.For that inner function() we are providing another name f1

Note: We can pass function as argument to another function Eg: filter(function,sequence) map(function,sequence) reduce(function,sequence)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Function Decorators: Decorator is a function which can take a function as argument and extend its functionality and returns modified function with extended functionality. Input Function wish()

new(add some functionality) inner()

Output Function with extended Functionality

The main objective of decorator functions is we can extend the functionality of existing functions without modifies that function. 1) 2)

def wish(name): print("Hello",name,"Good Morning")

This function can always print same output for any name Hello Durga Good Morning Hello Ravi Good Morning Hello Sunny Good Morning But we want to modify this function to provide different message if name is Sunny. We can do this without touching wish() function by using decorator. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16)

def decor(func): def inner(name): if name=="Sunny": print("Hello Sunny Bad Morning") else: func(name) return inner @decor def wish(name): print("Hello",name,"Good Morning") wish("Durga") wish("Ravi") wish("Sunny")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Output Hello Durga Good Morning Hello Ravi Good Morning Hello Sunny Bad Morning

In the above program whenever we call wish() function automatically decor function will be executed.

How to call same function with decorator and without decorator: We should not use @decor 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23) 24) 25)

def decor(func): def inner(name): if name=="Sunny": print("Hello Sunny Bad Morning") else: func(name) return inner

def wish(name): print("Hello",name,"Good Morning") decorfunction=decor(wish) wish("Durga") #decorator wont be executed wish("Sunny") #decorator wont be executed decorfunction("Durga")#decorator will be executed decorfunction("Sunny")#decorator will be executed Output Hello Durga Good Morning Hello Sunny Good Morning Hello Durga Good Morning Hello Sunny Bad Morning

Eg 2: 1) def smart_division(func): 2) def inner(a,b): 3) print("We are dividing",a,"with",b) 4) if b==0: 5) print("OOPS. cannot divide") 6) return 7) else: 8) return func(a,b)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23) 24) 25) 26)

return inner @smart_division def division(a,b): return a/b print(division(20,2)) print(division(20,0)) without decorator we will get Error.In this case output is: 10.0 Traceback (most recent call last): File "test.py", line 16, in print(division(20,0)) File "test.py", line 13, in division return a/b ZeroDivisionError: division by zero

with decorator we won't get any error. In this case output is: We are dividing 20 with 2 10.0 We are dividing 20 with 0 OOPS. cannot divide None

Decorator Chaining We can define multiple decorators for the same function and all these decorators will form Decorator Chaining. Eg: @decor1 @decor def num(): For num() function we are applying 2 decorator functions. First inner decorator will work and then outer decorator. Eg: 1) def decor1(func): 2) def inner(): 3) x=func() 4) return x*x

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18)

return inner def decor(func): def inner(): x=func() return 2*x return inner @decor1 @decor def num(): return 10 print(num())

Demo Program for decorator Chaining: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18)

def decor(func): def inner(name): print("First Decor(decor) Function Execution") func(name) return inner def decor1(func): def inner(name): print("Second Decor(decor1) Execution") func(name) return inner @decor1 @decor def wish(name): print("Hello",name,"Good Morning") wish("Durga")

D:\durgaclasses>py decaratordemo1.py Second Decor(decor1) Execution First Decor(decor) Function Execution Hello Durga Good Morning

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Generators Generator is a function which is responsible to generate a sequence of values. We can write generator functions just like ordinary functions, but it uses yield keyword to return values. Generator Function

A Sequence of Values

yield Eg 1: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22)

def mygen(): yield 'A' yield 'B' yield 'C' g=mygen() print(type(g)) print(next(g)) print(next(g)) print(next(g)) print(next(g)) Output A B C Traceback (most recent call last): File "test.py", line 12, in print(next(g)) StopIteration

Eg 2: 1) def countdown(num): 2) print("Start Countdown") 3) while(num>0): 4) yield num 5) num=num-1 6) 7) values=countdown(5) 8) for x in values:

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

9) 10) 11) 12) 13) 14) 15) 16) 17)

print(x) Output Start Countdown 5 4 3 2 1

Eg 3: To generate first n numbers: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16)

def firstn(num): n=1 while n 100: 8) break 9) print(f)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23)

Output 0 1 1 2 3 5 8 13 21 34 55 89

Advantages of Generator Functions: 1. when compared with class level iterators, generators are very easy to use 2. Improves memory utilization and performance. 3. Generators are best suitable for reading data from large number of large files 4. Generators work great for web scraping and crawling.

Generators vs Normal Collections wrt performance: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23)

import random import time names = ['Sunny','Bunny','Chinny','Vinny'] subjects = ['Python','Java','Blockchain'] def people_list(num_people): results = [] for i in range(num_people): person = < 'id':i, 'name': random.choice(names), 'subject':random.choice(subjects) >results.append(person) return results def people_generator(num_people): for i in range(num_people): person = < 'id':i, 'name': random.choice(names), 'major':random.choice(subjects)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

24) 25) 26) 27) 28) 29) 30) 31) 32) 33) 34) 35)

> yield person '''''t1 = time.clock() people = people_list(10000000) t2 = time.clock()''' t1 = time.clock() people = people_generator(10000000) t2 = time.clock() print('Took <>'.format(t2-t1))

Note: In the above program observe the differnce wrt execution time by using list and generators

Generators vs Normal Collections wrt Memory Utilization: Normal Collection: l=[x*x for x in range(10000000000000000)] print(l[0]) We will get MemoryError in this case because all these values are required to store in the memory.

Generators: g=(x*x for x in range(10000000000000000)) print(next(g)) Output: 0 We won't get any MemoryError because the values won't be stored at the beginning

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Modules A group of functions, variables and classes saved to a file, which is nothing but module. Every Python file (.py) acts as a module. Eg: durgamath.py 1) x=888 2) 3) def add(a,b): 4) print("The Sum:",a+b) 5) 6) def product(a,b): 7) print("The Product:",a*b)

durgamath module contains one variable and 2 functions. If we want to use members of module in our program then we should import that module. import modulename We can access members by using module name. modulename.variable modulename.function() test.py: 1) 2) 3) 4) 5) 6) 7) 8) 9)

import durgamath print(durgamath.x) durgamath.add(10,20) durgamath.product(10,20) Output 888 The Sum: 30 The Product: 200

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Note: whenever we are using a module in our program, for that module compiled file will be generated and stored in the hard disk permanently.

Renaming a module at the time of import (module aliasing): Eg: import durgamath as m here durgamath is original module name and m is alias name. We can access members by using alias name m test.py: 1) 2) 3) 4)

import durgamath as m print(m.x) m.add(10,20) m.product(10,20)

from . import: We can import particular members of module by using from . import . The main advantage of this is we can access members directly without using module name. Eg: from durgamath import x,add print(x) add(10,20) product(10,20)==> NameError: name 'product' is not defined We can import all members of a module as follows from durgamath import * test.py: 1) 2) 3) 4)

from durgamath import * print(x) add(10,20) product(10,20)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Various possibilties of import: import modulename import module1,module2,module3 import module1 as m import module1 as m1,module2 as m2,module3 from module import member from module import member1,member2,memebr3 from module import memeber1 as x from module import *

member aliasing: from durgamath import x as y,add as sum print(y) sum(10,20) Once we defined as alias name,we should use alias name only and we should not use original name Eg: from durgamath import x as y print(x)==>NameError: name 'x' is not defined

Reloading a Module: By default module will be loaded only once eventhough we are importing multiple multiple times.

Demo Program for module reloading: 1) 2) 3) 4) 5) 6) 7) 8)

import time from imp import reload import module1 time.sleep(30) reload(module1) time.sleep(30) reload(module1) print("This is test file")

Note: In the above program, everytime updated version of module1 will be available to our program

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

module1.py: print("This is from module1") test.py 1) 2) 3) 4) 5) 6) 7) 8) 9)

import module1 import module1 import module1 import module1 print("This is test module") Output This is from module1 This is test module

In the above program test module will be loaded only once eventhough we are importing multiple times. The problem in this approach is after loading a module if it is updated outside then updated version of module1 is not available to our program. We can solve this problem by reloading module explicitly based on our requirement. We can reload by using reload() function of imp module. import imp imp.reload(module1) test.py: 1) 2) 3) 4) 5) 6) 7)

import module1 import module1 from imp import reload reload(module1) reload(module1) reload(module1) print("This is test module")

In the above program module1 will be loaded 4 times in that 1 time by default and 3 times explicitly. In this case output is 1) 2) 3) 4) 5)

This is from module1 This is from module1 This is from module1 This is from module1 This is test module

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

The main advantage of explicit module reloading is we can ensure that updated version is always available to our program.

Finding members of module by using dir() function: Python provides inbuilt function dir() to list out all members of current module or a specified module. dir() ===>To list out all members of current module dir(moduleName)==>To list out all members of specified module Eg 1: test.py 1) 2) 3) 4) 5) 6) 7) 8)

x=10 y=20 def f1(): print("Hello") print(dir()) # To print all members of current module Output ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__nam e__', '__package__', '__spec__', 'f1', 'x', 'y']

Eg 2: To display members of particular module: durgamath.py: 1) x=888 2) 3) def add(a,b): 4) print("The Sum:",a+b) 5) 6) def product(a,b): 7) print("The Product:",a*b)

test.py: 1) 2) 3) 4) 5) 6)

import durgamath print(dir(durgamath)) Output ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'add', 'product', 'x']

Note: For every module at the time of execution Python interpreter will add some special properties automatically for internal use.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: __builtins__,__cached__,'__doc__,__file__, __loader__, __name__,__package__, __spec__ Based on our requirement we can access these properties also in our program. Eg: test.py: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13)

print(__builtins__ ) print(__cached__ ) print(__doc__) print(__file__) print(__loader__) print(__name__) print(__package__) print(__spec__) Output None None

test.py 1) 2) __main__ 3) None 4) None

The Special variable __name__: For every Python program , a special variable __name__ will be added internally. This variable stores information regarding whether the program is executed as an individual program or as a module. If the program executed as an individual program then the value of this variable is __main__ If the program executed as a module from some other program then the value of this variable is the name of module where it is defined. Hence by using this __name__ variable we can identify whether the program executed directly or as a module.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Demo program: module1.py: 1) def f1(): 2) if __name__=='__main__': 3) print("The code executed as a program") 4) else: 5) print("The code executed as a module from some other program") 6) f1()

test.py: 1) 2) 3) 4) 5) 6) 7) 8) 9)

import module1 module1.f1() D:\Python_classes>py module1.py The code executed as a program D:\Python_classes>py test.py The code executed as a module from some other program The code executed as a module from some other program

Working with math module: Python provides inbuilt module math. This module defines several functions which can be used for mathematical operations. The main important functions are 1. sqrt(x) 2. ceil(x) 3. floor(x) 4. fabs(x) 5.log(x) 6. sin(x) 7. tan(x) . Eg: 1) 2) 3) 4) 5) 6)

from math import * print(sqrt(4)) print(ceil(10.1)) print(floor(10.1)) print(fabs(-10.6)) print(fabs(10.6))

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

7) 8) 9) 10) 11) 12) 13)

Output 2.0 11 10 10.6 10.6

Note: We can find help for any module by using help() function Eg: import math help(math)

Working with random module: This module defines several functions to generate random numbers. We can use these functions while developing games,in cryptography and to generate random numbers on fly for authentication.

1. random() function: This function always generate some float value between 0 and 1 ( not inclusive) 0in between x and y ( inclusive) uniform(x,y) ==> in between x and y ( not inclusive)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

4. randrange([start],stop,[step]) returns a random number from range start generates a number from 0 to 9 randrange(1,11)-->generates a number from 1 to 10 randrange(1,11,2)-->generates a number from 1,3,5,7,9 Eg 1: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15)

from random import * for i in range(10): print(randrange(10)) Output 9 4 0 2 9 4 8 9 5 9

Eg 2: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15)

from random import * for i in range(10): print(randrange(1,11)) Output 2 2 8 10 3 5 9 1 6 3

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg 3: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15)

from random import * for i in range(10): print(randrange(1,11,2)) Output 1 3 9 5 7 1 1 1 7 3

5. choice() function: It wont return random number. It will return a random object from the given list or tuple. Eg: 1) from random import * 2) list=["Sunny","Bunny","Chinny","Vinny","pinny"] 3) for i in range(10): 4) print(choice(list))

Output Bunny pinny Bunny Sunny Bunny pinny pinny Vinny Bunny Sunny

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Packages It is an encapsulation mechanism to group related modules into a single unit. package is nothing but folder or directory which represents collection of Python modules. Any folder or directory contains __init__.py file,is considered as a Python package.This file can be empty. A package can contains sub packages also.

__init__.py File 1

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

__init__.py File 1 File 1

__init__.py Module 1

Loan The main advantages of package statement are 1. We can resolve naming conflicts 2. We can identify our components uniquely 3. It improves modularity of the application Eg 1: D:\Python_classes> |-test.py |-pack1 |-module1.py |-__init__.py __init__.py: empty file module1.py: def f1(): print("Hello this is from module1 present in pack1") test.py (version-1): import pack1.module1 pack1.module1.f1()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

test.py (version-2): from pack1.module1 import f1 f1() Eg 2: D:\Python_classes> |-test.py |-com |-module1.py |-__init__.py |-durgasoft |-module2.py |-__init__.py

__init__.py: empty file module1.py: def f1(): print("Hello this is from module1 present in com") module2.py: def f2(): print("Hello this is from module2 present in com.durgasoft") test.py: 1. 2. 3. 4. 5. 6. 7. 8. 9.

from com.module1 import f1 from com.durgasoft.module2 import f2 f1() f2() Output D:\Python_classes>py test.py Hello this is from module1 present in com Hello this is from module2 present in com.durgasoft

Note: Summary diagram of library,packages,modules which contains functions,classes and variables.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

module 1 module 2 module n

module 1 module 2 module n

function 1 function 2 function n variables classes

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

File Handling As the part of programming requirement, we have to store our data permanently for future purpose. For this requirement we should go for files. Files are very common permanent storage areas to store our data.

Types of Files: There are 2 types of files

1. Text Files: Usually we can use text files to store character data eg: abc.txt

2. Binary Files: Usually we can use binary files to store binary data like images,video files, audio files etc.

Opening a File: Before performing any operation (like read or write) on the file,first we have to open that file.For this we should use Python's inbuilt function open() But at the time of open, we have to specify mode,which represents the purpose of opening file.

f = open(filename, mode) The allowed modes in Python are 1. r  open an existing file for read operation. The file pointer is positioned at the beginning of the file.If the specified file does not exist then we will get FileNotFoundError.This is default mode.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

2. w  open an existing file for write operation. If the file already contains some data then it will be overridden. If the specified file is not already avaialble then this mode will create that file. 3. a  open an existing file for append operation. It won't override existing data.If the specified file is not already avaialble then this mode will create a new file. 4. r+  To read and write data into the file. The previous data in the file will not be deleted.The file pointer is placed at the beginning of the file. 5. w+  To write and read data. It will override existing data. 6. a+  To append and read data from the file.It wont override existing data. 7. x  To open a file in exclusive creation mode for write operation. If the file already exists then we will get FileExistsError. Note: All the above modes are applicable for text files. If the above modes suffixed with 'b' then these represents for binary files. Eg: rb,wb,ab,r+b,w+b,a+b,xb

f = open("abc.txt","w") We are opening abc.txt file for writing data.

Closing a File: After completing our operations on the file,it is highly recommended to close the file. For this we have to use close() function.

Various properties of File Object: Once we opend a file and we got file object,we can get various details related to that file by using its properties. name  Name of opened file mode  Mode in which the file is opened closed  Returns boolean value indicates that file is closed or not readable() Retruns boolean value indicates that whether file is readable or not writable() Returns boolean value indicates that whether file is writable or not.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18)

f=open("abc.txt",'w') print("File Name: ",f.name) print("File Mode: ",f.mode) print("Is File Readable: ",f.readable()) print("Is File Writable: ",f.writable()) print("Is File Closed : ",f.closed) f.close() print("Is File Closed : ",f.closed)

Output D:\Python_classes>py test.py File Name: abc.txt File Mode: w Is File Readable: False Is File Writable: True Is File Closed : False Is File Closed : True

Writing data to text files: We can write character data to the text files by using the following 2 methods. write(str) writelines(list of lines) Eg: 1) 2) 3) 4) 5) 6)

f=open("abcd.txt",'w') f.write("Durga\n") f.write("Software\n") f.write("Solutions\n") print("Data written to the file successfully") f.close()

abcd.txt: Durga Software Solutions

Note: In the above program, data present in the file will be overridden everytime if we run the program. Instead of overriding if we want append operation then we should open the file as follows. f = open("abcd.txt","a")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

f=open("abcd.txt",'w') list=["sunny\n","bunny\n","vinny\n","chinny"] f.writelines(list) print("List of lines written to the file successfully") f.close()

abcd.txt: sunny bunny vinny chinny

Note: while writing data by using write() methods, compulsory we have to provide line seperator(\n),otherwise total data should be written to a single line.

Reading Character Data from text files: We can read character data from text file by using the following read methods. read() To read total data from the file read(n)  To read 'n' characters from the file readline() To read only one line readlines() To read all lines into a list Eg 1: To read total data from the file 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

f=open("abc.txt",'r') data=f.read() print(data) f.close() Output sunny bunny chinny vinny

Eg 2: To read only first 10 characters: 1) 2) 3) 4) 5)

f=open("abc.txt",'r') data=f.read(10) print(data) f.close()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

6) Output 7) sunny 8) bunn

Eg 3: To read data line by line: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13)

f=open("abc.txt",'r') line1=f.readline() print(line1,end='') line2=f.readline() print(line2,end='') line3=f.readline() print(line3,end='') f.close() Output sunny bunny chinny

Eg 4: To read all lines into list: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11)

f=open("abc.txt",'r') lines=f.readlines() for line in lines: print(line,end='') f.close() Output sunny bunny chinny vinny

Eg 5: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13)

f=open("abc.txt","r") print(f.read(3)) print(f.readline()) print(f.read(4)) print("Remaining data") print(f.read()) Output sun ny bunn Remaining data

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

14) y 15) chinny 16) vinny

The with statement: The with statement can be used while opening a file.We can use this to group file operation statements within a block. The advantage of with statement is it will take care closing of file,after completing all operations automatically even in the case of exceptions also, and we are not required to close explicitly. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

with open("abc.txt","w") as f: f.write("Durga\n") f.write("Software\n") f.write("Solutions\n") print("Is File Closed: ",f.closed) print("Is File Closed: ",f.closed) Output Is File Closed: False Is File Closed: True

The seek() and tell() methods: tell(): ==>We can use tell() method to return current position of the cursor(file pointer) from beginning of the file. [ can you plese telll current cursor position] The position(index) of first character in files is zero just like string index. Eg: 1) 2) 3) 4) 5) 6)

f=open("abc.txt","r") print(f.tell()) print(f.read(2)) print(f.tell()) print(f.read(3)) print(f.tell())

abc.txt: sunny bunny chinny vinny

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Output: 0 su 2 nny 5

seek(): We can use seek() method to move cursor(file pointer) to specified location. [Can you please seek the cursor to a particular location] f.seek(offset, fromwhere) offset represents the number of positions The allowed values for second attribute(from where) are 0---->From beginning of file(default value) 1---->From current position 2--->From end of the file

Note: Python 2 supports all 3 values but Python 3 supports only zero. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21)

data="All Students are STUPIDS" f=open("abc.txt","w") f.write(data) with open("abc.txt","r+") as f: text=f.read() print(text) print("The Current Cursor Position: ",f.tell()) f.seek(17) print("The Current Cursor Position: ",f.tell()) f.write("GEMS. ") f.seek(0) text=f.read() print("Data After Modification:") print(text) Output All Students are STUPIDS The Current Cursor Position: 24 The Current Cursor Position: 17 Data After Modification:

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

22) All Students are GEMS.

How to check a particular file exists or not? We can use os library to get information about files in our computer. os module has path sub module,which contains isFile() function to check whether a particular file exists or not? os.path.isfile(fname)

Q. Write a program to check whether the given file exists or not. If it is available then print its content? 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23) 24) 25) 26) 27)

import os,sys fname=input("Enter File Name: ") if os.path.isfile(fname): print("File exists:",fname) f=open(fname,"r") else: print("File does not exist:",fname) sys.exit(0) print("The content of file is:") data=f.read() print(data) Output D:\Python_classes>py test.py Enter File Name: durga.txt File does not exist: durga.txt D:\Python_classes>py test.py Enter File Name: abc.txt File exists: abc.txt The content of file is: All Students are GEMS. All Students are GEMS. All Students are GEMS. All Students are GEMS. All Students are GEMS. All Students are GEMS.

Note: sys.exit(0) ===>To exit system without executing rest of the program. argument represents status code . 0 means normal termination and it is the default value.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Q. Program to print the number of lines,words and characters present in the given file? 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23) 24) 25) 26) 27) 28) 29)

import os,sys fname=input("Enter File Name: ") if os.path.isfile(fname): print("File exists:",fname) f=open(fname,"r") else: print("File does not exist:",fname) sys.exit(0) lcount=wcount=ccount=0 for line in f: lcount=lcount+1 ccount=ccount+len(line) words=line.split() wcount=wcount+len(words) print("The number of Lines:",lcount) print("The number of Words:",wcount) print("The number of Characters:",ccount) Output D:\Python_classes>py test.py Enter File Name: durga.txt File does not exist: durga.txt D:\Python_classes>py test.py Enter File Name: abc.txt File exists: abc.txt The number of Lines: 6 The number of Words: 24 The number of Characters: 149

abc.txt: All Students are GEMS. All Students are GEMS. All Students are GEMS. All Students are GEMS. All Students are GEMS. All Students are GEMS.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Handling Binary Data: It is very common requirement to read or write binary data like images,video files,audio files etc.

Q. Program to read image file and write to a new image file? 1) 2) 3) 4) 5)

f1=open("rossum.jpg","rb") f2=open("newpic.jpg","wb") bytes=f1.read() f2.write(bytes) print("New Image is available with the name: newpic.jpg")

Handling csv files: CSV==>Comma seperated values As the part of programming,it is very common requirement to write and read data wrt csv files. Python provides csv module to handle csv files.

Writing data to csv file: 1) import csv 2) with open("emp.csv","w",newline='') as f: 3) w=csv.writer(f) # returns csv writer object 4) w.writerow(["ENO","ENAME","ESAL","EADDR"]) 5) n=int(input("Enter Number of Employees:")) 6) for i in range(n): 7) eno=input("Enter Employee No:") 8) ename=input("Enter Employee Name:") 9) esal=input("Enter Employee Salary:") 10) eaddr=input("Enter Employee Address:") 11) w.writerow([eno,ename,esal,eaddr]) 12) print("Total Employees data written to csv file successfully")

Note: Observe the difference with newline attribute and without with open("emp.csv","w",newline='') as f: with open("emp.csv","w") as f:

Note: If we are not using newline attribute then in the csv file blank lines will be included between data. To prevent these blank lines, newline attribute is required in Python-3,but in Python-2 just we can specify mode as 'wb' and we are not required to use newline attribute.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Reading Data from csv file: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16)

import csv f=open("emp.csv",'r') r=csv.reader(f) #returns csv reader object data=list(r) #print(data) for line in data: for word in line: print(word,"\t",end='') print() Output D:\Python_classes>py test.py ENO ENAME ESAL EADDR 100 Durga 1000 Hyd 200 Sachin 2000 Mumbai 300 Dhoni 3000 Ranchi

Zipping and Unzipping Files: It is very common requirement to zip and unzip files. The main advantages are: 1. To improve memory utilization 2. We can reduce transport time 3. We can improve performance. To perform zip and unzip operations, Python contains one in-bulit module zip file. This module contains a class : ZipFile

To create Zip file: We have to create ZipFile class object with name of the zip file,mode and constant ZIP_DEFLATED. This constant represents we are creating zip file.

f = ZipFile("files.zip","w","ZIP_DEFLATED") Once we create ZipFile object,we can add files by using write() method.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: 1) 2) 3) 4) 5) 6) 7)

from zipfile import * f=ZipFile("files.zip",'w',ZIP_DEFLATED) f.write("file1.txt") f.write("file2.txt") f.write("file3.txt") f.close() print("files.zip file created successfully")

To perform unzip operation: We have to create ZipFile object as follows

f = ZipFile("files.zip","r",ZIP_STORED) ZIP_STORED represents unzip operation. This is default value and hence we are not required to specify. Once we created ZipFile object for unzip operation,we can get all file names present in that zip file by using namelist() method.

names = f.namelist() Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9)

from zipfile import * f=ZipFile("files.zip",'r',ZIP_STORED) names=f.namelist() for name in names: print( "File Name: ",name) print("The Content of this file is:") f1=open(name,'r') print(f1.read()) print()

Working with Directories: It is very common requirement to perform operations for directories like 1. To know current working directory 2. To create a new directory 3. To remove an existing directory 4. To rename a directory 5. To list contents of the directory etc.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

To perform these operations,Python provides inbuilt module os,which contains several functions to perform directory related operations.

Q1. To Know Current Working Directory: import os cwd=os.getcwd() print("Current Working Directory:",cwd)

Q2. To create a sub directory in the current working directory: import os os.mkdir("mysub") print("mysub directory created in cwd")

Q3. To create a sub directory in mysub directory: cwd |-mysub |-mysub2 import os os.mkdir("mysub/mysub2") print("mysub2 created inside mysub")

Note: Assume mysub already present in cwd. Q4. To create multiple directories like sub1 in that sub2 in that sub3: import os os.makedirs("sub1/sub2/sub3") print("sub1 and in that sub2 and in that sub3 directories created")

Q5. To remove a directory: import os os.rmdir("mysub/mysub2") print("mysub2 directory deleted")

Q6. To remove multiple directories in the path: import os os.removedirs("sub1/sub2/sub3") print("All 3 directories sub1,sub2 and sub3 removed")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Q7. To rename a directory: import os os.rename("mysub","newdir") print("mysub directory renamed to newdir")

Q8. To know contents of directory: os module provides listdir() to list out the contents of the specified directory. It won't display the contents of sub directory. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9)

import os print(os.listdir(".")) Output D:\Python_classes>py test.py ['abc.py', 'abc.txt', 'abcd.txt', 'com', 'demo.py', 'durgamath.py', 'emp.csv', ' file1.txt', 'file2.txt', 'file3.txt', 'files.zip', 'log.txt', 'module1.py', 'myl og.txt', 'newdir', 'newpic.jpg', 'pack1', 'rossum.jpg', 'test.py', '__pycache__' ]

The above program display contents of current working directory but not contents of sub directories. If we want the contents of a directory including sub directories then we should go for walk() function.

Q9. To know contents of directory including sub directories: We have to use walk() function [Can you please walk in the directory so that we can aware all contents of that directory] os.walk(path,topdown=True,onerror=None,followlinks=False) It returns an Iterator object whose contents can be displayed by using for loop path-->Directory path. cwd means . topdown=True --->Travel from top to bottom onerror=None --->on error detected which function has to execute. followlinks=True -->To visit directories pointed by symbolic links

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: To display all contents of Current working directory including sub directories: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20)

import os for dirpath,dirnames,filenames in os.walk('.'): print("Current Directory Path:",dirpath) print("Directories:",dirnames) print("Files:",filenames) print()

Output Current Directory Path: . Directories: ['com', 'newdir', 'pack1', '__pycache__'] Files: ['abc.txt', 'abcd.txt', 'demo.py', 'durgamath.py', 'emp.csv', 'file1.txt' , 'file2.txt', 'file3.txt', 'files.zip', 'log.txt', 'module1.py', 'mylog.txt', ' newpic.jpg', 'rossum.jpg', 'test.py'] Current Directory Path: .\com Directories: ['durgasoft', '__pycache__'] Files: ['module1.py', '__init__.py'] .

Note: To display contents of particular directory,we have to provide that directory name as argument to walk() function. os.walk("directoryname")

Q. What is the difference between listdir() and walk() functions? In the case of listdir(), we will get contents of specified directory but not sub directory contents. But in the case of walk() function we will get contents of specified directory and its sub directories also.

Running Other programs from Python program: os module contains system() function to run programs and commands. It is exactly same as system() function in C language. os.system("commad string") The argument is any command which is executing from DOS. Eg: import os os.system("dir *.py") os.system("py abc.py")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

How to get information about a File: We can get statistics of a file like size, last accessed time,last modified time etc by using stat() function of os module. stats = os.stat("abc.txt") The statistics of a file includes the following parameters: st_mode==>Protection Bits st_ino==>Inode number st_dev===>device st_nlink===>no of hard links st_uid===>userid of owner st_gid==>group id of owner st_size===>size of file in bytes st_atime==>Time of most recent access st_mtime==>Time of Most recent modification st_ctime==> Time of Most recent meta data change

Note: st_atime, st_mtime and st_ctime returns the time as number of milli seconds since Jan 1st 1970 ,12:00AM. By using datetime module fromtimestamp() function,we can get exact date and time.

Q. To print all statistics of file abc.txt: 1) 2) 3) 4) 5) 6) 7) 8)

import os stats=os.stat("abc.txt") print(stats) Output os.stat_result(st_mode=33206, st_ino=844424930132788, st_dev=2657980798, st_nlin k=1, st_uid=0, st_gid=0, st_size=22410, st_atime=1505451446, st_mtime=1505538999 , st_ctime=1505451446)

Q. To print specified properties: 1) 2) 3) 4) 5) 6) 7)

import os from datetime import * stats=os.stat("abc.txt") print("File Size in Bytes:",stats.st_size) print("File Last Accessed Time:",datetime.fromtimestamp(stats.st_atime)) print("File Last Modified Time:",datetime.fromtimestamp(stats.st_mtime))

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Output File Size in Bytes: 22410 File Last Accessed Time: 2017-09-15 10:27:26.599490 File Last Modified Time: 2017-09-16 10:46:39.245394

Pickling and Unpickling of Objects: Sometimes we have to write total state of object to the file and we have to read total object from the file. The process of writing state of object to the file is called pickling and the process of reading state of an object from the file is called unpickling. We can implement pickling and unpickling by using pickle module of Python. pickle module contains dump() function to perform pickling. pickle.dump(object,file) pickle module contains load() function to perform unpickling obj=pickle.load(file) pickling

eno: 100 ename: Durga esal: 10000 eaddr: HYD

eno: 100 ename: Durga esal: 10000 eaddr: HYD

pickle.dump (e1, f)

eno: 100 ename: Durga esal: 10000 eaddr: HYD

abc.txt pickle load (f) unpickling

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Writing and Reading State of object by using pickle Module: 1) import pickle 2) class Employee: 3) def __init__(self,eno,ename,esal,eaddr): 4) self.eno=eno; 5) self.ename=ename; 6) self.esal=esal; 7) self.eaddr=eaddr; 8) def display(self): 9) print(self.eno,"\t",self.ename,"\t",self.esal,"\t",self.eaddr) 10) with open("emp.dat","wb") as f: 11) e=Employee(100,"Durga",1000,"Hyd") 12) pickle.dump(e,f) 13) print("Pickling of Employee Object completed. ") 14)

15) with open("emp.dat","rb") as f: 16) obj=pickle.load(f) 17) print("Printing Employee Information after unpickling") 18) obj.display()

Writing Multiple Employee Objects to the file: emp.py: 1) class Employee: 2) def __init__(self,eno,ename,esal,eaddr): 3) self.eno=eno; 4) self.ename=ename; 5) self.esal=esal; 6) self.eaddr=eaddr; 7) def display(self): 8) 9) print(self.eno,"\t",self.ename,"\t",self.esal,"\t",self.eaddr)

pick.py: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11)

import emp,pickle f=open("emp.dat","wb") n=int(input("Enter The number of Employees:")) for i in range(n): eno=int(input("Enter Employee Number:")) ename=input("Enter Employee Name:") esal=float(input("Enter Employee Salary:")) eaddr=input("Enter Employee Address:") e=emp.Employee(eno,ename,esal,eaddr) pickle.dump(e,f) print("Employee Objects pickled successfully")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

unpick.py: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11)

import emp,pickle f=open("emp.dat","rb") print("Employee Details:") while True: try: obj=pickle.load(f) obj.display() except EOFError: print("All employees Completed") break f.close()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Exception Handling In any programming language there are 2 types of errors are possible. 1. Syntax Errors 2. Runtime Errors

1. Syntax Errors: The errors which occurs because of invalid syntax are called syntax errors. Eg 1: x=10 if x==10 print("Hello") SyntaxError: invalid syntax Eg 2: print "Hello" SyntaxError: Missing parentheses in call to 'print'

Note: Programmer is responsible to correct these syntax errors. Once all syntax errors are corrected then only program execution will be started.

2. Runtime Errors: Also known as exceptions. While executing the program if something goes wrong because of end user input or programming logic or memory problems etc then we will get Runtime Errors. Eg: print(10/0) ==>ZeroDivisionError: division by zero print(10/"ten") ==>TypeError: unsupported operand type(s) for /: 'int' and 'str' x=int(input("Enter Number:")) print(x) D:\Python_classes>py test.py

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Enter Number:ten ValueError: invalid literal for int() with base 10: 'ten'

Note: Exception Handling concept applicable for Runtime Errors but not for syntax errors

What is Exception: An unwanted and unexpected event that disturbs normal flow of program is called exception. Eg: ZeroDivisionError TypeError ValueError FileNotFoundError EOFError SleepingError TyrePuncturedError It is highly recommended to handle exceptions. The main objective of exception handling is Graceful Termination of the program(i.e we should not block our resources and we should not miss anything) Exception handling does not mean repairing exception. We have to define alternative way to continue rest of the program normally. Eg: For example our programming requirement is reading data from remote file locating at London. At runtime if london file is not available then the program should not be terminated abnormally. We have to provide local file to continue rest of the program normally. This way of defining alternative is nothing but exception handling.

try: read data from remote file locating at london except FileNotFoundError: use local file and continue rest of the program normally Q. What is an Exception? Q. What is the purpose of Exception Handling? Q. What is the meaning of Exception Handling?

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Default Exception Handing in Python: Every exception in Python is an object. For every exception type the corresponding classes are available. Whevever an exception occurs PVM will create the corresponding exception object and will check for handling code. If handling code is not available then Python interpreter terminates the program abnormally and prints corresponding exception information to the console. The rest of the program won't be executed. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

print("Hello") print(10/0) print("Hi") D:\Python_classes>py test.py Hello Traceback (most recent call last): File "test.py", line 2, in print(10/0) ZeroDivisionError: division by zero

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Python's Exception Hierarchy BaseException

Permission Error TimeOut Error

Every Exception in Python is a class. All exception classes are child classes of BaseException.i.e every exception class extends BaseException either directly or indirectly. Hence BaseException acts as root for Python Exception Hierarchy. Most of the times being a programmer we have to concentrate Exception and its child classes.

Customized Exception Handling by using try-except: It is highly recommended to handle exceptions. The code which may raise exception is called risky code and we have to take risky code inside try block. The corresponding handling code we have to take inside except block.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

try: Risky Code except XXX: Handling code/Alternative Code

without try-except: 1. 2. 3. 4. 5. 6. 7.

print("stmt-1") print(10/0) print("stmt-3") Output stmt-1 ZeroDivisionError: division by zero

Abnormal termination/Non-Graceful Termination

with try-except: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

print("stmt-1") try: print(10/0) except ZeroDivisionError: print(10/2) print("stmt-3") Output stmt-1 5.0 stmt-3

Normal termination/Graceful Termination

Control Flow in try-except: try: stmt-1 stmt-2 stmt-3 except XXX: stmt-4 stmt-5 case-1: If there is no exception 1,2,3,5 and Normal Termination

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

case-2: If an exception raised at stmt-2 and corresponding except block matched 1,4,5 Normal Termination case-3: If an exception raised at stmt-2 and corresponding except block not matched 1, Abnormal Termination case-4: If an exception raised at stmt-4 or at stmt-5 then it is always abnormal termination.

Conclusions: 1. within the try block if anywhere exception raised then rest of the try block wont be executed eventhough we handled that exception. Hence we have to take only risky code inside try block and length of the try block should be as less as possible. 2. In addition to try block,there may be a chance of raising exceptions inside except and finally blocks also. 3. If any statement which is not part of try block raises an exception then it is always abnormal termination.

How to print exception information: try: 1. print(10/0) 2. except ZeroDivisionError as msg: 3. print("exception raised and its description is:",msg) 4. 5. Output exception raised and its description is: division by zero

try with multiple except blocks: The way of handling exception is varied from exception to exception.Hence for every exception type a seperate except block we have to provide. i.e try with multiple except blocks is possible and recommended to use. Eg: try: ------------------except ZeroDivisionError: perform alternative arithmetic operations

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

except FileNotFoundError: use local file instead of remote file If try with multiple except blocks available then based on raised exception the corresponding except block will be executed. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23)

try: x=int(input("Enter First Number: ")) y=int(input("Enter Second Number: ")) print(x/y) except ZeroDivisionError : print("Can't Divide with Zero") except ValueError: print("please provide int value only") D:\Python_classes>py test.py Enter First Number: 10 Enter Second Number: 2 5.0 D:\Python_classes>py test.py Enter First Number: 10 Enter Second Number: 0 Can't Divide with Zero D:\Python_classes>py test.py Enter First Number: 10 Enter Second Number: ten please provide int value only

If try with multiple except blocks available then the order of these except blocks is important .Python interpreter will always consider from top to bottom until matched except block identified. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

try: x=int(input("Enter First Number: ")) y=int(input("Enter Second Number: ")) print(x/y) except ArithmeticError : print("ArithmeticError") except ZeroDivisionError: print("ZeroDivisionError") D:\Python_classes>py test.py

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

11) Enter First Number: 10 12) Enter Second Number: 0 13) ArithmeticError

Single except block that can handle multiple exceptions: We can write a single except block that can handle multiple different types of exceptions. except (Exception1,Exception2,exception3. ): or except (Exception1,Exception2,exception3. ) as msg : Parenthesis are mandatory and this group of exceptions internally considered as tuple. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17)

try: x=int(input("Enter First Number: ")) y=int(input("Enter Second Number: ")) print(x/y) except (ZeroDivisionError,ValueError) as msg: print("Plz Provide valid numbers only and problem is: ",msg) D:\Python_classes>py test.py Enter First Number: 10 Enter Second Number: 0 Plz Provide valid numbers only and problem is: division by zero D:\Python_classes>py test.py Enter First Number: 10 Enter Second Number: ten Plz Provide valid numbers only and problem is: invalid literal for int() with b ase 10: 'ten'

Default except block: We can use default except block to handle any type of exceptions. In default except block generally we can print normal error messages. Syntax: except: statements Eg: 1) try: 2) x=int(input("Enter First Number: ")) 3) y=int(input("Enter Second Number: ")) 4) print(x/y)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18)

except ZeroDivisionError: print("ZeroDivisionError:Can't divide with zero") except: print("Default Except:Plz provide valid input only") D:\Python_classes>py test.py Enter First Number: 10 Enter Second Number: 0 ZeroDivisionError:Can't divide with zero D:\Python_classes>py test.py Enter First Number: 10 Enter Second Number: ten Default Except:Plz provide valid input only

***Note: If try with multiple except blocks available then default except block should be last,otherwise we will get SyntaxError. Eg: 1) 2) 3) 4) 5) 6) 7) 8)

try: print(10/0) except: print("Default Except") except ZeroDivisionError: print("ZeroDivisionError") SyntaxError: default 'except:' must be last

Note: The following are various possible combinations of except blocks 1. except ZeroDivisionError: 1. except ZeroDivisionError as msg: 3. except (ZeroDivisionError,ValueError) : 4. except (ZeroDivisionError,ValueError) as msg: 5. except :

finally block: 1. It is not recommended to maintain clean up code(Resource Deallocating Code or Resource Releasing code) inside try block because there is no guarentee for the execution of every statement inside try block always. 2. It is not recommended to maintain clean up code inside except block, because if there is no exception then except block won't be executed.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Hence we required some place to maintain clean up code which should be executed always irrespective of whether exception raised or not raised and whether exception handled or not handled. Such type of best place is nothing but finally block. Hence the main purpose of finally block is to maintain clean up code. try: Risky Code except: Handling Code finally: Cleanup code The speciality of finally block is it will be executed always whether exception raised or not raised and whether exception handled or not handled.

Case-1: If there is no exception 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

try: print("try") except: print("except") finally: print("finally") Output try finally

Case-2: If there is an exception raised but handled: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12)

try: print("try") print(10/0) except ZeroDivisionError: print("except") finally: print("finally") Output try except finally

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Case-3: If there is an exception raised but not handled: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12)

try: print("try") print(10/0) except NameError: print("except") finally: print("finally") Output try finally ZeroDivisionError: division by zero(Abnormal Termination)

*** Note: There is only one situation where finally block won't be executed ie whenever we are using os._exit(0) function. Whenever we are using os._exit(0) function then Python Virtual Machine itself will be shutdown.In this particular case finally won't be executed. 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11)

imports try: print("try") os._exit(0) except NameError: print("except") finally: print("finally") Output try

Note: os._exit(0) where 0 represents status code and it indicates normal termination There are multiple status codes are possible.

Control flow in try-except-finally: try: stmt-1 stmt-2 stmt-3 except: stmt-4

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

finally: stmt-5 stmt6

Case-1: If there is no exception 1,2,3,5,6 Normal Termination

Case-2: If an exception raised at stmt2 and the corresponding except block matched 1,4,5,6 Normal Termination

Case-3: If an exception raised at stmt2 but the corresponding except block not matched 1,5 Abnormal Termination

Case-4:If an exception raised at stmt4 then it is always abnormal termination but before that finally block will be executed.

Case-5: If an exception raised at stmt-5 or at stmt-6 then it is always abnormal termination

Nested try-except-finally blocks: We can take try-except-finally blocks inside try or except or finally blocks.i.e nesting of tryexcept-finally is possible. try: ---------------------------try: --------------------------------------except: --------------------------------------------------except: ------------------------------General Risky code we have to take inside outer try block and too much risky code we have to take inside inner try block. Inside Inner try block if an exception raised then inner

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

except block is responsible to handle. If it is unable to handle then outer except block is responsible to handle. Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20)

try: print("outer try block") try: print("Inner try block") print(10/0) except ZeroDivisionError: print("Inner except block") finally: print("Inner finally block") except: print("outer except block") finally: print("outer finally block") Output outer try block Inner try block Inner except block Inner finally block outer finally block

Control flow in nested try-except-finally: try: stmt-1 stmt-2 stmt-3 try: stmt-4 stmt-5 stmt-6 except X: stmt-7 finally: stmt-8 stmt-9 except Y: stmt-10 finally: stmt-11 stmt-12

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

case-1: If there is no exception 1,2,3,4,5,6,8,9,11,12 Normal Termination

case-2: If an exception raised at stmt-2 and the corresponding except block matched 1,10,11,12 Normal Termination

case-3: If an exceptiion raised at stmt-2 and the corresponding except block not matched 1,11,Abnormal Termination

case-4: If an exception raised at stmt-5 and inner except block matched 1,2,3,4,7,8,9,11,12 Normal Termination

case-5: If an exception raised at stmt-5 and inner except block not matched but outer except block matched 1,2,3,4,8,10,11,12,Normal Termination

case-6:If an exception raised at stmt-5 and both inner and outer except blocks are not matched 1,2,3,4,8,11,Abnormal Termination

case-7: If an exception raised at stmt-7 and corresponding except block matched 1,2,3. 8,10,11,12,Normal Termination

case-8: If an exception raised at stmt-7 and corresponding except block not matched 1,2,3. 8,11,Abnormal Termination

case-9: If an exception raised at stmt-8 and corresponding except block matched 1,2,3. 10,11,12 Normal Termination

case-10: If an exception raised at stmt-8 and corresponding except block not matched 1,2,3. 11,Abnormal Termination

case-11: If an exception raised at stmt-9 and corresponding except block matched 1,2,3. 8,10,11,12,Normal Termination

case-12: If an exception raised at stmt-9 and corresponding except block not matched 1,2,3. 8,11,Abnormal Termination

case-13: If an exception raised at stmt-10 then it is always abonormal termination but before abnormal termination finally block(stmt-11) will be executed.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

case-14: If an exception raised at stmt-11 or stmt-12 then it is always abnormal termination.

Note: If the control entered into try block then compulsary finally block will be executed. If the control not entered into try block then finally block won't be executed.

else block with try-except-finally: We can use else block with try-except-finally blocks. else block will be executed if and only if there are no exceptions inside try block. try: Risky Code except: will be executed if exception inside try else: will be executed if there is no exception inside try finally: will be executed whether exception raised or not raised and handled or not handled Eg: try: print("try") print(10/0)--->1 except: print("except") else: print("else") finally: print("finally") If we comment line-1 then else block will be executed b'z there is no exception inside try. In this case the output is: try else finally If we are not commenting line-1 then else block won't be executed b'z there is exception inside try block. In this case output is:

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

try except finally

Various possible combinations of try-except-else-finally: 1. Whenever we are writing try block, compulsory we should write except or finally block.i.e without except or finally block we cannot write try block. 2. Wheneever we are writing except block, compulsory we should write try block. i.e except without try is always invalid. 3. Whenever we are writing finally block, compulsory we should write try block. i.e finally without try is always invalid. 4. We can write multiple except blocks for the same try,but we cannot write multiple finally blocks for the same try 5. Whenever we are writing else block compulsory except block should be there. i.e without except we cannot write else block. 6. In try-except-else-finally order is important. 7. We can define try-except-else-finally inside try,except,else and finally blocks. i.e nesting of try-except-else-finally is always possible. 1 2 3 4

try: print("try") except: print("Hello") else: print("Hello") finally: print("Hello") try: print("try") except: print("except") try: print("try") finally: print("finally") try: print("try") nd

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

except: print("except") else: print("else") try: print("try") else: print("else") try: print("try") else: print("else") finally: print("finally") try: print("try") except XXX: print("except-1") except YYY: print("except-2") try: print("try") except : print("except-1") else: print("else") else: print("else") try: print("try") except : print("except-1") finally: print("finally") finally: print("finally") try: print("try") print("Hello") except: print("except") try: print("try") except: nd

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

print("except") print("Hello") except: print("except") try: print("try") except: print("except") print("Hello") finally: print("finally") try: print("try") except: print("except") print("Hello") else: print("else") try: print("try") except: print("except") try: print("try") except: print("except") try: print("try") except: print("except") try: print("try") finally: print("finally") try: print("try") except: print("except") if 10>20: print("if") else: print("else") try: print("try") nd

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

try: print("inner try") except: print("inner except block") finally: print("inner finally block") except: print("except") try: print("try")

except: print("except") try: print("inner try") except: print("inner except block") finally: print("inner finally block") try: print("try") except: print("except") finally: try: print("inner try") except: print("inner except block") finally: print("inner finally block") try: print("try") except: print("except") try: print("try") else: print("else") try: print("try") try: print("inner try") except: print("except") nd

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

try: print("try") else: 25

print("else") except: print("except") finally: print("finally")

Types of Exceptions: In Python there are 2 types of exceptions are possible. 1. Predefined Exceptions 2. User Definded Exceptions

1. Predefined Exceptions: Also known as in-built exceptions The exceptions which are raised automatically by Python virtual machine whenver a particular event occurs, are called pre defined exceptions. Eg 1: Whenever we are trying to perform Division by zero, automatically Python will raise ZeroDivisionError. print(10/0) Eg 2: Whenever we are trying to convert input value to int type and if input value is not int value then Python will raise ValueError automatically x=int("ten")===>ValueError

2. User Defined Exceptions: Also known as Customized Exceptions or Programatic Exceptions Some time we have to define and raise exceptions explicitly to indicate that something goes wrong ,such type of exceptions are called User Defined Exceptions or Customized Exceptions Programmer is responsible to define these exceptions and Python not having any idea about these. Hence we have to raise explicitly based on our requirement by using "raise" keyword.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: InSufficientFundsException InvalidInputException TooYoungException TooOldException

How to Define and Raise Customized Exceptions: Every exception in Python is a class that extends Exception class either directly or indirectly. Syntax: class classname(predefined exception class name): def __init__(self,arg): self.msg=arg Eg: 1) class TooYoungException(Exception): 2) def __init__(self,arg): 3) self.msg=arg

TooYoungException is our class name which is the child class of Exception We can raise exception by using raise keyword as follows raise TooYoungException("message") Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13)

class TooYoungException(Exception): def __init__(self,arg): self.msg=arg class TooOldException(Exception): def __init__(self,arg): self.msg=arg

age=int(input("Enter Age:")) if age>60: raise TooYoungException("Plz wait some more time you will get best match soon. ") elif age py test.py

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

18) 19) 20) 21) 22) 23) 24) 25) 26) 27) 28)

Enter Age:90 __main__.TooYoungException: Plz wait some more time you will get best match soon. D:\Python_classes>py test.py Enter Age:12 __main__.TooOldException: Your age already crossed marriage age. no chance of g etting marriage D:\Python_classes>py test.py Enter Age:27 You will get match details soon by email.

Note: raise keyword is best suitable for customized exceptions but not for pre defined exceptions

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

PYTHON LOGGING Logging the Exceptions: It is highly recommended to store complete application flow and exceptions information to a file. This process is called logging. The main advantages of logging are: 1. We can use log files while performing debugging 2. We can provide statistics like number of requests per day etc To implement logging, Python provides one inbuilt module logging.

logging levels: Depending on type of information, logging data is divided according to the following 6 levels in Python. table 1. CRITICAL==>50==>Represents a very serious problem that needs high attention 2. ERROR===>40===>Represents a serious error 3. WARNING==>30==>Represents a warning message, some caution needed. It is alert to the programmer 4. INFO===>20===>Represents a message with some important information 5. DEBUG===>10==>Represents a message with debugging information 6. NOTSET==>0==>Rrepresents that the level is not set. By default while executing Python program only WARNING and higher level messages will be displayed.

How to implement logging: To perform logging, first we required to create a file to store messages and we have to specify which level messages we have to store. We can do this by using basicConfig() function of logging module. logging.basicConfig(filename='log.txt',level=logging.WARNING)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

The above line will create a file log.txt and we can store either WARNING level or higher level messages to that file. After creating log file, we can write messages to that file by using the following methods. logging.debug(message) logging.info(message) logging.warning(message) logging.error(message) logging.critical(message)

Q.Write a Python program to create a log file and write WARNING and higher level messages? 1) 2) 3) 4) 5) 6) 7) 8)

import logging logging.basicConfig(filename='log.txt',level=logging.WARNING) print("Logging Module Demo") logging.debug("This is debug message") logging.info("This is info message") logging.warning("This is warning message") logging.error("This is error message") logging.critical("This is critical message")

log.txt: 1) WARNING:root:This is warning message 2) ERROR:root:This is error message 3) CRITICAL:root:This is critical message

Note: In the above program only WARNING and higher level messages will be written to log file. If we set level as DEBUG then all messages will be written to log file. 1) 2) 3) 4) 5) 6) 7) 8)

import logging logging.basicConfig(filename='log.txt',level=logging.DEBUG) print("Logging Module Demo") logging.debug("This is debug message") logging.info("This is info message") logging.warning("This is warning message") logging.error("This is error message") logging.critical("This is critical message")

log.txt: 1) DEBUG:root:This is debug message 2) INFO:root:This is info message

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

3) WARNING:root:This is warning message 4) ERROR:root:This is error message 5) CRITICAL:root:This is critical message

Note: We can format log messages to include date and time, ip address of the client etc at advanced level.

How to write Python program exceptions to the log file: By using the following function we can write exceptions information to the log file. logging.exception(msg)

Q. Python Program to write exception information to the log file 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23) 24) 25) 26) 27) 28) 29) 30)

import logging logging.basicConfig(filename='mylog.txt',level=logging.INFO) logging.info("A New request Came:") try: x=int(input("Enter First Number: ")) y=int(input("Enter Second Number: ")) print(x/y) except ZeroDivisionError as msg: print("cannot divide with zero") logging.exception(msg) except ValueError as msg: print("Enter only int values") logging.exception(msg) logging.info("Request Processing Completed")

D:\Python_classes>py test.py Enter First Number: 10 Enter Second Number: 2 5.0 D:\Python_classes>py test.py Enter First Number: 10 Enter Second Number: 0 cannot divide with zero D:\Python_classes>py test.py Enter First Number: 10 Enter Second Number: ten Enter only int values

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

mylog.txt: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16)

INFO:root:A New request Came: INFO:root:Request Processing Completed INFO:root:A New request Came: ERROR:root:division by zero Traceback (most recent call last): File "test.py", line 7, in print(x/y) ZeroDivisionError: division by zero INFO:root:Request Processing Completed INFO:root:A New request Came: ERROR:root:invalid literal for int() with base 10: 'ten' Traceback (most recent call last): File "test.py", line 6, in y=int(input("Enter Second Number: ")) ValueError: invalid literal for int() with base 10: 'ten' INFO:root:Request Processing Completed

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

PYTHON DEBUGGING BY USING ASSERTIONS Debugging Python Program by using assert keyword: The process of identifying and fixing the bug is called debugging. Very common way of debugging is to use print() statement. But the problem with the print() statement is after fixing the bug,compulsory we have to delete the extra added print() statments,otherwise these will be executed at runtime which creates performance problems and disturbs console output. To overcome this problem we should go for assert statement. The main advantage of assert statement over print() statement is after fixing bug we are not required to delete assert statements. Based on our requirement we can enable or disable assert statements. Hence the main purpose of assertions is to perform debugging. Usully we can perform debugging either in development or in test environments but not in production environment. Hence assertions concept is applicable only for dev and test environments but not for production environment.

Types of assert statements: There are 2 types of assert statements 1. Simple Version 2. Augmented Version

1. Simple Version: assert conditional_expression

2. Augmented Version: assert conditional_expression,message conditional_expression will be evaluated and if it is true then the program will be continued. If it is false then the program will be terminated by raising AssertionError. By seeing AssertionError, programmer can analyze the code and can fix the problem. Eg: 1) def squareIt(x): 2) return x**x

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23) 24) 25) 26) 27) 28)

assert squareIt(2)==4,"The square of 2 should be 4" assert squareIt(3)==9,"The square of 3 should be 9" assert squareIt(4)==16,"The square of 4 should be 16" print(squareIt(2)) print(squareIt(3)) print(squareIt(4)) D:\Python_classes>py test.py Traceback (most recent call last): File "test.py", line 4, in assert squareIt(3)==9,"The square of 3 should be 9" AssertionError: The square of 3 should be 9 def squareIt(x): return x*x assert squareIt(2)==4,"The square of 2 should be 4" assert squareIt(3)==9,"The square of 3 should be 9" assert squareIt(4)==16,"The square of 4 should be 16" print(squareIt(2)) print(squareIt(3)) print(squareIt(4)) Output 4 9 16

Exception Handling vs Assertions: Assertions concept can be used to alert programmer to resolve development time errors. Exception Handling can be used to handle runtime errors.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Python's Object Oriented Programming (OOPs) What is Class: ⚽ In Python every thing is an object. To create objects we required some Model or Plan or Blue print, which is nothing but class. ⚽ We can write a class to represent properties (attributes) and actions (behaviour) of object. ⚽ Properties can be represented by variables ⚽ Actions can be represented by Methods. ⚽ Hence class contains both variables and methods.

How to Define a class? We can define a class by using class keyword.

Syntax: class className: ''' documenttation string ''' variables:instance variables,static and local variables methods: instance methods,static methods,class methods Documentation string represents description of the class. Within the class doc string is always optional. We can get doc string by using the following 2 ways. 1. print(classname.__doc__) 2. help(classname)

Example: 1) class Student: 2) ''''' This is student class with required data''' 3) print(Student.__doc__) 4) help(Student) Within the Python class we can represent data by using variables. There are 3 types of variables are allowed. 1. Instance Variables (Object Level Variables) 2. Static Variables (Class Level Variables) 3. Local variables (Method Level Variables) Within the Python class, we can represent operations by using methods. The following are various types of allowed methods

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

1. Instance Methods 2. Class Methods 3. Static Methods

Example for class: 1) class Student: 2) '''''Developed by durga for python demo''' 3) def __init__(self): 4) self.name='durga' 5) self.age=40 6) self.marks=80 7) 8) def talk(self): 9) print("Hello I am :",self.name) 10) print("My Age is:",self.age) 11) print("My Marks are:",self.marks)

What is Object: Pysical existence of a class is nothing but object. We can create any number of objects for a class.

Syntax to create object: referencevariable = classname() Example: s = Student()

What is Reference Variable: The variable which can be used to refer object is called reference variable. By using reference variable, we can access properties and methods of object.

Program: Write a Python program to create a Student class and Creates an object to it. Call the method talk() to display student details 1) class Student: 2) 3) def __init__(self,name,rollno,marks): 4) self.name=name 5) self.rollno=rollno 6) self.marks=marks 7) 8) def talk(self): 9) print("Hello My Name is:",self.name) 10) print("My Rollno is:",self.rollno) 11) print("My Marks are:",self.marks) 12)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

13) s1=Student("Durga",101,80) 14) s1.talk()

Output: D:\durgaclasses>py test.py Hello My Name is: Durga My Rollno is: 101 My Marks are: 80

Self variable: self is the default variable which is always pointing to current object (like this keyword in Java) By using self we can access instance variables and instance methods of object.

Note: 1. self should be first parameter inside constructor def __init__(self): 2. self should be first parameter inside instance methods def talk(self):

Constructor is a special method in python. The name of the constructor should be __init__(self) Constructor will be executed automatically at the time of object creation. The main purpose of constructor is to declare and initialize instance variables. Per object constructor will be exeucted only once. Constructor can take atleast one argument(atleast self)

☕ Constructor is optional and if we are not providing any constructor then python will provide default constructor.

Example: 1) def __init__(self,name,rollno,marks): 2) self.name=name 3) self.rollno=rollno 4) self.marks=marks

Program to demonistrate constructor will execute only once per object: 1) class Test: 2) 3) def __init__(self): 4) print("Constructor exeuction. ") 5)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

6) 7) 8) 9) 10) 11) 12)

def m1(self): print("Method execution. ") t1=Test() t2=Test() t3=Test() t1.m1()

Output Constructor exeuction. Constructor exeuction. Constructor exeuction. Method execution.

Program: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

class Student: ''''' This is student class with required data''' def __init__(self,x,y,z): self.name=x self.rollno=y self.marks=z def display(self): print("Student Name:<>\nRollno:<> \nMarks:<>".format(self.name,self.rollno,self.marks) )

s1=Student("Durga",101,80) s1.display() s2=Student("Sunny",102,100) s2.display()

Output Student Name:Durga Rollno:101 Marks:80 Student Name:Sunny Rollno:102 Marks:100

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Differences between Methods and Constructors: Method

1. Name of method can be any name 2. Method will be executed if we call that method 3. Per object, method can be called any number of times. 4. Inside method we can write business logic

1. Constructor name should be always __init__ 2. Constructor will be executed automatically at the time of object creation. 3. Per object, Constructor will be executed only once 4. Inside Constructor we have to declare and initialize instance variables

Types of Variables: Inside Python class 3 types of variables are allowed. 1. Instance Variables (Object Level Variables) 2. Static Variables (Class Level Variables) 3. Local variables (Method Level Variables)

1. Instance Variables: If the value of a variable is varied from object to object, then such type of variables are called instance variables. For every object a separate copy of instance variables will be created.

Where we can declare Instance variables: 1. Inside Constructor by using self variable 2. Inside Instance Method by using self variable 3. Outside of the class by using object reference variable

1. Inside Constructor by using self variable: We can declare instance variables inside a constructor by using self keyword. Once we creates object, automatically these variables will be added to the object.

Example: 1) class Employee: 2) 3) def __init__(self): 4) self.eno=100 5) self.ename='Durga' 6) self.esal=10000 7) 8) e=Employee()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

2. Inside Instance Method by using self variable: We can also declare instance variables inside instance method by using self variable. If any instance variable declared inside instance method, that instance variable will be added once we call taht method.

Example: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12)

class Test: def __init__(self): self.a=10 self.b=20 def m1(self): self.c=30 t=Test() t.m1() print(t.__dict__)

3. Outside of the class by using object reference variable: We can also add instance variables outside of a class to a particular object. 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13)

class Test: def __init__(self): self.a=10 self.b=20 def m1(self): self.c=30 t=Test() t.m1() t.d=40 print(t.__dict__)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

How to access Instance variables: We can access instance variables with in the class by using self variable and outside of the class by using object reference. 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13)

class Test: def __init__(self): self.a=10 self.b=20 def display(self): print(self.a) print(self.b) t=Test() t.display() print(t.a,t.b)

Output 10 20 10 20

How to delete instance variable from the object: 1. Within a class we can delete instance variable as follows del self.variableName 2. From outside of class we can delete instance variables as follows del objectreference.variableName

Example: 1) class Test: 2) def __init__(self): 3) self.a=10 4) self.b=20 5) self.c=30 6) self.d=40 7) def m1(self): 8) del self.d 9) 10) t=Test() 11) print(t.__dict__)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

t.m1() print(t.__dict__) del t.c print(t.__dict__)

Note: The instance variables which are deleted from one object,will not be deleted from other objects.

Example: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13)

class Test: def __init__(self): self.a=10 self.b=20 self.c=30 self.d=40

t1=Test() t2=Test() del t1.a print(t1.__dict__) print(t2.__dict__)

Output If we change the values of instance variables of one object then those changes won't be reflected to the remaining objects, because for every object we are separate copy of instance variables are available.

Example: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

class Test: def __init__(self): self.a=10 self.b=20 t1=Test() t1.a=888 t1.b=999 t2=Test() print('t1:',t1.a,t1.b)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Output t1: 888 999 t2: 10 20

1. Static variables: If the value of a variable is not varied from object to object, such type of variables we have to declare with in the class directly but outside of methods. Such type of variables are called Static variables. For total class only one copy of static variable will be created and shared by all objects of that class. We can access static variables either by class name or by object reference. But recommended to use class name.

Instance Variable vs Static Variable: Note: In the case of instance variables for every object a seperate copy will be created,but in the case of static variables for total class only one copy will be created and shared by every object of that class. 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13)

class Test: x=10 def __init__(self): self.y=20 t1=Test() t2=Test() print('t1:',t1.x,t1.y) print('t2:',t2.x,t2.y) Test.x=888 t1.y=999 print('t1:',t1.x,t1.y) print('t2:',t2.x,t2.y)

Output t1: 10 20 t2: 10 20 t1: 888 999 t2: 888 20

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Various places to declare static variables: 1. In general we can declare within the class directly but from out side of any method 2. Inside constructor by using class name 3. Inside instance method by using class name 4. Inside classmethod by using either class name or cls variable 5. Inside static method by using class name 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23) 24)

class Test: a=10 def __init__(self): Test.b=20 def m1(self): Test.c=30 @classmethod def m2(cls): cls.d1=40 Test.d2=400 @staticmethod def m3(): Test.e=50 print(Test.__dict__) t=Test() print(Test.__dict__) t.m1() print(Test.__dict__) Test.m2() print(Test.__dict__) Test.m3() print(Test.__dict__) Test.f=60 print(Test.__dict__)

How to access static variables: 1. inside constructor: by using either self or classname 2. inside instance method: by using either self or classname 3. inside class method: by using either cls variable or classname 4. inside static method: by using classname 5. From outside of class: by using either object reference or classnmae 1) class Test: 2) a=10 3) def __init__(self): 4) print(self.a) 5) print(Test.a) 6) def m1(self): 7) print(self.a)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21)

print(Test.a) @classmethod def m2(cls): print(cls.a) print(Test.a) @staticmethod def m3(): print(Test.a) t=Test() print(Test.a) print(t.a) t.m1() t.m2() t.m3()

Where we can modify the value of static variable: Anywhere either with in the class or outside of class we can modify by using classname. But inside class method, by using cls variable.

Example: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13)

class Test: a=777 @classmethod def m1(cls): cls.a=888 @staticmethod def m2(): Test.a=999 print(Test.a) Test.m1() print(Test.a) Test.m2() print(Test.a)

Output 777 888 999

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

If we change the value of static variable by using either self or object reference variable: If we change the value of static variable by using either self or object reference variable, then the value of static variable won't be changed,just a new instance variable with that name will be added to that particular object.

Example 1: 1) 2) 3) 4) 5) 6) 7) 8)

class Test: a=10 def m1(self): self.a=888 t1=Test() t1.m1() print(Test.a) print(t1.a)

Example: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13)

class Test: x=10 def __init__(self): self.y=20 t1=Test() t2=Test() print('t1:',t1.x,t1.y) print('t2:',t2.x,t2.y) t1.x=888 t1.y=999 print('t1:',t1.x,t1.y) print('t2:',t2.x,t2.y)

Output t1: 10 20 t2: 10 20 t1: 888 999 t2: 10 20

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Example: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

class Test: a=10 def __init__(self): self.b=20 t1=Test() t2=Test() Test.a=888 t1.b=999 print(t1.a,t1.b) print(t2.a,t2.b)

Output 888 999 888 20 -----------------------------------1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13)

class Test: a=10 def __init__(self): self.b=20 def m1(self): self.a=888 self.b=999 t1=Test() t2=Test() t1.m1() print(t1.a,t1.b) print(t2.a,t2.b)

Output 888 999 10 20

Example: 1) class Test: 2) a=10 3) def __init__(self): 4) self.b=20 5) @classmethod 6) def m1(cls): 7) cls.a=888 8) cls.b=999 9) 10) t1=Test() 11) t2=Test()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

t1.m1() print(t1.a,t1.b) print(t2.a,t2.b) print(Test.a,Test.b)

Output 888 20 888 20 888 999

How to delete static variables of a class: We can delete static variables from anywhere by using the following syntax del classname.variablename But inside classmethod we can also use cls variable del cls.variablename 1) class Test: 2) a=10 3) @classmethod 4) def m1(cls): 5) del cls.a 6) Test.m1() 7) print(Test.__dict__)

Example: 1) class Test: 2) a=10 3) def __init__(self): 4) Test.b=20 5) del Test.a 6) def m1(self): 7) Test.c=30 8) del Test.b 9) @classmethod 10) def m2(cls): 11) cls.d=40 12) del Test.c 13) @staticmethod 14) def m3(): 15) Test.e=50 16) del Test.d 17) print(Test.__dict__) 18) t=Test()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

19) 20) 21) 22) 23) 24) 25) 26) 27) 28) 29)

print(Test.__dict__) t.m1() print(Test.__dict__) Test.m2() print(Test.__dict__) Test.m3() print(Test.__dict__) Test.f=60 print(Test.__dict__) del Test.e print(Test.__dict__)

Note: By using object reference variable/self we can read static variables, but we cannot modify or delete. If we are trying to modify, then a new instance variable will be added to that particular object. t1.a = 70 If we are trying to delete then we will get error.

Example: 1) class Test: 2) a=10 3) 4) t1=Test() 5) del t1.a ===>AttributeError: a We can modify or delete static variables only by using classname or cls variable. 1) import sys 2) class Customer: 3) ''''' Customer class with bank operations.. ''' 4) bankname='DURGABANK' 5) def __init__(self,name,balance=0.0): 6) self.name=name 7) self.balance=balance 8) def deposit(self,amt): 9) self.balance=self.balance+amt 10) print('Balance after deposit:',self.balance) 11) def withdraw(self,amt): 12) if amt>self.balance: 13) print('Insufficient Funds..cannot perform this operation') 14) sys.exit() 15) self.balance=self.balance-amt 16) print('Balance after withdraw:',self.balance) 17) 18) print('Welcome to',Customer.bankname)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

19) name=input('Enter Your Name:') 20) c=Customer(name) 21) while True: 22) print('d-Deposit \nw-Withdraw \ne-exit') 23) option=input('Choose your option:') 24) if option=='d' or option=='D': 25) amt=float(input('Enter amount:')) 26) c.deposit(amt) 27) elif option=='w' or option=='W': 28) amt=float(input('Enter amount:')) 29) c.withdraw(amt) 30) elif option=='e' or option=='E': 31) print('Thanks for Banking') 32) sys.exit() 33) else: 34) print('Invalid option..Plz choose valid option')

output: D:\durga_classes>py test.py Welcome to DURGABANK Enter Your Name:Durga d-Deposit w-Withdraw e-exit Choose your option:d Enter amount:10000 Balance after deposit: 10000.0 d-Deposit w-Withdraw e-exit Choose your option:d Enter amount:20000 Balance after deposit: 30000.0 d-Deposit w-Withdraw e-exit Choose your option:w Enter amount:2000 Balance after withdraw: 28000.0 d-Deposit w-Withdraw e-exit Choose your option:r Invalid option..Plz choose valid option d-Deposit w-Withdraw e-exit Choose your option:e Thanks for Banking

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Local variables: Sometimes to meet temporary requirements of programmer,we can declare variables inside a method directly,such type of variables are called local variable or temporary variables. Local variables will be created at the time of method execution and destroyed once method completes. Local variables of a method cannot be accessed from outside of method.

Example: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

class Test: def m1(self): a=1000 print(a) def m2(self): b=2000 print(b) t=Test() t.m1() t.m2()

Output 1000 2000

Example 2: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11)

class Test: def m1(self): a=1000 print(a) def m2(self): b=2000 print(a) #NameError: name 'a' is not defined print(b) t=Test() t.m1() t.m2()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Types of Methods: Inside Python class 3 types of methods are allowed 1. Instance Methods 2. Class Methods 3. Static Methods

1. Instance Methods: Inside method implementation if we are using instance variables then such type of methods are called instance methods. Inside instance method declaration,we have to pass self variable. def m1(self): By using self variable inside method we can able to access instance variables. Within the class we can call instance method by using self variable and from outside of the class we can call by using object reference. 1) class Student: 2) def __init__(self,name,marks): 3) self.name=name 4) self.marks=marks 5) def display(self): 6) print('Hi',self.name) 7) print('Your Marks are:',self.marks) 8) def grade(self): 9) if self.marks>=60: 10) print('You got First Grade') 11) elif self.marks>=50: 12) print('Yout got Second Grade') 13) elif self.marks>=35: 14) print('You got Third Grade') 15) else: 16) print('You are Failed') 17) n=int(input('Enter number of students:')) 18) for i in range(n): 19) name=input('Enter Name:') 20) marks=int(input('Enter Marks:')) 21) s= Student(name,marks) 22) s.display() 23) s.grade() 24) print()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

ouput: D:\durga_classes>py test.py Enter number of students:2 Enter Name:Durga Enter Marks:90 Hi Durga Your Marks are: 90 You got First Grade Enter Name:Ravi Enter Marks:12 Hi Ravi Your Marks are: 12 You are Failed

Setter and Getter Methods: We can set and get the values of instance variables by using getter and setter methods.

Setter Method: setter methods can be used to set values to the instance variables. setter methods also known as mutator methods.

syntax: def setVariable(self,variable): self.variable=variable

Example: def setName(self,name): self.name=name

Getter Method: Getter methods can be used to get values of the instance variables. Getter methods also known as accessor methods.

syntax: def getVariable(self): return self.variable

Example: def getName(self): return self.name

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Demo Program: 1) class Student: 2) def setName(self,name): 3) self.name=name 4) 5) def getName(self): 6) return self.name 7) 8) def setMarks(self,marks): 9) self.marks=marks 10) 11) def getMarks(self): 12) return self.marks 13) 14) n=int(input('Enter number of students:')) 15) for i in range(n): 16) s=Student() 17) name=input('Enter Name:') 18) s.setName(name) 19) marks=int(input('Enter Marks:')) 20) s.setMarks(marks) 21) 22) print('Hi',s.getName()) 23) print('Your Marks are:',s.getMarks()) 24) print()

output: D:\python_classes>py test.py Enter number of students:2 Enter Name:Durga Enter Marks:100 Hi Durga Your Marks are: 100 Enter Name:Ravi Enter Marks:80 Hi Ravi Your Marks are: 80

2. Class Methods: Inside method implementation if we are using only class variables (static variables), then such type of methods we should declare as class method. We can declare class method explicitly by using @classmethod decorator. For class method we should provide cls variable at the time of declaration

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

We can call classmethod by using classname or object reference variable.

Demo Program: 1) class Animal: 2) legs=4 3) @classmethod 4) def walk(cls,name): 5) print('<> walks with <> legs. '.format(name,cls.legs)) 6) Animal.walk('Dog') 7) Animal.walk('Cat')

Output D:\python_classes>py test.py Dog walks with 4 legs. Cat walks with 4 legs.

Program to track the number of objects created for a class: 1) class Test: 2) count=0 3) def __init__(self): 4) Test.count =Test.count+1 5) @classmethod 6) def noOfObjects(cls): 7) print('The number of objects created for test class:',cls.count) 8) 9) t1=Test() 10) t2=Test() 11) Test.noOfObjects() 12) t3=Test() 13) t4=Test() 14) t5=Test() 15) Test.noOfObjects()

3. Static Methods: In general these methods are general utility methods. Inside these methods we won't use any instance or class variables. Here we won't provide self or cls arguments at the time of declaration. We can declare static method explicitly by using @staticmethod decorator We can access static methods by using classname or object reference 1) class DurgaMath: 2) 3) @staticmethod 4) def add(x,y):

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

5) print('The Sum:',x+y) 6) 7) @staticmethod 8) def product(x,y): 9) print('The Product:',x*y) 10) 11) @staticmethod 12) def average(x,y): 13) print('The average:',(x+y)/2) 14) 15) DurgaMath.add(10,20) 16) DurgaMath.product(10,20) 17) DurgaMath.average(10,20)

Output The Sum: 30 The Product: 200 The average: 15.0

Note: In general we can use only instance and static methods.Inside static method we can access class level variables by using class name. class methods are most rarely used methods in python.

Passing members of one class to another class: We can access members of one class inside another class. 1) class Employee: 2) def __init__(self,eno,ename,esal): 3) self.eno=eno 4) self.ename=ename 5) self.esal=esal 6) def display(self): 7) print('Employee Number:',self.eno) 8) print('Employee Name:',self.ename) 9) print('Employee Salary:',self.esal) 10) class Test: 11) def modify(emp): 12) emp.esal=emp.esal+10000 13) emp.display() 14) e=Employee(100,'Durga',10000) 15) Test.modify(e)

Output D:\python_classes>py test.py Employee Number: 100 Employee Name: Durga

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Employee Salary: 20000 In the above application, Employee class members are available to Test class.

Inner classes: Sometimes we can declare a class inside another class,such type of classes are called inner classes. Without existing one type of object if there is no chance of existing another type of object,then we should go for inner classes.

Example: Without existing Car object there is no chance of existing Engine object. Hence Engine class should be part of Car class. class Car: . class Engine: .

Example: Without existing university object there is no chance of existing Department object class University: . class Department: .

eg3: Without existing Human there is no chance of existin Head. Hence Head should be part of Human. class Human: class Head:

Note: Without existing outer class object there is no chance of existing inner class object. Hence inner class object is always associated with outer class object.

Demo Program-1: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11)

class Outer: def __init__(self): print("outer class object creation") class Inner: def __init__(self): print("inner class object creation") def m1(self): print("inner class method") o=Outer() i=o.Inner() i.m1()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Output outer class object creation inner class object creation inner class method

Note: The following are various possible syntaxes for calling inner class method 1. o=Outer() i=o.Inner() i.m1() 2. i=Outer().Inner() i.m1() 3. Outer().Inner().m1()

Demo Program-2: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17)

class Person: def __init__(self): self.name='durga' self.db=self.Dob() def display(self): print('Name:',self.name) class Dob: def __init__(self): self.dd=10 self.mm=5 self.yy=1947 def display(self): print('Dob=<>/<>/<>'.format(self.dd,self.mm,self.yy)) p=Person() p.display() x=p.db x.display()

Output Name: durga Dob=10/5/1947

Demo Program-3: Inside a class we can declare any number of inner classes. 1) class Human: 2) 3) def __init__(self):

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16)

self.name = 'Sunny' self.head = self.Head() self.brain = self.Brain() def display(self): print("Hello..",self.name) class Head: def talk(self): print('Talking. ') class Brain: def think(self): print('Thinking. ')

h=Human() h.display() h.head.talk() h.brain.think()

Output Hello.. Sunny Talking. Thinking.

Garbage Collection: In old languages like C++, programmer is responsible for both creation and destruction of objects.Usually programmer taking very much care while creating object, but neglecting destruction of useless objects. Because of his neglectance, total memory can be filled with useless objects which creates memory problems and total application will be down with Out of memory error. But in Python, We have some assistant which is always running in the background to destroy useless objects.Because this assistant the chance of failing Python program with memory problems is very less. This assistant is nothing but Garbage Collector. Hence the main objective of Garbage Collector is to destroy useless objects. If an object does not have any reference variable then that object eligible for Garbage Collection.

How to enable and disable Garbage Collector in our program: By default Gargbage collector is enabled, but we can disable based on our requirement. In this context we can use the following functions of gc module.

1. gc.isenabled() Returns True if GC enabled

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

2. gc.disable() To disable GC explicitly

3. gc.enable() To enable GC explicitly

Example: 1) 2) 3) 4) 5) 6)

import gc print(gc.isenabled()) gc.disable() print(gc.isenabled()) gc.enable() print(gc.isenabled())

Output True False True

Destructors: Destructor is a special method and the name should be __del__ Just before destroying an object Garbage Collector always calls destructor to perform clean up activities (Resource deallocation activities like close database connection etc). Once destructor execution completed then Garbage Collector automatically destroys that object.

Note: The job of destructor is not to destroy object and it is just to perform clean up activities. Example: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11)

import time class Test: def __init__(self): print("Object Initialization. ") def __del__(self): print("Fulfilling Last Wish and performing clean up activities. ") t1=Test() t1=None time.sleep(5) print("End of application")

Output Object Initialization. Fulfilling Last Wish and performing clean up activities. End of application

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Note: If the object does not contain any reference variable then only it is eligible fo GC. ie if the reference count is zero then only object eligible for GC

Example: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18)

import time class Test: def __init__(self): print("Constructor Execution. ") def __del__(self): print("Destructor Execution. ") t1=Test() t2=t1 t3=t2 del t1 time.sleep(5) print("object not yet destroyed after deleting t1") del t2 time.sleep(5) print("object not yet destroyed even after deleting t2") print("I am trying to delete last reference variable. ") del t3

Example: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11)

import time class Test: def __init__(self): print("Constructor Execution. ") def __del__(self): print("Destructor Execution. ") list=[Test(),Test(),Test()] del list time.sleep(5) print("End of application")

Output Constructor Execution. Constructor Execution. Constructor Execution. Destructor Execution. Destructor Execution. Destructor Execution. End of application

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

How to find the number of references of an object: sys module contains getrefcount() function for this purpose. sys.getrefcount(objectreference)

Example: 1) 2) 3) 4) 5) 6) 7) 8)

import sys class Test: pass t1=Test() t2=t1 t3=t1 t4=t1 print(sys.getrefcount(t1))

Output 5 Note: For every object, Python internally maintains one default reference variable self.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Polymorphism Poly means many. Morphs means forms. Polymorphism means 'Many Forms'.

Eg1: Yourself is best example of polymorphism.In front of Your parents You will have one type of behaviour and with friends another type of behaviour.Same person but different behaviours at different places,which is nothing but polymorphism.

Eg2: + operator acts as concatenation and arithmetic addition Eg3: * operator acts as multiplication and repetition operator Eg4: The Same method with different implementations in Parent class and child classes.(overriding) Related to polymorphism the following 4 topics are important 1. Duck Typing Philosophy of Python 2. Overloading 1. Operator Overloading 2. Method Overloading 3. Constructor Overloading 3. Overriding 1. Method overriding 2. constructor overriding

1. Duck Typing Philosophy of Python: In Python we cannot specify the type explicitly. Based on provided value at runtime the type will be considered automatically. Hence Python is considered as Dynamically Typed Programming Language. def f1(obj): obj.talk() What is the type of obj? We cannot decide at the beginning. At runtime we can pass any type.Then how we can decide the type? At runtime if 'it walks like a duck and talks like a duck,it must be duck'. Python follows this principle. This is called Duck Typing Philosophy of Python.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Demo Program: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22)

class Duck: def talk(self): print('Quack.. Quack..') class Dog: def talk(self): print('Bow Bow..') class Cat: def talk(self): print('Moew Moew ..') class Goat: def talk(self): print('Myaah Myaah ..') def f1(obj): obj.talk() l=[Duck(),Cat(),Dog(),Goat()] for obj in l: f1(obj)

Output: Quack.. Quack.. Moew Moew .. Bow Bow.. Myaah Myaah .. The problem in this approach is if obj does not contain talk() method then we will get AttributeError

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13)

class Duck: def talk(self): print('Quack.. Quack..') class Dog: def bark(self): print('Bow Bow..') def f1(obj): obj.talk() d=Duck() f1(d)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Output: D:\durga_classes>py test.py Quack.. Quack.. Traceback (most recent call last): File "test.py", line 22, in f1(d) File "test.py", line 13, in f1 obj.talk() AttributeError: 'Dog' object has no attribute 'talk' But we can solve this problem by using hasattr() function. hasattr(obj,'attributename') attributename can be method name or variable name

Demo Program with hasattr() function: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23) 24) 25) 26) 27)

class Duck: def talk(self): print('Quack.. Quack..') class Human: def talk(self): print('Hello Hi. ') class Dog: def bark(self): print('Bow Bow..') def f1(obj): if hasattr(obj,'talk'): obj.talk() elif hasattr(obj,'bark'): obj.bark() d=Duck() f1(d) h=Human() f1(h) d=Dog() f1(d) Myaah Myaah Myaah.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Overloading: We can use same operator or methods for different purposes.

Eg1: + operator can be used for Arithmetic addition and String concatenation print(10+20)#30 print('durga'+'soft')#durgasoft

Eg2: * operator can be used for multiplication and string repetition purposes. print(10*20)#200 print('durga'*3)#durgadurgadurga

Eg3: We can use deposit() method to deposit cash or cheque or dd deposit(cash) deposit(cheque) deposit(dd) There are 3 types of overloading 1. Operator Overloading 2. Method Overloading 3. Constructor Overloading

1. Operator Overloading: We can use the same operator for multiple purposes, which is nothing but operator overloading. Python supports operator overloading.

Eg1: + operator can be used for Arithmetic addition and String concatenation print(10+20)#30 print('durga'+'soft')#durgasoft

Eg2: * operator can be used for multiplication and string repetition purposes. print(10*20)#200 print('durga'*3)#durgadurgadurga

Demo program to use + operator for our class objects: 1) 2) 3) 4) 5) 6) 7)

class Book: def __init__(self,pages): self.pages=pages b1=Book(100) b2=Book(200) print(b1+b2)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

D:\durga_classes>py test.py Traceback (most recent call last): File "test.py", line 7, in print(b1+b2) TypeError: unsupported operand type(s) for +: 'Book' and 'Book' We can overload + operator to work with Book objects also. i.e Python supports Operator Overloading. For every operator Magic Methods are available. To overload any operator we have to override that Method in our class. Internally + operator is implemented by using __add__() method.This method is called magic method for + operator. We have to override this method in our class.

Demo program to overload + operator for our Book class objects: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

class Book: def __init__(self,pages): self.pages=pages def __add__(self,other): return self.pages+other.pages b1=Book(100) b2=Book(200) print('The Total Number of Pages:',b1+b2)

Output: The Total Number of Pages: 300 The following is the list of operators and corresponding magic methods. + ---> object.__add__(self,other) - ---> object.__sub__(self,other) * ---> object.__mul__(self,other) / ---> object.__div__(self,other) // ---> object.__floordiv__(self,other) % ---> object.__mod__(self,other) ** ---> object.__pow__(self,other) += ---> object.__iadd__(self,other) -= ---> object.__isub__(self,other) *= ---> object.__imul__(self,other) /= ---> object.__idiv__(self,other) //= ---> object.__ifloordiv__(self,other) %= ---> object.__imod__(self,other) **= ---> object.__ipow__(self,other) object.__lt__(self,other) object.__le__(self,other) > ---> object.__gt__(self,other) >= ---> object.__ge__(self,other)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Overloading > and other.marks def __le__(self,other): return self.marks 20 Durga",100) s2=Student("Ravi",200) print("s1>s2 s1

2. finditer(): Returns an Iterator object which yields Match object for every Match matcher = pattern.finditer("abaababa") On Match object we can call the following methods. 1. start()  Returns start index of the match 2. end()  Returns end+1 index of the match 3. group()  Returns the matched string

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: 1) 2) 3) 4) 5) 6) 7)

import re count=0 pattern=re.compile("ab") matcher=pattern.finditer("abaababa") for match in matcher: count+=1 print(match.start(),". ",match.end(),". ",match.group()) print("The number of occurrences: ",count)

Output: 0 . 2 . ab 3 . 5 . ab 5 . 7 . ab The number of occurrences: 3

Note: We can pass pattern directly as argument to finditer() function. Eg: 1) 2) 3) 4) 5) 6) 7)

import re count=0 matcher=re.finditer("ab","abaababa") for match in matcher: count+=1 print(match.start(),". ",match.end(),". ",match.group()) print("The number of occurrences: ",count)

Output: 0 . 2 . ab 3 . 5 . ab 5 . 7 . ab The number of occurrences: 3

Character classes: We can use character classes to search a group of characters 1. [abc]===>Either a or b or c 2. [^abc] ===>Except a and b and c 3. [a-z]==>Any Lower case alphabet symbol 4. [A-Z]===>Any upper case alphabet symbol 5. [a-zA-Z]==>Any alphabet symbol 6. [0-9] Any digit from 0 to 9 7. [a-zA-Z0-9]==>Any alphanumeric character 8. [^a-zA-Z0-9]==>Except alphanumeric characters(Special Characters)

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: 1) import re 2) matcher=re.finditer("x","a7b@k9z") 3) for match in matcher: 4) print(match.start(),". ",match.group())

x = [abc] 0 . a 2 . b

x = [^abc] 1 . 7 3 . @ 4 . k 5 . 9 6 . z

x = [a-z] 0 . a 2 . b 4 . k 6 . z

x = [0-9] 1 . 7 5 . 9

x = [a-zA-Z0-9] 0 . a 1 . 7 2 . b 4 . k 5 . 9 6 . z

Pre defined Character classes: \s  Space character \S  Any character except space character \d  Any digit from 0 to 9 \D  Any character except digit \w  Any word character [a-zA-Z0-9] \W  Any character except word character (Special Characters) .  Any character including special characters

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: 1) import re 2) matcher=re.finditer("x","a7b k@9z") 3) for match in matcher: 4) print(match.start(),". ",match.group())

x = \S: 0 . a 1 . 7 2 . b 4 . k 5 . @ 6 . 9 7 . z

x = \D: 0 . a 2 . b 3 . 4 . k 5 . @ 7 . z

x = \w: 0 . a 1 . 7 2 . b 4 . k 6 . 9 7 . z

x=. 0 . a 1 . 7 2 . b 3 .

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

4 . k 5 . @ 6 . 9 7 . z

Qunatifiers: We can use quantifiers to specify the number of occurrences to match. a  Exactly one 'a' a+  Atleast one 'a' a*  Any number of a's including zero number a?  Atmost one 'a' ie either zero number or one number a  Exactly m number of a's a  Minimum m number of a's and Maximum n number of a's

Eg: 1) import re 2) matcher=re.finditer("x","abaabaaab") 3) for match in matcher: 4) print(match.start(),". ",match.group())

x = a: 0 . a 2 . a 3 . a 5 . a 6 . a 7 . a

x = a+: 0 . a 2 . aa 5 . aaa

x = a*: 0 . a 1 . 2 . aa 4 . 5 . aaa 8 . 9 .

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

x = a?: 0 . a 1 . 2 . a 3 . a 4 . 5 . a 6 . a 7 . a 8 . 9 .

x = a: 2 . aa 5 . aaa

Note: ^x  It will check whether target string starts with x or not x$  It will check whether target string ends with x or not

Important functions of re module: 1. match() 2. fullmatch() 3. search() 4.findall() 5.finditer() 6. sub() 7.subn() 8. split() 9. compile()

1. match(): We can use match function to check the given pattern at beginning of target string. If the match is available then we will get Match object, otherwise we will get None.

import re s=input("Enter pattern to check: ") m=re.match(s,"abcabdefg") if m!= None: print("Match is available at the beginning of the String") print("Start Index:",m.start(), "and End Index:",m.end())

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

7) else: 8) print("Match is not available at the beginning of the String")

Output: D:\python_classes>py test.py Enter pattern to check: abc Match is available at the beginning of the String Start Index: 0 and End Index: 3 D:\python_classes>py test.py Enter pattern to check: bde Match is not available at the beginning of the String

2. fullmatch(): We can use fullmatch() function to match a pattern to all of target string. i.e complete string should be matched according to given pattern. If complete string matched then this function returns Match object otherwise it returns None.

Eg: 1) 2) 3) 4) 5) 6) 7)

import re s=input("Enter pattern to check: ") m=re.fullmatch(s,"ababab") if m!= None: print("Full String Matched") else: print("Full String not Matched")

Output: D:\python_classes>py test.py Enter pattern to check: ab Full String not Matched D:\python_classes>py test.py Enter pattern to check: ababab Full String Matched

3. search(): We can use search() function to search the given pattern in the target string. If the match is available then it returns the Match object which represents first occurrence of the match. If the match is not available then it returns None

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Eg: 1) 2) 3) 4) 5) 6) 7) 8)

import re s=input("Enter pattern to check: ") m=re.search(s,"abaaaba") if m!= None: print("Match is available") print("First Occurrence of match with start index:",m.start(),"and end index:",m.end()) else: print("Match is not available")

Output: D:\python_classes>py test.py Enter pattern to check: aaa Match is available First Occurrence of match with start index: 2 and end index: 5 D:\python_classes>py test.py Enter pattern to check: bbb Match is not available

4. findall(): To find all occurrences of the match. This function returns a list object which contains all occurrences.

Eg: 1) import re 2) l=re.findall("[0-9]","a7b9c5kz") 3) print(l)

5. finditer(): Returns the iterator yielding a match object for each match. On each match object we can call start(), end() and group() functions.

Eg: 1) import re 2) itr=re.finditer("[a-z]","a7b9c5k8z") 3) for m in itr: 4) print(m.start(),". ",m.end(),". ",m.group())

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Output: D:\python_classes>py test.py 0 . 1 . a 2 . 3 . b 4 . 5 . c 6 . 7 . k 8 . 9 . z

6. sub(): sub means substitution or replacement re.sub(regex,replacement,targetstring) In the target string every matched pattern will be replaced with provided replacement.

Eg: 1) import re 2) s=re.sub("[a-z]","#","a7b9c5k8z") 3) print(s)

Output: #7#9#5#8# Every alphabet symbol is replaced with # symbol

7. subn(): It is exactly same as sub except it can also returns the number of replacements. This function returns a tuple where first element is result string and second element is number of replacements. (resultstring, number of replacements)

import re t=re.subn("[a-z]","#","a7b9c5k8z") print(t) print("The Result String:",t[0]) print("The number of replacements:",t[1])

Output: D:\python_classes>py test.py ('#7#9#5#8#', 5) The Result String: #7#9#5#8# The number of replacements: 5

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

8. split(): If we want to split the given target string according to a particular pattern then we should go for split() function. This function returns list of all tokens.

import re l=re.split(",","sunny,bunny,chinny,vinny,pinny") print(l) for t in l: print(t)

Output: D:\python_classes>py test.py ['sunny', 'bunny', 'chinny', 'vinny', 'pinny'] sunny bunny chinny vinny pinny

Eg: 1) import re 2) l=re.split("\.","www.durgasoft.com") 3) for t in l: 4) print(t)

Output: D:\python_classes>py test.py www durgasoft com

^ symbol: We can use ^ symbol to check whether the given target string starts with our provided pattern or not.

Eg: res=re.search("^Learn",s) if the target string starts with Learn then it will return Match object,otherwise returns None.

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

test.py: 1) 2) 3) 4) 5) 6) 7)

import re s="Learning Python is Very Easy" res=re.search("^Learn",s) if res != None: print("Target String starts with Learn") else: print("Target String Not starts with Learn")

Output: Target String starts with Learn

$ symbol: We can use $ symbol to check whether the given target string ends with our provided pattern or not

Eg: res=re.search("Easy$",s) If the target string ends with Easy then it will return Match object,otherwise returns None.

test.py: 1) 2) 3) 4) 5) 6) 7)

import re s="Learning Python is Very Easy" res=re.search("Easy$",s) if res != None: print("Target String ends with Easy") else: print("Target String Not ends with Easy")

Output: Target String ends with Easy Note: If we want to ignore case then we have to pass 3rd argument re.IGNORECASE for search() function.

Eg: res = re.search("easy$",s,re.IGNORECASE) test.py: 1) 2) 3) 4) 5) 6) 7)

import re s="Learning Python is Very Easy" res=re.search("easy$",s,re.IGNORECASE) if res != None: print("Target String ends with Easy by ignoring case") else: print("Target String Not ends with Easy by ignoring case")

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Output: Target String ends with Easy by ignoring case

App1: Write a Regular Expression to represent all Yava language identifiers Rules: 1. The allowed characters are a-z,A-Z,0-9,# 2. The first character should be a lower case alphabet symbol from a to k 3. The second character should be a digit divisible by 3 4. The length of identifier should be atleast 2. [a-k][0369][a-zA-Z0-9#]*

App2: Write a python program to check whether the given string is Yava language identifier or not? 1) 2) 3) 4) 5) 6) 7)

import re s=input("Enter Identifier:") m=re.fullmatch("[a-k][0369][a-zA-Z0-9#]*",s) if m!= None: print(s,"is valid Yava Identifier") else: print(s,"is invalid Yava Identifier")

Output: D:\python_classes>py test.py Enter Identifier:a6kk9z## a6kk9z## is valid Yava Identifier D:\python_classes>py test.py Enter Identifier:k9b876 k9b876 is valid Yava Identifier D:\python_classes>py test.py Enter Identifier:k7b9 k7b9 is invalid Yava Identifier

App3: Write a Regular Expression to represent all 10 digit mobile numbers. Rules: 1. Every number should contains exactly 10 digits 2. The first digit should be 7 or 8 or 9 [7-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] or

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

App4: Write a Python Program to check whether the given number is valid mobile number or not? 1) 2) 3) 4) 5) 6) 7)

import re n=input("Enter number:") m=re.fullmatch("[7-9]\d",n) if m!= None: print("Valid Mobile Number") else: print("Invalid Mobile Number")

Output: D:\python_classes>py test.py Enter number:9898989898 Valid Mobile Number D:\python_classes>py test.py Enter number:6786786787 Invalid Mobile Number D:\python_classes>py test.py Enter number:898989 Invalid Mobile Number

App5: Write a python program to extract all mobile numbers present in input.txt where numbers are mixed with normal text data 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

import re f1=open("input.txt","r") f2=open("output.txt","w") for line in f1: list=re.findall("[7-9]\d",line) for n in list: f2.write(n+"\n") print("Extracted all Mobile Numbers into output.txt") f1.close() f2.close()

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Web Scraping by using Regular Expressions: The process of collecting information from web pages is called web scraping. In web scraping to match our required patterns like mail ids, mobile numbers we can use regular expressions.

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

import re,urllib import urllib.request sites="google rediff".split() print(sites) for s in sites: print("Searching. ",s) u=urllib.request.urlopen("http://"+s+".com") text=u.read() title=re.findall(" .* ",str(text),re.I) print(title[0])

Eg: Program to get all phone numbers of redbus.in by using web scraping and regular expressions 1) 2) 3) 4) 5) 6) 7)

import re,urllib import urllib.request u=urllib.request.urlopen("https://www.redbus.in/info/contactus") text=u.read() numbers=re.findall("[0-9-][0-9-]+",str(text),re.I) for n in numbers: print(n)

Q. Write a Python Program to check whether the given mail id is valid gmail id or not? 1) 2) 3) 4) 5) 6) 7)

import re s=input("Enter Mail id:") m=re.fullmatch("\w[a-zA-Z0-9_.]*@gmail[.]com",s) if m!=None: print("Valid Mail Id"); else: print("Invalid Mail id")

Output: D:\python_classes>py test.py Enter Mail id:[email protected] Valid Mail Id

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

D:\python_classes>py test.py Enter Mail id:durgatoc Invalid Mail id D:\python_classes>py test.py Enter Mail id:[email protected] Invalid Mail id

Q. Write a python program to check whether given car registration number is valid Telangana State Registration number or not? 1) 2) 3) 4) 5) 6) 7)

import re s=input("Enter Vehicle Registration Number:") m=re.fullmatch("TS[012][0-9][A-Z]\d",s) if m!=None: print("Valid Vehicle Registration Number"); else: print("Invalid Vehicle Registration Number")

Output: D:\python_classes>py test.py Enter Vehicle Registration Number:TS07EA7777 Valid Vehicle Registration Number D:\python_classes>py test.py Enter Vehicle Registration Number:TS07KF0786 Valid Vehicle Registration Number D:\python_classes>py test.py Enter Vehicle Registration Number:AP07EA7898 Invalid Vehicle Registration Number

Q. Python Program to check whether the given mobile number is valid OR not (10 digit OR 11 digit OR 12 digit) 1) 2) 3) 4) 5) 6) 7)

import re s=input("Enter Mobile Number:") m=re.fullmatch("(0|91)?[7-9][0-9]",s) if m!=None: print("Valid Mobile Number"); else: print("Invalid Mobile Number")

Summary table and some more examples.

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Multi Threading Multi Tasking: Executing several tasks simultaneously is the concept of multitasking. There are 2 types of Multi Tasking 1. Process based Multi Tasking 2. Thread based Multi Tasking

1. Process based Multi Tasking: Executing several tasks simmultaneously where each task is a seperate independent process is called process based multi tasking.

Eg: while typing python program in the editor we can listen mp3 audio songs from the same system. At the same time we can download a file from the internet. All these taks are executing simultaneously and independent of each other. Hence it is process based multi tasking. This type of multi tasking is best suitable at operating system level.

2. Thread based MultiTasking: Executing several tasks simultaneously where each task is a seperate independent part of the same program, is called Thread based multi tasking, and each independent part is called a Thread. This type of multi tasking is best suitable at programmatic level.

Note: Whether it is process based or thread based, the main advantage of multi tasking is to improve performance of the system by reducing response time. The main important application areas of multi threading are: 1. To implement Multimedia graphics 2. To develop animations 3. To develop video games 4. To develop web and application servers etc.

Note: Where ever a group of independent jobs are available, then it is highly recommended to execute simultaneously instead of executing one by one.For such type of cases we should go for Multi Threading. Python provides one inbuilt module "threading" to provide support for developing threads. Hence developing multi threaded Programs is very easy in python.

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Every Python Program by default contains one thread which is nothing but MainThread.

Q.Program to print name of current executing thread: 1) import threading 2) print("Current Executing Thread:",threading.current_thread().getName())

o/p: Current Executing Thread: MainThread Note: threading module contains function current_thread() which returns the current executing Thread object. On this object if we call getName() method then we will get current executing thread name.

The ways of Creating Thread in Python: We can create a thread in Python by using 3 ways 1. Creating a Thread without using any class 2. Creating a Thread by extending Thread class 3. Creating a Thread without extending Thread class

1. Creating a Thread without using any class: 1) 2) 3) 4) 5) 6) 7) 8)

from threading import * def display(): for i in range(1,11): print("Child Thread") t=Thread(target=display) #creating Thread object t.start() #starting of Thread for i in range(1,11): print("Main Thread")

If multiple threads present in our program, then we cannot expect execution order and hence we cannot expect exact output for the multi threaded programs. B'z of this we cannot provide exact output for the above program.It is varied from machine to machine and run to run.

Note: Thread is a pre defined class present in threading module which can be used to create our own Threads.

2. Creating a Thread by extending Thread class We have to create child class for Thread class. In that child class we have to override run() method with our required job. Whenever we call start() method then automatically run() method will be executed and performs our job. 1) from threading import * 2) class MyThread(Thread):

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

3) def run(self): 4) for i in range(10): 5) print("Child Thread-1") 6) t=MyThread() 7) t.start() 8) for i in range(10): 9) print("Main Thread-1")

3. Creating a Thread without extending Thread class: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10)

from threading import * class Test: def display(self): for i in range(10): print("Child Thread-2") obj=Test() t=Thread(target=obj.display) t.start() for i in range(10): print("Main Thread-2")

Without multi threading: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15)

from threading import * import time def doubles(numbers): for n in numbers: time.sleep(1) print("Double:",2*n) def squares(numbers): for n in numbers: time.sleep(1) print("Square:",n*n) numbers=[1,2,3,4,5,6] begintime=time.time() doubles(numbers) squares(numbers) print("The total time taken:",time.time()-begintime)

With multithreading: 1) 2) 3) 4) 5) 6) 7) 8)

from threading import * import time def doubles(numbers): for n in numbers: time.sleep(1) print("Double:",2*n) def squares(numbers): for n in numbers:

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20)

time.sleep(1) print("Square:",n*n) numbers=[1,2,3,4,5,6] begintime=time.time() t1=Thread(target=doubles,args=(numbers,)) t2=Thread(target=squares,args=(numbers,)) t1.start() t2.start() t1.join() t2.join() print("The total time taken:",time.time()-begintime)

Setting and Getting Name of a Thread: Every thread in python has name. It may be default name generated by Python or Customized Name provided by programmer. We can get and set name of thread by using the following Thread class methods. t.getName()  Returns Name of Thread t.setName(newName)  To set our own name

Note: Every Thread has implicit variable "name" to represent name of Thread. Eg: 1) 2) 3) 4) 5)

from threading import * print(current_thread().getName()) current_thread().setName("Pawan Kalyan") print(current_thread().getName()) print(current_thread().name)

Output: MainThread Pawan Kalyan Pawan Kalyan

Thread Identification Number (ident): For every thread internally a unique identification number is available. We can access this id by using implicit variable "ident" 1) from threading import * 2) def test(): 3) print("Child Thread") 4) t=Thread(target=test)

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

5) t.start() 6) print("Main Thread Identification Number:",current_thread().ident) 7) print("Child Thread Identification Number:",t.ident)

Output: Child Thread Main Thread Identification Number: 2492 Child Thread Identification Number: 2768

active_count(): This function returns the number of active threads currently running.

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16)

from threading import * import time def display(): print(current_thread().getName(),". started") time.sleep(3) print(current_thread().getName(),". ended") print("The Number of active Threads:",active_count()) t1=Thread(target=display,name="ChildThread1") t2=Thread(target=display,name="ChildThread2") t3=Thread(target=display,name="ChildThread3") t1.start() t2.start() t3.start() print("The Number of active Threads:",active_count()) time.sleep(5) print("The Number of active Threads:",active_count())

Output: D:\python_classes>py test.py The Number of active Threads: 1 ChildThread1 . started ChildThread2 . started ChildThread3 . started The Number of active Threads: 4 ChildThread1 . ended ChildThread2 . ended ChildThread3 . ended The Number of active Threads: 1

enumerate() function: This function returns a list of all active threads currently running.

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19)

from threading import * import time def display(): print(current_thread().getName(),". started") time.sleep(3) print(current_thread().getName(),". ended") t1=Thread(target=display,name="ChildThread1") t2=Thread(target=display,name="ChildThread2") t3=Thread(target=display,name="ChildThread3") t1.start() t2.start() t3.start() l=enumerate() for t in l: print("Thread Name:",t.name) time.sleep(5) l=enumerate() for t in l: print("Thread Name:",t.name)

Output: D:\python_classes>py test.py ChildThread1 . started ChildThread2 . started ChildThread3 . started Thread Name: MainThread Thread Name: ChildThread1 Thread Name: ChildThread2 Thread Name: ChildThread3 ChildThread1 . ended ChildThread2 . ended ChildThread3 . ended Thread Name: MainThread

isAlive(): isAlive() method checks whether a thread is still executing or not.

Eg: 1) 2) 3) 4) 5) 6) 7) 8)

from threading import * import time def display(): print(current_thread().getName(),". started") time.sleep(3) print(current_thread().getName(),". ended") t1=Thread(target=display,name="ChildThread1") t2=Thread(target=display,name="ChildThread2")

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

9) 10) 11) 12) 13) 14) 15) 16)

t1.start() t2.start() print(t1.name,"is Alive :",t1.isAlive()) print(t2.name,"is Alive :",t2.isAlive()) time.sleep(5) print(t1.name,"is Alive :",t1.isAlive()) print(t2.name,"is Alive :",t2.isAlive())

Output: D:\python_classes>py test.py ChildThread1 . started ChildThread2 . started ChildThread1 is Alive : True ChildThread2 is Alive : True ChildThread1 . ended ChildThread2 . ended ChildThread1 is Alive : False ChildThread2 is Alive : False

join() method: If a thread wants to wait until completing some other thread then we should go for join() method.

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12)

from threading import * import time def display(): for i in range(10): print("Seetha Thread") time.sleep(2) t=Thread(target=display) t.start() t.join()#This Line executed by Main Thread for i in range(10): print("Rama Thread")

In the above example Main Thread waited until completing child thread. In this case output is: Seetha Thread Seetha Thread Seetha Thread Seetha Thread Seetha Thread Seetha Thread Seetha Thread

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Seetha Thread Seetha Thread Seetha Thread Rama Thread Rama Thread Rama Thread Rama Thread Rama Thread Rama Thread Rama Thread Rama Thread Rama Thread Rama Thread

Note: We can call join() method with time period also. t.join(seconds) In this case thread will wait only specified amount of time.

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12)

from threading import * import time def display(): for i in range(10): print("Seetha Thread") time.sleep(2) t=Thread(target=display) t.start() t.join(5)#This Line executed by Main Thread for i in range(10): print("Rama Thread")

In this case Main Thread waited only 5 seconds.

Output: Seetha Thread Seetha Thread Seetha Thread Rama Thread Rama Thread Rama Thread Rama Thread Rama Thread Rama Thread Rama Thread

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Rama Thread Rama Thread Rama Thread Seetha Thread Seetha Thread Seetha Thread Seetha Thread Seetha Thread Seetha Thread Seetha Thread Summary of all methods related to threading module and Thread

Daemon Threads: The threads which are running in the background are called Daemon Threads. The main objective of Daemon Threads is to provide support for Non Daemon Threads( like main thread)

Eg: Garbage Collector Whenever Main Thread runs with low memory, immediately PVM runs Garbage Collector to destroy useless objects and to provide free memory,so that Main Thread can continue its execution without having any memory problems. We can check whether thread is Daemon or not by using t.isDaemon() method of Thread class or by using daemon property.

Eg: 1) from threading import * 2) print(current_thread().isDaemon()) #False 3) print(current_thread().daemon) #False We can change Daemon nature by using setDaemon() method of Thread class. t.setDaemon(True) But we can use this method before starting of Thread.i.e once thread started,we cannot change its Daemon nature,otherwise we will get RuntimeException:cannot set daemon status of active thread

Eg: 1) from threading import * 2) print(current_thread().isDaemon())

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

3) current_thread().setDaemon(True) RuntimeError: cannot set daemon status of active thread

Default Nature: By default Main Thread is always non-daemon.But for the remaining threads Daemon nature will be inherited from parent to child.i.e if the Parent Thread is Daemon then child thread is also Daemon and if the Parent Thread is Non Daemon then ChildThread is also Non Daemon.

Eg: 1) 2) 3) 4) 5) 6) 7)

from threading import * def job(): print("Child Thread") t=Thread(target=job) print(t.isDaemon())#False t.setDaemon(True) print(t.isDaemon()) #True

Note: Main Thread is always Non-Daemon and we cannot change its Daemon Nature b'z it is already started at the beginning only. Whenever the last Non-Daemon Thread terminates automatically all Daemon Threads will be terminated.

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12)

from threading import * import time def job(): for i in range(10): print("Lazy Thread") time.sleep(2) t=Thread(target=job) #t.setDaemon(True)===>Line-1 t.start() time.sleep(5) print("End Of Main Thread")

In the above program if we comment Line-1 then both Main Thread and Child Threads are Non Daemon and hence both will be executed until their completion. In this case output is: Lazy Thread Lazy Thread Lazy Thread

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

End Of Main Thread Lazy Thread Lazy Thread Lazy Thread Lazy Thread Lazy Thread Lazy Thread Lazy Thread If we are not commenting Line-1 then Main Thread is Non-Daemon and Child Thread is Daemon. Hence whenever MainThread terminates automatically child thread will be terminated. In this case output is Lazy Thread Lazy Thread Lazy Thread End of Main Thread

Synchronization: If multiple threads are executing simultaneously then there may be a chance of data inconsistency problems.

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11)

from threading import * import time def wish(name): for i in range(10): print("Good Evening:",end='') time.sleep(2) print(name) t1=Thread(target=wish,args=("Dhoni",)) t2=Thread(target=wish,args=("Yuvraj",)) t1.start() t2.start()

Output: Good Evening:Good Evening:Yuvraj Dhoni Good Evening:Good Evening:Yuvraj Dhoni . We are getting irregular output b'z both threads are executing simultaneously wish() function. To overcome this problem we should go for synchronization.

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

In synchronization the threads will be executed one by one so that we can overcome data inconsistency problems. Synchronization means at a time only one Thread The main application areas of synchronization are 1. Online Reservation system 2. Funds Transfer from joint accounts etc In Python, we can implement synchronization by using the following 1. Lock 2. RLock 3. Semaphore

Synchronization By using Lock concept: Locks are the most fundamental synchronization mechanism provided by threading module. We can create Lock object as follows l=Lock() The Lock object can be hold by only one thread at a time.If any other thread required the same lock then it will wait until thread releases lock.(similar to common wash rooms,public telephone booth etc) A Thread can acquire the lock by using acquire() method. l.acquire() A Thread can release the lock by using release() method. l.release()

Note: To call release() method compulsory thread should be owner of that lock.i.e thread should has the lock already,otherwise we will get Runtime Exception saying RuntimeError: release unlocked lock

Eg: 1) from threading import * 2) l=Lock() 3) #l.acquire() ==>1 4) l.release() If we are commenting line-1 then we will get RuntimeError: release unlocked lock

Eg: 1) from threading import *

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17)

import time l=Lock() def wish(name): l.acquire() for i in range(10): print("Good Evening:",end='') time.sleep(2) print(name) l.release() t1=Thread(target=wish,args=("Dhoni",)) t2=Thread(target=wish,args=("Yuvraj",)) t3=Thread(target=wish,args=("Kohli",)) t1.start() t2.start() t3.start()

In the above program at a time only one thread is allowed to execute wish() method and hence we will get regular output.

Problem with Simple Lock: The standard Lock object does not care which thread is currently holding that lock.If the lock is held and any thread attempts to acquire lock, then it will be blocked,even the same thread is already holding that lock.

from threading import * l=Lock() print("Main Thread trying to acquire Lock") l.acquire() print("Main Thread trying to acquire Lock Again") l.acquire()

Output: D:\python_classes>py test.py Main Thread trying to acquire Lock Main Thread trying to acquire Lock Again -In the above Program main thread will be blocked b'z it is trying to acquire the lock second time.

Note: To kill the blocking thread from windows command prompt we have to use ctrl+break. Here ctrl+C won't work. If the Thread calls recursive functions or nested access to resources,then the thread may trying to acquire the same lock again and again,which may block our thread.

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Hence Traditional Locking mechanism won't work for executing recursive functions. To overcome this problem, we should go for RLock(Reentrant Lock). Reentrant means the thread can acquire the same lock again and again.If the lock is held by other threads then only the thread will be blocked. Reentrant facility is available only for owner thread but not for other threads.

from threading import * l=RLock() print("Main Thread trying to acquire Lock") l.acquire() print("Main Thread trying to acquire Lock Again") l.acquire()

In this case Main Thread won't be Locked b'z thread can acquire the lock any number of times. This RLock keeps track of recursion level and hence for every acquire() call compulsory release() call should be available. i.e the number of acquire() calls and release() calls should be matched then only lock will be released.

Eg: l=RLock() l.acquire() l.acquire() l.release() l.release() After 2 release() calls only the Lock will be released.

Note: 1. Only owner thread can acquire the lock multiple times 2. The number of acquire() calls and release() calls should be matched.

Demo Program for synchronization by using RLock: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11)

from threading import * import time l=RLock() def factorial(n): l.acquire() if n==0: result=1 else: result=n*factorial(n-1) l.release() return result

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

12) 13) 14) 15) 16) 17) 18) 19)

def results(n): print("The Factorial of",n,"is:",factorial(n)) t1=Thread(target=results,args=(5,)) t2=Thread(target=results,args=(9,)) t1.start() t2.start()

Output: The Factorial of 5 is: 120 The Factorial of 9 is: 362880 In the above program instead of RLock if we use normal Lock then the thread will be blocked.

Difference between Lock and RLock: table

Lock: 1. Lock object can be acquired by only one thread at a time.Even owner thread also cannot acquire multiple times. 2. Not suitable to execute recursive functions and nested access calls 3. In this case Lock object will takes care only Locked or unlocked and it never takes care about owner thread and recursion level.

RLock: 1. RLock object can be acquired by only one thread at a time, but owner thread can acquire same lock object multiple times. 2. Best suitable to execute recursive functions and nested access calls 3. In this case RLock object will takes care whether Locked or unlocked and owner thread information, recursiion level.

Synchronization by using Semaphore: In the case of Lock and RLock,at a time only one thread is allowed to execute. Sometimes our requirement is at a time a particular number of threads are allowed to access(like at a time 10 memebers are allowed to access database server,4 members are allowed to access Network connection etc).To handle this requirement we cannot use Lock and RLock concepts and we should go for Semaphore concept. Semaphore can be used to limit the access to the shared resources with limited capacity. Semaphore is advanced Synchronization Mechanism.

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

We can create Semaphore object as follows.

s=Semaphore(counter) Here counter represents the maximum number of threads are allowed to access simultaneously. The default value of counter is 1. Whenever thread executes acquire() method,then the counter value will be decremented by 1 and if thread executes release() method then the counter value will be incremented by 1. i.e for every acquire() call counter value will be decremented and for every release() call counter value will be incremented.

In this case counter value is 1 and at a time only one thread is allowed to access. It is exactly same as Lock concept.

Case-2: s=Semaphore(3) In this case Semaphore object can be accessed by 3 threads at a time.The remaining threads have to wait until releasing the semaphore.

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21)

from threading import * import time s=Semaphore(2) def wish(name): s.acquire() for i in range(10): print("Good Evening:",end='') time.sleep(2) print(name) s.release() t1=Thread(target=wish,args=("Dhoni",)) t2=Thread(target=wish,args=("Yuvraj",)) t3=Thread(target=wish,args=("Kohli",)) t4=Thread(target=wish,args=("Rohit",)) t5=Thread(target=wish,args=("Pandya",)) t1.start() t2.start() t3.start() t4.start() t5.start()

In the above program at a time 2 threads are allowed to access semaphore and hence 2 threads are allowed to execute wish() function.

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

BoundedSemaphore: Normal Semaphore is an unlimited semaphore which allows us to call release() method any number of times to increment counter.The number of release() calls can exceed the number of acquire() calls also.

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9)

from threading import * s=Semaphore(2) s.acquire() s.acquire() s.release() s.release() s.release() s.release() print("End")

It is valid because in normal semaphore we can call release() any number of times. BounedSemaphore is exactly same as Semaphore except that the number of release() calls should not exceed the number of acquire() calls,otherwise we will get ValueError: Semaphore released too many times

Eg: 1) 2) 3) 4) 5) 6) 7) 8) 9)

from threading import * s=BoundedSemaphore(2) s.acquire() s.acquire() s.release() s.release() s.release() s.release() print("End")

ValueError: Semaphore released too many times It is invalid b'z the number of release() calls should not exceed the number of acquire() calls in BoundedSemaphore.

Note: To prevent simple programming mistakes, it is recommended to use BoundedSemaphore over normal Semaphore.

Difference between Lock and Semaphore: 17

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

At a time Lock object can be acquired by only one thread, but Semaphore object can be acquired by fixed number of threads specified by counter value.

Conclusion: The main advantage of synchronization is we can overcome data inconsistency problems.But the main disadvantage of synchronization is it increases waiting time of threads and creates performance problems. Hence if there is no specific requirement then it is not recommended to use synchronization.

Inter Thread Communication: Some times as the part of programming requirement, threads are required to communicate with each other. This concept is nothing but interthread communication.

Eg: After producing items Producer thread has to communicate with Consumer thread to notify about new item.Then consumer thread can consume that new item. In Python, we can implement interthread communication by using the following ways 1. Event 2. Condition 3. Queue etc

Interthread communication by using Event Objects: Event object is the simplest communication mechanism between the threads. One thread signals an event and other thereds wait for it. We can create Event object as follows. event = threading.Event() Event manages an internal flag that can set() or clear() Threads can wait until event set.

Methods of Event class: 1.set()  internal flag value will become True and it represents GREEN signal for all waiting threads. 2. clear()  inernal flag value will become False and it represents RED signal for all waiting threads. 3. isSet()  This method can be used whether the event is set or not

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

4. wait()|wait(seconds)  Thread can wait until event is set

Pseudo Code: event = threading.Event() #consumer thread has to wait until event is set event.wait() #producer thread can set or clear event event.set() event.clear()

Demo Program-1: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17)

from threading import * import time def producer(): time.sleep(5) print("Producer thread producing items:") print("Producer thread giving notification by setting event") event.set() def consumer(): print("Consumer thread is waiting for updation") event.wait() print("Consumer thread got notification and consuming items") event=Event() t1=Thread(target=producer) t2=Thread(target=consumer) t1.start() t2.start()

Output: Consumer thread is waiting for updation Producer thread producing items Producer thread giving notification by setting event Consumer thread got notification and consuming items

Demo Program-2: 1) from threading import * 2) import time 3) def trafficpolice(): 4) while True: 5) time.sleep(10) 6) print("Traffic Police Giving GREEN Signal")

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23) 24) 25) 26)

event.set() time.sleep(20) print("Traffic Police Giving RED Signal") event.clear() def driver(): num=0 while True: print("Drivers waiting for GREEN Signal") event.wait() print("Traffic Signal is GREEN. Vehicles can move") while event.isSet(): num=num+1 print("Vehicle No:",num,"Crossing the Signal") time.sleep(2) print("Traffic Signal is RED. Drivers have to wait") event=Event() t1=Thread(target=trafficpolice) t2=Thread(target=driver) t1.start() t2.start()

In the above program driver thread has to wait until Trafficpolice thread sets event.ie until giving GREEN signal.Once Traffic police thread sets event(giving GREEN signal),vehicles can cross the signal.Once traffic police thread clears event (giving RED Signal)then the driver thread has to wait.

Interthread communication by using Condition Object: Condition is the more advanced version of Event object for interthread communication.A condition represents some kind of state change in the application like producing item or consuming item. Threads can wait for that condition and threads can be notified once condition happend.i.e Condition object allows one or more threads to wait until notified by another thread. Condition is always associated with a lock (ReentrantLock). A condition has acquire() and release() methods that call the corresponding methods of the associated lock. We can create Condition object as follows condition = threading.Condition()

Methods of Condition: 1. acquire()  To acquire Condition object before producing or consuming items.i.e thread acquiring internal lock. 2. release()  To release Condition object after producing or consuming items. i.e thread releases internal lock 3. wait()|wait(time)  To wait until getting Notification or time expired

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

4. notify()  To give notification for one waiting thread 5. notifyAll()  To give notification for all waiting threads

Case Study: The producing thread needs to acquire the Condition before producing item to the resource and notifying the consumers. #Producer Thread . generate item.. condition.acquire() . add item to the resource. condition.notify()#signal that a new item is available(notifyAll()) condition.release() The Consumer must acquire the Condition and then it can consume items from the resource #Consumer Thread condition.acquire() condition.wait() consume item condition.release()

Demo Program-1: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20)

from threading import * def consume(c): c.acquire() print("Consumer waiting for updation") c.wait() print("Consumer got notification & consuming the item") c.release() def produce(c): c.acquire() print("Producer Producing Items") print("Producer giving Notification") c.notify() c.release() c=Condition() t1=Thread(target=consume,args=(c,)) t2=Thread(target=produce,args=(c,)) t1.start() t2.start()

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Output: Consumer waiting for updation Producer Producing Items Producer giving Notification Consumer got notification & consuming the item

Demo Program-2: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23) 24) 25) 26) 27) 28) 29)

from threading import * import time import random items=[] def produce(c): while True: c.acquire() item=random.randint(1,100) print("Producer Producing Item:",item) items.append(item) print("Producer giving Notification") c.notify() c.release() time.sleep(5) def consume(c): while True: c.acquire() print("Consumer waiting for updation") c.wait() print("Consumer consumed the item",items.pop()) c.release() time.sleep(5) c=Condition() t1=Thread(target=consume,args=(c,)) t2=Thread(target=produce,args=(c,)) t1.start() t2.start()

Output: Consumer waiting for updation Producer Producing Item: 49 Producer giving Notification Consumer consumed the item 49 . In the above program Consumer thread expecting updation and hence it is responsible to call wait() method on Condition object. Producer thread performing updation and hence it is responsible to call notify() or notifyAll() on Condition object.

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Interthread communication by using Queue: Queues Concept is the most enhanced Mechanism for interthread communication and to share data between threads. Queue internally has Condition and that Condition has Lock.Hence whenever we are using Queue we are not required to worry about Synchronization. If we want to use Queues first we should import queue module. import queue

We can create Queue object as follows q = queue.Queue()

Important Methods of Queue: 1. put(): Put an item into the queue. 2. get(): Remove and return an item from the queue. Producer Thread uses put() method to insert data in the queue. Internally this method has logic to acquire the lock before inserting data into queue. After inserting data lock will be released automatically. put() method also checks whether the queue is full or not and if queue is full then the Producer thread will entered in to waiting state by calling wait() method internally.

Consumer Thread uses get() method to remove and get data from the queue. Internally this method has logic to acquire the lock before removing data from the queue.Once removal completed then the lock will be released automatically. If the queue is empty then consumer thread will entered into waiting state by calling wait() method internally.Once queue updated with data then the thread will be notified automatically.

Note: The queue module takes care of locking for us which is a great advantage.

from threading import * import time import random import queue def produce(q):

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22)

while True: item=random.randint(1,100) print("Producer Producing Item:",item) q.put(item) print("Producer giving Notification") time.sleep(5) def consume(q): while True: print("Consumer waiting for updation") print("Consumer consumed the item:",q.get()) time.sleep(5) q=queue.Queue() t1=Thread(target=consume,args=(q,)) t2=Thread(target=produce,args=(q,)) t1.start() t2.start()

Output: Consumer waiting for updation Producer Producing Item: 58 Producer giving Notification Consumer consumed the item: 58

Types of Queues: Python Supports 3 Types of Queues.

1. FIFO Queue: q = queue.Queue() This is Default Behaviour. In which order we put items in the queue, in the same order the items will come out (FIFO-First In First Out).

Eg: 1) 2) 3) 4) 5) 6) 7) 8)

import queue q=queue.Queue() q.put(10) q.put(5) q.put(20) q.put(15) while not q.empty(): print(q.get(),end=' ')

Output: 10 5 20 15

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

2. LIFO Queue: The removal will be happend in the reverse order of insertion(Last In First Out)

Eg: 1) 2) 3) 4) 5) 6) 7) 8)

import queue q=queue.LifoQueue() q.put(10) q.put(5) q.put(20) q.put(15) while not q.empty(): print(q.get(),end=' ')

Output: 15 20 5 10

3. Priority Queue: The elements will be inserted based on some priority order. 1) 2) 3) 4) 5) 6) 7) 8)

import queue q=queue.PriorityQueue() q.put(10) q.put(5) q.put(20) q.put(15) while not q.empty(): print(q.get(),end=' ')

Output: 5 10 15 20 Eg 2: If the data is non-numeric, then we have to provide our data in the form of tuple. (x,y) x is priority y is our element 1) 2) 3) 4) 5) 6) 7) 8)

import queue q=queue.PriorityQueue() q.put((1,"AAA")) q.put((3,"CCC")) q.put((2,"BBB")) q.put((4,"DDD")) while not q.empty(): print(q.get()[1],end=' ')

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Output: AAA BBB CCC DDD

Good Programming Practices with usage of Locks: Case-1: It is highly recommended to write code of releasing locks inside finally block.The advantage is lock will be released always whether exception raised or not raised and whether handled or not handled. l=threading.Lock() l.acquire() try: perform required safe operations finally: l.release()

Demo Program: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19)

from threading import * import time l=Lock() def wish(name): l.acquire() try: for i in range(10): print("Good Evening:",end='') time.sleep(2) print(name) finally: l.release() t1=Thread(target=wish,args=("Dhoni",)) t2=Thread(target=wish,args=("Yuvraj",)) t3=Thread(target=wish,args=("Kohli",)) t1.start() t2.start() t3.start()

Case-2: It is highly recommended to acquire lock by using with statement. The main advantage of with statement is the lock will be released automatically once control reaches end of with block and we are not required to release explicitly. This is exactly same as usage of with statement for files.

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Example for File: with open('demo.txt','w') as f: f.write("Hello. ")

Example for Lock: lock=threading.Lock() with lock: perform required safe operations lock will be released automatically

Demo Program: 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15)

from threading import * import time lock=Lock() def wish(name): with lock: for i in range(10): print("Good Evening:",end='') time.sleep(2) print(name) t1=Thread(target=wish,args=("Dhoni",)) t2=Thread(target=wish,args=("Yuvraj",)) t3=Thread(target=wish,args=("Kohli",)) t1.start() t2.start() t3.start()

Q. What is the advantage of using with statement to acquire a lock in threading? Lock will be released automatically once control reaches end of with block and We are not required to release explicitly.

Note: We can use with statement in multithreading for the following cases: 1. Lock 2. RLock 3. Semaphore 4. Condition

DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Python Database Programming Storage Areas As the Part of our Applications, we required to store our Data like Customers Information, Billing Information, Calls Information etc.. To store this Data, we required Storage Areas. There are 2 types of Storage Areas. 1) Temporary Storage Areas 2) Permanent Storage Areas

1.Temporary Storage Areas: These are the Memory Areas where Data will be stored temporarily. Eg: Python objects like List, Tuple, Dictionary. Once Python program completes its execution then these objects will be destroyed automatically and data will be lost.

2. Permanent Storage Areas: Also known as Persistent Storage Areas. Here we can store Data permanently. Eg: File Systems, Databases, Data warehouses, Big Data Technologies etc

File Systems: File Systems can be provided by Local operating System. File Systems are best suitable to store very less Amount of Information.

Limitations: 1) We cannot store huge Amount of Information. 2) There is no Query Language support and hence operations will become very complex. 3) There is no Security for Data. 4) There is no Mechanism to prevent duplicate Data. Hence there may be a chance of Data Inconsistency Problems. To overcome the above Problems of File Systems, we should go for Databases.

Databases: 1) We can store Huge Amount of Information in the Databases.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

2) Query Language Support is available for every Database and hence we can perform Database Operations very easily. 3) To access Data present in the Database, compulsory username and pwd must be required. Hence Data is secured. 4) Inside Database Data will be stored in the form of Tables. While developing Database Table Schemas, Database Admin follow various Normalization Techniques and can implement various Constraints like Unique Key Constrains, Primary Key Constraints etc which prevent Data Duplication. Hence there is no chance of Data Inconsistency Problems.

Limitations of Databases: 1) Database cannot hold very Huge Amount of Information like Terabytes of Data. 2) Database can provide support only for Structured Data (Tabular Data OR Relational Data) and cannot provide support for Semi Structured Data (like XML Files) and Unstructured Data (like Video Files, Audio Files, Images etc) To overcome these Problems we should go for more Advanced Storage Areas like Big Data Technologies, Data warehouses etc.

Python Database Programming: Sometimes as the part of Programming requirement we have to connect to the database and we have to perform several operations like creating tables, inserting data,updating data,deleting data,selecting data etc. We can use SQL Language to talk to the database and we can use Python to send those SQL commands to the database. Python provides inbuilt support for several databases like Oracle, MySql, SqlServer, GadFly, sqlite, etc. Python has seperate module for each database. Eg: cx_Oralce module for communicating with Oracle database pymssql module for communicating with Microsoft Sql Server

Standard Steps for Python database Programming: 1. Import database specific module Eg: import cx_Oracle 2. Establish Connection between Python Program and database. We can create this Connection object by using connect() function of the module. con = cx_Oracle.connect(datbase information)

Eg: con=cx_Oracle.connect('scott/tiger@localhost') 3. To execute our sql queries and to hold results some special object is required, which is nothing but Cursor object. We can create Cursor object by using cursor() method.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

cursor=con.cursor() 4. Execute SQL Queries By using Cursor object. For this we can use the following methods i) execute(sqlquery)  To execute a single sql query ii) executescript(sqlqueries)  To execute a string of sql queries seperated by semi-colon ';' iii) executemany()  To execute a Parameterized query

Eg: cursor.execute("select * from employees") 5. commit or rollback changes based on our requirement in the case of DML Queries(insert|update|delete) commit()  Saves the changes to the database rollback()  rolls all temporary changes back 6. Fetch the result from the Cursor object in the case of select queries fetchone()  To fetch only one row fetchall()  To fetch all rows and it returns a list of rows fecthmany(n)  To fetch first n rows

Eg 1: data =cursor.fetchone() print(data)

Eg 2: data=cursor.fetchall() for row in data: print(row) 7. close the resources After completing our operations it is highly recommended to close the resources in the reverse order of their opening by using close() methods. cursor.close() con.close()

Note: The following is the list of all important methods which can be used for python database programming. connect() cursor() execute() executescript() executemany() commit() rollback() fetchone() fetchall() fetchmany(n)

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

fetch close() These methods won't be changed from database to database and same for all databases.

Working with Oracle Database: From Python Program if we want to communicate with any database,some translator must be required to translate Python calls into Database specific calls and Database specific calls into Python calls.This translator is nothing but Driver/Connector. Diagram For Oracle database the name of driver needed is cx_Oracle. cx_Oracle is a Python extension module that enables access to Oracle Database.It can be used for both Python2 and Python3. It can work with any version of Oracle database like 9,10,11 and 12.

Installing cx_Oracle: From Normal Command Prompt (But not from Python console)execute the following command D:\python_classes>pip install cx_Oracle Collecting cx_Oracle Downloading cx_Oracle-6.0.2-cp36-cp36m-win32.whl (100kB) 100% |-----------| 102kB 256kB/s Installing collected packages: cx-Oracle Successfully installed cx-Oracle-6.0.2

How to Test Installation: From python console execute the following command: >>> help("modules") In the output we can see cx_Oracle . _multiprocessing crypt ntpath _opcode csv nturl2path _operator csvr numbers _osx_support csvw opcode _overlapped ctypes operator _pickle curses optparse _pydecimal custexcept os _pyio cx_Oracle parser _random data pathlib _sha1 datetime pdb

timeit tkinter token tokenize trace traceback tracemalloc try tty turtle

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

_sha256 dbm pick turtledemo _sha3 decimal pickle types _sha512 demo pickletools typing _signal difflib pip unicodedata _sitebuiltins dis pipes unittest _socket distutils pkg_resources unpick _sqlite3 doctest pkgutil update _sre dummy_threading platform urllib _ssl durgamath plistlib uu _stat easy_install polymorph uuid .

App1: Program to connect with Oracle database and print its version. 1) 2) 3) 4)

import cx_Oracle con=cx_Oracle.connect('scott/tiger@localhost') print(con.version) con.close()

Output: D:\python_classes>py db1.py 11.2.0.2.0

App2: Write a Program to create employees table in the oracle database : employees(eno,ename,esal,eaddr) 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15)

import cx_Oracle try: con=cx_Oracle.connect('scott/tiger@localhost') cursor=con.cursor() cursor.execute("create table employees(eno number,ename varchar2(10),esal number(10,2),eaddr varchar2(10))") print("Table created successfully") except cx_Oracle.DatabaseError as e: if con: con.rollback() print("There is a problem with sql",e) finally: if cursor: cursor.close() if con: con.close()

App3: Write a program to drop employees table from oracle database? 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15)

import cx_Oracle try: con=cx_Oracle.connect('scott/tiger@localhost') cursor=con.cursor() cursor.execute("drop table employees") print("Table dropped successfully") except cx_Oracle.DatabaseError as e: if con: con.rollback() print("There is a problem with sql",e) finally: if cursor: cursor.close() if con: con.close()

App3: Write a program to insert a single row in the employees table.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16)

import cx_Oracle try: con=cx_Oracle.connect('scott/tiger@localhost') cursor=con.cursor() cursor.execute("insert into employees values(100,'Durga',1000,'Hyd')") con.commit() print("Record Inserted Successfully") except cx_Oracle.DatabaseError as e: if con: con.rollback() print("There is a problem with sql",e) finally: if cursor: cursor.close() if con: con.close()

Note: While performing DML Operations (insert|update|delte), compulsory we have to use commit() method,then only the results will be reflected in the database.

App4: Write a program to insert multiple rows in the employees table by using executemany() method. 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20)

import cx_Oracle try: con=cx_Oracle.connect('scott/tiger@localhost') cursor=con.cursor() sql="insert into employees values(:eno,:ename,:esal,:eaddr)" records=[(200,'Sunny',2000,'Mumbai'), (300,'Chinny',3000,'Hyd'), (400,'Bunny',4000,'Hyd')] cursor.executemany(sql,records) con.commit() print("Records Inserted Successfully") except cx_Oracle.DatabaseError as e: if con: con.rollback() print("There is a problem with sql",e) finally: if cursor: cursor.close() if con: con.close()

App5: Write a program to insert multiple rows in the employees table with dynamic input from the keyboard? 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23) 24) 25)

import cx_Oracle try: con=cx_Oracle.connect('scott/tiger@localhost') cursor=con.cursor() while True: eno=int(input("Enter Employee Number:")) ename=input("Enter Employee Name:") esal=float(input("Enter Employee Salary:")) eaddr=input("Enter Employee Address:") sql="insert into employees values(%d,'%s',%f,'%s')" cursor.execute(sql %(eno,ename,esal,eaddr)) print("Record Inserted Successfully") option=input("Do you want to insert one more record[Yes|No] :") if option=="No": con.commit() break except cx_Oracle.DatabaseError as e: if con: con.rollback() print("There is a problem with sql :",e) finally: if cursor: cursor.close() if con: con.close()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

App6: Write a program to update employee salaries with increment for the certain range with dynamic input. Eg: Increment all employee salaries by 500 whose salary 5000 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18)

import cx_Oracle try: con=cx_Oracle.connect('scott/tiger@localhost') cursor=con.cursor() cutoffsalary=float(input("Enter CutOff Salary:")) sql cursor.execute(sql %(cutoffsalary)) print("Records Deleted Successfully") con.commit() except cx_Oracle.DatabaseError as e: if con: con.rollback() print("There is a problem with sql :",e) finally: if cursor: cursor.close() if con: con.close()

App8: Write a program to select all employees info by using fetchone() method? 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18)

import cx_Oracle try: con=cx_Oracle.connect('scott/tiger@localhost') cursor=con.cursor() cursor.execute("select * from employees") row=cursor.fetchone() while row is not None: print(row) row=cursor.fetchone() except cx_Oracle.DatabaseError as e: if con: con.rollback() print("There is a problem with sql :",e) finally: if cursor: cursor.close() if con: con.close()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

App9: Write a program to select all employees info by using fetchall() method? 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22)

import cx_Oracle try: con=cx_Oracle.connect('scott/tiger@localhost') cursor=con.cursor() cursor.execute("select * from employees") data=cursor.fetchall() for row in data: print("Employee Number:",row[0]) print("Employee Name:",row[1]) print("Employee Salary:",row[2]) print("Employee Address:",row[3]) print() print() except cx_Oracle.DatabaseError as e: if con: con.rollback() print("There is a problem with sql :",e) finally: if cursor: cursor.close() if con: con.close()

App10: Write a program to select employees info by using fetchmany() method and the required number of rows will be provided as dynamic input? 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18)

import cx_Oracle try: con=cx_Oracle.connect('scott/tiger@localhost') cursor=con.cursor() cursor.execute("select * from employees") n=int(input("Enter the number of required rows:")) data=cursor.fetchmany(n) for row in data: print(row) except cx_Oracle.DatabaseError as e: if con: con.rollback() print("There is a problem with sql :",e) finally: if cursor: cursor.close() if con: con.close()

Output: D:\python_classes>py test.py Enter the number of required rows:3 (100, 'Durga', 1500.0, 'Hyd') (200, 'Sunny', 2500.0, 'Mumbai') (300, 'Chinny', 3500.0, 'Hyd') D:\python_classes>py test.py Enter the number of required rows:4 (100, 'Durga', 1500.0, 'Hyd') (200, 'Sunny', 2500.0, 'Mumbai') (300, 'Chinny', 3500.0, 'Hyd') (400, 'Bunny', 4500.0, 'Hyd')

Working with Mysql database: Current version: 5.7.19 Vendor: SUN Micro Systems/Oracle Corporation

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Open Source and Freeware Default Port: 3306 Default user: root

Note: In MySQL, everything we have to work with our own databases, which are also known as Logical Databases. The following are 4 default databases available in mysql. 1. information_schema 2. mysql 3. performance_schema 4. test Diagram

In the above diagram only one physical database is available and 4 logical databases are available.

Commonly used commands in MySql: 1. To know available databases: mysql> show databases;

2. To create our own logical database mysql> create database durgadb;

3. To drop our own database: mysql> drop database durgadb;

4. To use a particular logical database mysql> use durgadb;

mysql> connect durgadb;

5. To create a table: create table employees(eno int(5) primary key,ename varchar(10),esal double(10,2),eaddr varchar(10));

6. To insert data: insert into employees values(100,'Durga',1000,'Hyd'); insert into employees values(200,'Ravi',2000,'Mumbai'); In MySQL instead of single quotes we can use double quotes also.

Driver/Connector Information: From Python program if we want to communicates with MySql database,compulsory some translator is required to convert python specific calls into mysql database specific calls and mysql database specific calls into python specific calls. This translator is nothing but Driver or Connector.

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Diagram We have to download connector seperately from mysql database. https://dev.mysql.com/downloads/connector/python/2.1.html

How to check installation: From python console we have to use help("modules") In the list of modules,compulsory mysql should be there.

Note: In the case of Python3.4 we have to set PATH and PYTHONPATH explicitly PATH=C:\Python34 PYTHONPATH=C:\Python34\Lib\site-packages

Q. Write a Program to create table,insert data and display data by using mysql database. 1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23) 24) 25) 26) 27) 28) 29) 30) 31) 32) 33)

import mysql.connector try: con=mysql.connector.connect(host='localhost',database='durgadb',user='root',password='root') cursor=con.cursor() cursor.execute("create table employees(eno int(5) primary key,ename varchar(10),esal double(10,2),eaddr varchar( 10))") print("Table Created. ") sql = "insert into employees(eno, ename, esal, eaddr) VALUES(%s, %s, %s, %s)" records=[(100,'Sachin',1000,'Mumbai'), (200,'Dhoni',2000,'Ranchi'), (300,'Kohli',3000,'Delhi')] cursor.executemany(sql,records) con.commit() print("Records Inserted Successfully. ") cursor.execute("select * from employees") data=cursor.fetchall() for row in data: print("Employee Number:",row[0]) print("Employee Name:",row[1]) print("Employee Salary:",row[2]) print("Employee Address:",row[3]) print() print() except mysql.connector.DatabaseError as e: if con: con.rollback() print("There is a problem with sql :",e) finally: if cursor: cursor.close() if con: con.close()

Q. Write a Program to copy data present in employees table of mysql database into Oracle database. 1) 2) 3) 4)

import mysql.connector import cx_Oracle try: con=mysql.connector.connect(host='localhost',database='durgadb',user='root',password='root')

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

5) 6) 7) 8) 9) 10) 11) 12) 13) 14) 15) 16) 17) 18) 19) 20) 21) 22) 23) 24) 25) 26) 27) 28) 29) 30) 31) 32) 33) 34) 35) 36) 37)

cursor=con.cursor() cursor.execute("select * from employees") data=cursor.fetchall() list=[] for row in data: t=(row[0],row[1],row[2],row[3]) list.append(t) except mysql.connector.DatabaseError as e: if con: con.rollback() print("There is a problem with MySql :",e) finally: if cursor: cursor.close() if con: con.close() try: con=cx_Oracle.connect('scott/tiger@localhost') cursor=con.cursor() sql="insert into employees values(:eno,:ename,:esal,:eaddr)" cursor.executemany(sql,list) con.commit() print("Records Copied from MySQL Database to Oracle Database except cx_Oracle.DatabaseError as e: if con: con.rollback() print("There is a problem with sql",e) finally: if cursor: cursor.close() if con: con.close()

https://dev.mysql.com/downloads/connector/python/2.1.html 1) 2) 3) 4) 5)

create table employees(eno int(5) primary key,ename varchar(10),esal double(10,2),eaddr varchar(10));

insert into employees values(100,'Durga',1000,'Hyd'); insert into employees values(200,'Ravi',2000,'Mumbai'); insert into employees values(300,'Shiva',3000,'Hyd');

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Pattern-2: 1111111111 2222222222 3333333333 4444444444 5555555555 6666666666 7777777777 8888888888 9999999999 10 10 10 10 10 10 10 10 10 10 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+1): 4) print(i,end=" ") 5) print()

Pattern-3: 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10

1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+1): 4) print(j,end=" ") 5) print()

Pattern-4: AAAAAAAAAA BBBBBBBBBB CCCCCCCCCC DDDDDDDDDD EEEEEEEEEE FFFFFFFFFF GGGGGGGGGG HHHHHHHHHH IIIIIIIIII JJJJJJJJJJ 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+1): 4) print(chr(64+i),end=" ") 5) print()

Pattern-5: ABCDEFGHIJ ABCDEFGHIJ ABCDEFGHIJ ABCDEFGHIJ ABCDEFGHIJ ABCDEFGHIJ ABCDEFGHIJ ABCDEFGHIJ ABCDEFGHIJ ABCDEFGHIJ

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+1): 4) print(chr(64+j),end=" ") 5) print()

Pattern-6: 10 10 10 10 10 10 10 10 10 10 9999999999 8888888888 7777777777 6666666666 5555555555 4444444444 3333333333 2222222222 1111111111 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+1): 4) print(n+1-i,end=" ") 5) print()

Pattern-6: 10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+1): 4) print(n+1-j,end=" ") 5) print()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Pattern-7: JJJJJJJJJJ IIIIIIIIII HHHHHHHHHH GGGGGGGGGG FFFFFFFFFF EEEEEEEEEE DDDDDDDDDD CCCCCCCCCC BBBBBBBBBB AAAAAAAAAA 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+1): 4) print(chr(65+n-i),end=" ") 5) print()

Pattern-8: JIHGFEDCBA JIHGFEDCBA JIHGFEDCBA JIHGFEDCBA JIHGFEDCBA JIHGFEDCBA JIHGFEDCBA JIHGFEDCBA JIHGFEDCBA JIHGFEDCBA 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+1): 4) print(chr(65+n-j),end=" ") 5) print()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Code - 1: 1) n=int(input("Enter the number of rows:")) 2) for i in range(1,n+1): 3) for j in range(1,i+1): 4) print("*",end=" ") 5) print()

Code - 2: 1) n=int(input("Enter the number of rows:")) 2) for i in range(1,n+1): 3) print("* "*i)

Pattern-10: 1 22 333 4444 55555 666666 7777777 88888888 999999999 10 10 10 10 10 10 10 10 10 10 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,i+1): 4) print(i,end=" ") 5) print()

Pattern-11: 1 12 123 1234 12345 123456 1234567 12345678

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

123456789 1 2 3 4 5 6 7 8 9 10 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,i+1): 4) print(j,end=" ") 5) print()

Pattern-12: A BB CCC DDDD EEEEE FFFFFF GGGGGGG HHHHHHHH IIIIIIIII JJJJJJJJJJ 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,i+1): 4) print(chr(64+i),end=" ") 5) print()

Pattern-13: A AB ABC ABCD ABCDE ABCDEF ABCDEFG ABCDEFGH ABCDEFGHI ABCDEFGHIJ 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,i+1): 4) print(chr(64+j),end=" ") 5) print()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

 Squares  Right Angled Triangle  Reverse of Right Angled Triangle

Pattern-14: ********** ********* ******** ******* ****** ***** **** *** ** * 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+2-i): 4) print("*",end=" ") 5) print()

Pattern-15: 1111111111 222222222 33333333 4444444 555555 66666 7777 888 99 10 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+2-i): 4) print(i,end=" ") 5) print()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Pattern-16: 1 2 3 4 5 6 7 8 9 10 123456789 12345678 1234567 123456 12345 1234 123 12 1 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+2-i): 4) print(j,end=" ") 5) print()

Pattern-17: AAAAAAAAAA BBBBBBBBB CCCCCCCC DDDDDDD EEEEEE FFFFF GGGG HHH II J 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+2-i): 4) print(chr(64+i),end=" ") 5) print()

Pattern-18: ABCDEFGHIJ ABCDEFGHI ABCDEFGH ABCDEFG ABCDEF ABCDE ABCD

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

ABC AB A 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+2-i): 4) print(chr(64+j),end=" ") 5) print()

Pattern-19: 10 10 10 10 10 10 10 10 10 10 999999999 88888888 7777777 666666 55555 4444 333 22 1 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+2-i): 4) print(n+1-i,end=" ") 5) print()

Pattern-20: 10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 10 9 8 7 6 5 4 3 10 9 8 7 6 5 4 10 9 8 7 6 5 10 9 8 7 6 10 9 8 7 10 9 8 10 9 10 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+2-i): 4) print(n+1-j,end=" ") 5) print()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Pattern-21: JJJJJJJJJJ IIIIIIIII HHHHHHHH GGGGGGG FFFFFF EEEEE DDDD CCC BB A 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+2-i): 4) print(chr(65+n-i),end=" ") 5) print()

Pattern-22: JIHGFEDCBA JIHGFEDCB JIHGFEDC JIHGFED JIHGFE JIHGF JIHG JIH JI J 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) for j in range(1,n+2-i): 4) print(chr(65+n-j),end=" ") 5) print()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

******** ********* ********** 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),"*"*i,end=" ") 4) print()

Pattern-24: * ** *** **** ***** ****** ******* ******** ********* ********** 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),end="") 4) for j in range(1,i+1): 5) print("*",end=" ") 6) print()

Pattern-25: 1 22 333 4444 55555 666666 7777777 88888888

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

999999999 10 10 10 10 10 10 10 10 10 10 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),(str(i)+" ")*i) 4) print()

Pattern-26: 1 12 123 1234 12345 123456 1234567 12345678 123456789 1 2 3 4 5 6 7 8 9 10 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),end="") 4) for j in range(1,i+1): 5) print(j,end=" ") 6) print()

Pattern-27: A BB CCC DDDD EEEEE FFFFFF GGGGGGG HHHHHHHH

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),(chr(64+i)+" ")*i) 4) print()

Pattern-28: A AB ABC ABCD ABCDE ABCDEF ABCDEFG ABCDEFGH ABCDEFGHI ABCDEFGHIJ 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),end="") 4) for j in range(1,i+1): 5) print(chr(64+j),end=" ") 6) print()

Pattern-29: ***** **** *** ** * 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(i-1),"* "*(n+1-i))

Pattern-30: 55555 4444 333 22 1

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(i-1),(str(n+1-i)+" ")*(n+1-i))

Pattern-31: 12345 1234 123 12 1 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(i-1),end="") 4) for j in range(1,n+2-i): 5) print(j,end=" ") 6) print()

Pattern-32: EEEEE DDDD CCC BB A 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(i-1),(str(chr(65+n-i))+" ")*(n+1-i))

Pattern-33: ABCDE ABCD ABC AB A 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(i-1),end="") 4) for j in range(65,66+n-i): 5) print(chr(j),end=" ") 6) print()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Pattern-34: * *** ***** ******* ********* 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),"* "*(2*i-1))

Pattern-35: 1 222 33333 4444444 555555555 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),(str(i)+" ")*(2*i-1))

Pattern-36: A BBB CCCCC DDDDDDD EEEEEEEEE 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),(str(chr(64+i)+" "))*(2*i-1))

Pattern-37: A CCC EEEEE GGGGGGG IIIIIIIII

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),(str(chr(64+2*i-1)+" "))*(2*i-1))

Pattern-38: 1 123 12345 1234567 123456789 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),end="") 4) for j in range(1,2*i): 5) print(j,end=" ") 6) print()

Pattern-39: 1 321 54321 7654321 987654321 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),end="") 4) for j in range(2*i-1,0,-1): 5) print(j,end=" ") 6) print()

Pattern-40: A ABC ABCDE ABCDEFG ABCDEFGHI 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),end="") 4) for j in range(65,65+2*i-1):

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Pattern-41: A CBA EDCBA GFEDCBA IHGFEDCBA 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),end="") 4) for j in range(65+2*i-2,64,-1): 5) print(chr(j),end=" ") 6) print()

Pattern-42: 0 101 21012 3210123 432101234 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),end="") 4) for j in range(1,i): 5) print(i-j,end=" ") 6) for k in range(0,i): 7) print(k,end=" ") 8) print()

Pattern-43: A BAB CBABC DCBABCD EDCBABCDE 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),end="")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

for j in range(1,i): print(chr(i-j+65),end=" ") for k in range(0,i): print(chr(k+65),end=" ") print()

Pattern-44: 1 121 12321 1234321 123454321 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),end="") 4) for j in range(1,i+1): 5) print(j,end=" ") 6) for k in range(i-1,0,-1): 7) print(k,end=" ") 8) print()

Pattern-45: A ABA ABCAB ABCDABC ABCDEABCD 1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1): 3) print(" "*(n-i),end="") 4) for j in range(1,i+1): 5) print(chr(64+j),end=" ") 6) for k in range(1,i): 7) print(chr(64+k),end=" ") 8) print()

Pattern-46: 1) n=int(input("Enter a number:")) 2) for i in range(1,n+1): 3) print(" "*(n-i),end="") 4) for j in range(1,i+1):

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

5 54 543 5432 54321

Pattern-47: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(i-1),end="") 4) for j in range(1,num+2-i): 5) print("*",end=" ") 6) for k in range(1,num+1-i): 7) print("*",end=" ") 8) print() ********* ******* ***** *** *

Pattern-48: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(i-1),end="") 4) for j in range(0,num+1-i): 5) print(num+1-i,end=" ") 6) for k in range(1,num+1-i): 7) print(num+1-i,end=" ") 8) print() 555555555 4444444 33333 222 1

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Pattern-49: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(i-1),end="") 4) for j in range(0,num+1-i): 5) print(2*num+1-2*i,end=" ") 6) for k in range(1,num+1-i): 7) print(2*num+1-2*i,end=" ") 8) print() 999999999 7777777 55555 333 1

Pattern-50: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(i-1),end="") 4) for j in range(1,num+2-i): 5) print(j,end=" ") 6) for k in range(2,num+2-i): 7) print(num+k-i,end=" ") 8) print() 1234567 12345 123 1

Pattern-51: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(i-1),end="") 4) for j in range(1,num+2-i): 5) print(chr(65+num-i),end=" ") 6) for k in range(2,num+2-i): 7) print(chr(65+num-i),end=" ") 8) print()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

EEEEEEEEE DDDDDDD CCCCC BBB A

Pattern-52: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(i-1),end="") 4) for j in range(1,num+2-i): 5) print(chr(65+2*num-2*i),end=" ") 6) for k in range(2,num+2-i): 7) print(chr(65+2*num-2*i),end=" ") 8) print() I I I I I I I I I G G G G G G G E E E E E C C C A

Pattern-53: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(i-1),end="") 4) for j in range(1,num+2-i): 5) print(chr(64+j),end=" ") 6) for k in range(2,num+2-i): 7) print(chr(68+k-i),end=" ") 8) print() ABCDEFG ABCDE ABC A

Pattern-54: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(1,i+1): 5) print(j,end=" ")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

6) print() 7) for k in range(1,num): 8) print(" "*k,end="") 9) for l in range(1,num+1-k): 10) print(l,end=" ") 11) print() 1 12 123 1234 12345 1234 123 12 1

Pattern-55: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(1,i+1): 5) print("*",end=" ") 6) print() 7) for k in range(1,num): 8) print(" "*k,end="") 9) for l in range(1,num+1-k): 10) print("*",end=" ") 11) print() * ** *** **** ***** **** *** ** *

Pattern-56: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(1,i+1):

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

5) print(num-j,end=" ") 6) print() 7) for k in range(1,num): 8) print(" "*k,end="") 9) for l in range(1,num+1-k): 10) print(num-l,end=" ") 11) print() 4 43 432 4321 43210 4321 432 43 4

Pattern-57: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(0,i): 5) print(num+j-i,end=" ") 6) print() 7) for k in range(1,num): 8) print(" "*k,end="") 9) for l in range(1,num+1-k): 10) print(l+k-1,end=" ") 11) print() 3 23 123 0123 123 23 3

Pattern-58: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(0,i): 5) print(chr(65+num+j-i),end=" ")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

6) print() 7) for k in range(1,num): 8) print(" "*k,end="") 9) for l in range(0,num-k): 10) print(chr(65+k+l),end=" ") 11) print() E DE CDE BCDE ABCDE BCDE CDE DE E

Pattern-59: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) for j in range(1,i+1): 4) print("*",end=" ") 5) print() 6) for a in range(1,num+1): 7) for k in range(1,num+1-a): 8) print("*",end=" ") 9) print() * ** *** **** ***** **** *** ** *

Pattern-60: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) for j in range(1,i+1): 4) print(num-j,end=" ") 5) print() 6) for a in range(1,num+1): 7) for k in range(1,num+1-a):

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

4 43 432 4321 43210 4321 432 43 4

Pattern-61: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) for j in range(1,i+1): 4) print(num-i+j-1,end=" ") 5) print() 6) for a in range(1,num+1): 7) for k in range(0,num-a): 8) print(k+a,end=" ") 9) print() 4 34 234 1234 01234 1234 234 34 4

Pattern-62: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) for j in range(1,i+1): 4) print(chr(65+num-i),end=" ") 5) print() 6) for a in range(1,num+1): 7) for k in range(0,num-a): 8) print(chr(65+a),end=" ") 9) print()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

E DD CCC BBBB AAAAA BBBB CCC DD E

Pattern-63: 1) for i in range(1,num+1): 2) for j in range(1,i+1): 3) print(chr(65+num-j),end=" ") 4) print() 5) for a in range(1,num+1): 6) for k in range(num-a,0,-1): 7) print(chr(64+k+a),end=" ") 8) print() 9) num=int(input("Enter a number:")) E ED EDC EDCB EDCBA EDCB EDC ED E

Pattern-64: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) for j in range(1,i+1): 4) print(chr(64+num-i+j),end=" ") 5) print() 6) for a in range(1,num+1): 7) for k in range(1,num-a+1): 8) print(chr(64+k+a),end=" ") 9) print()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

E DE CDE BCDE ABCDE BCDE CDE DE E

Pattern-65: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(1,i+1): 5) print("*",end=" ") 6) print()

Pattern-66: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(1,i+1): 5) print(i,end=" ") 6) print() 1 22 333 4444 55555

Pattern-67: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

for j in range(1,1+i): print(j,end=" ") print()

1 12 123 1234 12345

Pattern-68: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(1,1+i): 5) print(chr(64+i),end=" ") 6) print() A BB CCC DDDD EEEEE

Pattern-69: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(1,1+i): 5) print(chr(64+j),end=" ") 6) print() A AB ABC ABCD ABCDE

Pattern-70: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(i-1),end="") 4) for j in range(1,num+2-i):

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Pattern-71: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(i-1),end="") 4) for j in range(1,num+2-i): 5) print(num-i+1,end=" ") 6) print() 55555 4444 333 22 1

Pattern-72: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(i-1),end="") 4) for j in range(1,num+2-i): 5) print(num+2-i-j,end=" ") 6) print() 54321 4321 321 21 1

Pattern-73: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(i-1),end="") 4) for j in range(1,num+2-i): 5) print(chr(65+num-i),end=" ") 6) print()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

EEEEE DDDD CCC BB A

Pattern-74: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(i-1),end="") 4) for j in range(1,num+2-i): 5) print(chr(65+num+1-i-j),end=" ") 6) print() EDCBA DCBA CBA BA A

Pattern-75: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(i-1),end="") 4) for j in range(1,num+2-i): 5) print(chr(64+j),end=" ") 6) print() ABCDE ABCD ABC AB A

Pattern-76: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(1,i+1): 5) print("*",end=" ") 6) print() 7) for p in range(1,num): 8) print(" "*p,end="")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

for q in range(1,num+1-p): print("*",end=" ") print()

Pattern-77: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(1,i+1): 5) print(i,end=" ") 6) print() 7) for p in range(1,num): 8) print(" "*p,end="") 9) for q in range(1,num+1-p): 10) print(num-p,end=" ") 11) print() 1 22 333 4444 55555 4444 333 22 1

Pattern-78: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(1,i+1): 5) print(j,end=" ") 6) print() 7) for p in range(1,num):

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

print(" "*p,end="") for q in range(1,num+1-p): print(q+p,end=" ") print()

1 12 123 1234 12345 2345 345 45 5

Pattern-79: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(1,i+1): 5) print(j,end=" ") 6) print() 7) for p in range(1,num): 8) print(" "*p,end="") 9) for q in range(1,num+1-p): 10) print(q,end=" ") 11) print() 1 12 123 1234 12345 1234 123 12 1

Pattern-80: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(1,i+1): 5) print(chr(64+i),end=" ") 6) print()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

7) for p in range(1,num): 8) print(" "*p,end="") 9) for q in range(1,num+1-p): 10) print(chr(64+num-p),end=" ") 11) print() A BB CCC DDDD EEEEE DDDD CCC BB A

Pattern-81: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(1,i+1): 5) print(chr(64+j),end=" ") 6) print() 7) for p in range(1,num): 8) print(" "*p,end="") 9) for q in range(1,num+1-p): 10) print(chr(64+q+p),end=" ") 11) print() A AB ABC ABCD ABCDE BCDE CDE DE E

Pattern-82: 1) n=int(input("Enter a number:")) 2) for i in range(1,n+1): 3) print(" "*(n-i),end="") 4) for j in range(1,i+1): 5) print(n-i+j,end=" ")

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

6) for k in range(2,i+1): 7) print(n+1-k,end=" ") 8) print() 9) for i in range(1,n+1): 10) print(" "*i,end="") 11) for j in range(1+i,n+1): 12) print(j,end=" ") 13) for k in range(2,n+1-i): 14) print(n+1-k,end=" ") 15) print() 5 454 34543 2345432 123454321 2345432 34543 454 5

Pattern-83: 1) while True: 2) n=int(input("Enter a number:")) 3) for i in range(1,n+1): 4) print(" "*(n-i),end="") 5) for j in range(1,i+1): 6) print(n+1-j,end=" ") 7) for k in range(2,i+1): 8) print(n-i+k,end=" ") 9) print() 10) for i in range(1,n+1): 11) print(" "*i,end="") 12) for j in range(1,n+1-i): 13) print(n+1-j,end=" ") 14) for k in range(2,n+1-i): 15) print(i+k,end=" ") 16) print() 5 545 54345 5432345 543212345 5432345 54345 545

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

Pattern-84: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(i,i+1): 5) print("*",end=" ") 6) if i>=2: 7) print(" "*(2*i-4),end="") 8) for k in range(i,i+1): 9) print("*",end=" ") 10) print() * ** * * * * * *

Pattern-85: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(i,i+1): 5) print(i,end=" ") 6) if i>=2: 7) print(" "*(2*i-4),end="") 8) for k in range(i,i+1): 9) print(i,end=" ") 10) print() 1 22 3 3 4 4 5 5

Pattern-86: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(i,i+1):

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

print(num+1-i,end=" ") if i>=2: print(" "*(2*i-4),end="") for k in range(i,i+1): print(num+1-i,end=" ") print()

5 44 3 3 2 2 1 1

Pattern-87: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(i,i+1): 5) print(chr(64+num+1-i),end=" ") 6) if i>=2: 7) print(" "*(2*i-4),end="") 8) for k in range(i,i+1): 9) print(chr(64+num+1-i),end=" ") 10) print() E DD C C B B A A

Pattern-88: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(num-i),end="") 4) for j in range(i,i+1): 5) print(chr(64+i),end=" ") 6) if i>=2: 7) print(" "*(2*i-4),end="") 8) for k in range(i,i+1): 9) print(chr(64+i),end=" ") 10) print()

DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

A BB C C D D E E

Pattern-89: 1) num=int(input("Enter a number:")) 2) for i in range(1,num+1): 3) print(" "*(i-1),end="") 4) for j in range(i,i+1): 5) print("*",end=" ") 6) if i