Core Python
Core Python
Core Python
2) Operators …………………………………………………………………………………......…… 31
1 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Introduction to Python
1.Under the leadership of "ANDREW STUART TANENBAUM" a group of employees
developed distributed operating system.
2.group of employees used ABC scripting language to develop distributed
operating system.
3."ABC" scripting language is very simple and easy to learn and work.
4."GUIDO VAN ROSSUM" is a member in that group and he likes ABC scripting
language very well as it is very simple and easy.
5.In christmas holidays , Guido Van Rossum started developing a new language
to be simpler and easy compare to ABC scripting language and all other
existing language.
6.finally he developed a new language.
7.He likes "Nonty python's Flying Circus" english daily serial very well.
8.So finally Guido Van Rossum takenword python from that serial and kept
for his language.
9.So finally Guido van Rossum developed python scripting language at the
national research institute for mathematics & computer science in Netherland
in 1989 and it available to public in 20th feb 1991.
10.Python is now maintained by a core development team at the institute,although
Guido Van Rossum still hold the vital role in directing its progress.
11.Python 1.0 was released in january 1994.
12.Python 2.0 was released in october 2000 any python 2.7.11 in the last edition
of python 2.
13.Meanwhile, Python 3.0 was released in december 2008.
14.Python is general purpose high level programming language.
15.Python is recommended as first programming language for beginners.
16.Guido Van Rossum has developed python language by taking almost all programming
features from different languages.
17.The most of the syntaxes in python is taken from C and ABC languages.
Python:
--> Python is genral purpose programming language implemented by Guido Van Rossum in
1989 @ mathematics and science research center called CWI.CWI is located @ netherland.
-->Guido Van Rossum implemented python language by taking the different varities of
language features like:
=> Procedure Oriented Programming Languages.
=> Object Orientyed programming languages.
=>Scripting Languages.
=>Modular Programming Languages.
2 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
-->Guido Van Rossum make it available python to public in 1991. by using python we can
implement different varities of application like :
1) Automation Application.
2) Data Analytics.
3)Web Application.
4)Scientific application.
5)Web Scrapping.
6)N/W with IOT.
7)Test Cases.
8)Gaming Application.
9)GUI Application.
10)Admin Application.
11)animation applications and so on........
-->Currently copy right of pythons are registered with an community & non profitable
organisation called Python S/W foundation.
-->Python S/W which is provided by python s/w foundation is known as "cpyhton".
There are so many distributions are available for cpython
1) Active Python.
2) Anaconda Python.
3) iPython.
4)Pocket Python.
5)PYPY Python.
Flavors of Python
1. CPython:
It is the standard flaver of python.It can be used to work with c language
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.
3 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
6.Anaconda Python:
It is specially designed for handling large volume of data processing.
-->NTFS file system format in windows (No proper security,But it is user friendly)
-->APFS file system in MAC OS.
-->EXT3 file system in linux (user, group, author level security is provided in linux, but not
user friendly.)
-->HDFS this file system is similar to linux but with limited differences.
1) Interactive Mode:
--> The concept submitting 1-by-1 python statement explicitly to the python interpritter
is known as an interactive mode.
--> We can submit 1-by-1 python statement explicitly to the python interpritter by using
the python command line shell.
--> We can open the python cmd line shell, by executing the python command on cmd
prompt or terminal.
Drawbacks:
-->Once if we exit from python cmd line prompt, the work which we done is going to loss.
-->Interactive mode is suitable for learning python & to test predefined functions
functionalities, but it is not suitable for application development.
Batch Mode:
Concept of writting group of python statements in a file saving that file with extension.py
file and submitting entire file to interpritter is known as batch mode.
-->We can develop the python files by using the "editors" or "IDE's".
-->Different editors are notepad, notepad++, editplus, nano, VI, GEdit etc...
4 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
-->Different IDE's are pycharm(90% usage), eclipse, netbeans, eric etc...
-->Open Notepad save file with .py in any drive and type code .
-->To run the program open cmd then type python filename.py or py filename.py
Editors Dis-Advantages:
-->By using editors takes longer time(we have to remeber every thing while writting
program).
-->By development the python files by using editors we can't use code generation tools
(Smart help like ctrl+space)
-->We can't perform the automatic debugging operations on python files by using editors.
ID's Advantages:
To overcome the problems we use IDE's. Different IDE's are:
-->Pycharm
-->Eric
-->Eclipse
-->Netbeans
Features of Python:
1).Simple and easy to learn:
-->Python is a simple programming language, when we read python program, we can fell
like reading english statements.
-->The syntaxes are very simple and only 30+ keywords 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 time and cost of the project.
5 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
3).High level programming language:
-->Python is a high level programming language hence it is a 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 the python program, it can run on any platform without rewritting 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 other platform
very easily.
-->Python programs will provide same results on any platform.
**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 are statically typed languages bcoz we have to provide type at the beginning
only.
-->This dynamically typing nature will provide more flexibility to the programmer.
8).Intrepreted:
-->We are not required to compile python programs explicitly. Internally python
interpreter will take care that compilation.
6 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
9).Extensible:
-->We can use other language programs in python.
-->The main advantage of this approach are:
1).We can use already existing legacy non-python code.
2).We can improve performance of the application.
10).Embeded:
-->We can use python programs in any other language program.
-->i.e we can embedded python programs any where.
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.
Limitations of Python:
-->Performance wise not up to the mark bcoz it is interpreted language.
-->Not suitable for mobile applications.
Identfiers:
-->A name in the python program is called as identifier.
-->It can be a class name or function or module name or variable name.
Ex: a=10
def f():
class test:
-->By mistake if we are using any other symbol like $ then we will get syntax error.
7 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex: cash=10(Valid)
ca$h=10(Invalid)
3).Identifiers are case sensitive. Of course python language is case sensitive language.
Ex: total=500
TOTAL=500
Note:
-->If identifier starts with underscore(_) then it indicates it is private.
-->We can't use reserved words as identifiers
Ex: def=10
-->There is no length limit for python identifiers. But not recommended to use too lengthy
identifiers.
-->Dollar ($) symbol is not allowed in python.
-->If idetifier starts with (_ _)it indicates that strongly private identifiers.
-->If the identifier starts and ends with two underscores symbols then the isentifier is
language defined special name, which is also known as magic methods.
Ex: __add__
Reserved Words:
->In python some words are reserved to represent some meaning or functionality. Such
type of words are called as Reserved words.
-->There are 30+ reserved words in python
-->True, False, None
-->and, or, not, is
-->if, else, elif
-->while,for,break,continue,return,in,yield
-->try,except,finally,raise,assert
-->import,from,as,class,def,global,nonlocal,lambda,del,with
Note:
8 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Data Types:
-->Any organization use cases or scenarios are 2-parts.
1).Data
2).Operations
-->Data of any organization usecase can be represented in any programming language by
using data types and variables.
-->Every programming language supports data types & variables, but the data type of any
programming language are not going to be same with the data types & variables of other
programming language.
-->Operations of any organization use case can be represented in any programming
language by using functions or methods.
-->Every programming language supports functions or methods or both.
Datatype:
-->Data types are nothing but some of the keywords of programming language, which are
used to specify what type of data has to be store in the variable.
-->Without specifying data types variable memory allocation with not take place for
variables.
-->Without allocating memory space for the variable we can't store the data into
variables.
-->Programming languages supports 2-types of data types.
1).Static
2).Dynamic
9 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
-->Python, java script........languages are supported dynamic data types.
-->Every data type in python language is internally implemented as a class.
-->Python data types are catagorised into 2-parts.
-->Fundamental types
-->Collection types
10 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
>>> r=range(10)
To represent a range
range Immutable >>> r1=range(10,20)
of values
>>> r2=range(10,50,5)
To represent an >>> l=[10,20,30,40]
list ordered collection of Muttable >>> type(l)
objects <class 'list'>
To represent an >>> t=(1,2,3,4,5)
tuple ordered collection of Immutable >>> type(t)
objects <class 'tuple'>
To represent an >>> s={1,2,3,4,5,6}
set unordered collection Muttable >>> type(s)
of unique objects <class 'set'>
>>>
To represent a group
dict Muttable d={100:'Mahesh',102:'Durga',103:'Sunny'}
of key value pair
>>> type(d)
<class 'dict'>
1.int
2.float
3.complex
4.bool
5.str
6.bytes
7.bytesarray
8.range
9.list
10.tuple
11.set
12.frozenset
13.dict
14.None
11 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
1) >>> a=10
2) >>> id(a)
3) 140731593971008
4) >>> b=10
5) >>> id(b)
6) 140731593971008
7) >>> a=20
8) >>> id(a)
9) 140731593971328
Note:
Python contains several inbuilt functions
1).type():
To check the type of variable.
2).id():
To get the address of object.
-->In python every thing is an object
3).print():
To print the value
-->In python-2 we have long data type to represent very large integer values.
-->But in python-3 there is no long type explicitly we can represent long values also by
using int type only.
12 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
1).Decimal Form(Base-10):
-->It is the default number system in python.
-->The allowed digits are :0 to 9.
Ex: a=10
2).Binary form(Base-2):
-->The allowed digits are : 0 & 1.
-->Literal value should be prefixed with 0b or 0B.
Ex: a=0b1111(valid)
a=0B1111(valid)
a=0B123(Invalid)
3).Octal form(Base-8):
-->The allowed digits are :0 to 7
-->Literal value should be prefixed with 0o or 0O
Ex: a=0o123(Valid)
a=0O786(Invalid)
Note:
Being a programmer we can specify literal values in decimal, binary, octal and hexa
decimal forms, But PVM will always provide values in decimal form.
Ex:
1) >>> a=10
2) >>> b=0b10
3) >>> c=0o10
4) >>> d=0x10
5) >>> print(a):10
6) >>> print(b):2
7) >>> print(c):8
8) >>> print(d):16
13 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Base Conversions:
Python provides the following in-built functions for base conversions
1).bin():
We can use bin() to convert from any base to binary
1) >>> bin(15)
2) '0b1111'
3) >>> bin(0o11)
4) '0b1001'
5) >>> bin(0x10)
6) '0b10000'
2).oct():
We can use oct() to convert from any base to octal.
1. >>> oct(10)
2. '0o12'
3. >>> oct(0b1111)
4. '0o17'
5. >>> oct(0x123)
6. '0o443'
3).hex():
We can use hex() to convert any base to hexa decimal.
1. >>> hex(100)
2. '0x64'
3. >>> hex(0B111111)
4. '0x3f'
5. >>> hex(0o12345)
6. '0x14e5'
2).Float:
-->We can use float data type to represent floating point values(decimal values).
1. >>> f=1.234
2. >>> type(f)
3. <class 'float'>
14 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
-->We can also represent floating point values by using exponential form(Scintific
notation)
1. >>> f=1.2e3
2. >>> f
3. 1200.0
-->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 by using decimal form only.
1. f=0B11.10(Invalid)
2. f=0o123.234(Invalid)
3. f=0x12.face(Invalid)
1. a=3+4j
2. a=1.5+2.5j
3. a=3+0B1010j(Invalid)
4. a=0b10101+3J(valid)
1. >>> a=3+1.5j
2. >>> b=4+2.5j
3. >>> a+b
15 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
4. (7+4j)
5. >>> a-b
6. (-1-1j)
Note:
Complex data type has some inbuilt attributes to retrieve the real part and imaginary part.
1. >>> c=10.5+3.6j
2. >>> c.real
3. 10.5
4. >>> c.imag
5. 3.6
-->We can use complex type generally in scintific applications and electrical engineering
applications.
1. a=True
2. type(a)==>bool
Ex:
1. >>> a=10
2. >>> b=20
3. >>> c=a<b
4. >>> print(c)
5. True
6.
7. >>>True+True==>2
8. >>>True-False==>1
16 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
s="Mahesh"
-->By using single quotes or double quotes we can't represent multi line string literals.
Ex: s="Mahesh
Dasari"(Invalid)
-->For this requirement we should go for triple quotes(''') or triple double quotes(""")
Ex: s='''Mahesh
Dasari'''
s="""Durga
Soft"""
-->We can embeded one string in another string.
Ex: '''This "python classes very helpful" for java students'''.
Slicing of Strings:
-->Slice means a piece.
-->[:] is called as slice operator, which can be used to retrieve parts of string.
-->In python string 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. >>> s="python"
2. >>> s[0]
3. 'p'
4. >>> s[1]
5. 'y'
6. >>> s[-1]
7. 'n'
8. >>> s[30]
9. IndexError: string index out of range
10. >>> s[1:40]
11. 'ython'
12. >>> s[1:]
13. 'ython'
14. >>> s[:4]
15. 'pyth'
16. >>> s[:]
17. 'python'
18. >>> s[-1:-4](Begin position should be lower than end position)
19. ''
20. >>> s[-4:-1]
21. 'tho'
22. >>> s*3
17 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
23. 'pythonpythonpython'
24. >>> len(s)
25. 6
Note:
-->In the python the following data types are considered as fundamental data types.
-->int
-->float
-->complex
-->bool
-->str
-->In python , we can represent char values also by using str type and explicitly char type
not available.
1. >>> c='a'
2. >>> type(c)
3. <class 'str'>
-->long data type is available in python2 but not in python3. In python3 long values also
we can represent by using int type only.
Type Casting:
-->We can convert one type to other type. This conversion is called as Typecasting or Type
coersion.
-->The following are various in-built functions for type casting.
-->int()
-->float()
-->complex()
-->bool()
-->str()
1).int():
We can use this function to convert values from other types to int.
1. >>> int(123.456)
2. 123
3. >>> int(10+4j)
4. TypeError: can't convert complex to int
5. >>> int(True)
6. 1
7. >>> int(False)
18 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
8. 0
9. >>> int("10")
10. 10
11. >>> int("10.5")
12. ValueError: invalid literal for int() with base 10: '10.5'
13. >>> int("ten")
14. ValueError: invalid literal for int() with base 10: 'ten'
15. >>> int("0B1010")
16. ValueError: invalid literal for int() with base 10: '0B1010'
Note:
-->We can convert from any type to int except complex type.
-->If we want to convert str type to int type, compalsury str should contains only integral
value and should be specified in base-10.
2).float():
We can use float() to convert other type values to float type.
1. >>> float(10)
2. 10.0
3. >>> float(10+4j)
4. TypeError: can't convert complex to float
5. >>> float(True)
6. 1.0
7. >>> float(False)
8. 0.0
9. >>> float("10")
10. 10.0
11. >>> float("10.5")
12. 10.5
13. >>>float("ten")
14. ValueError: could not convert string to float: 'ten'
Note:
-->We can convert any type value to float type expcept complex type.
-->Whenever we are trying to convert str type to float type compalsury 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 data type to complex type.
19 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Form-1:complex(x)
We can use this function to convert x into complex number with real part x and imaginary
part 0.
1. >>> complex(10)
2. (10+0j)
3. >>> complex(10.5)
4. (10.5+0j)
5. >>> complex(True)
6. (1+0j)
7. >>> complex(False)
8. 0j
9. >>> complex("10")
10. (10+0j)
11. >>> complex("10.5")
12. (10.5+0j)
13. >>> complex("ten")
14. ValueError: complex() arg is a malformed string
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.
1. >>> complex(10,2)
2. (10+2j)
3. >>> complex(10,-2)
4. (10-2j)
5. >>> complex(True,False)
6. (1+0j)
7. >>> complex("10","10.2")
8. TypeError: complex() can't take second arg if first is a string
4).bool():
We can use this function to convert other type to bool type
1. >>> bool(0)
2. False
3. >>> bool(1)
4. True
5. >>> bool(10)
6. True
7. >>> bool(0.123)
8. True
20 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
9. >>> bool(10.5)
10. True
11. >>> bool(0.0)
12. False
13. >>> bool(10+4J)
14. True
15. >>> bool(0+0j)
16. False
17. >>> bool("True")
18. True
19. >>> bool("")
20. False
21. >>> bool(None)
22. False
23. >>> bool(" ")
24. True
5).str():
We can use this method to convert other type values to str type.
1. >>> str(10)
2. '10'
3. >>> str(10.5)
4. '10.5'
5. >>> str(True)
6. 'True'
7. >>> str(10+4j)
8. '(10+4j)'
-->In python if a new object is required, then PVM won't create object immediately. First it
will check if any object is available with the required content or not. If available then
existing object will be re-used. 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.
21 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Accordint to this once we create an object we are not allowed to change content. If we are
trying with those changes a new object will be created.
Ex:
1) >>> a=10
2) >>> b=10
3) >>> id(a)
4) 140723035886912
5) >>> id(b)
6) 140723035886912
7) >>> a is b
8) True
9)
Note:
-->There is no Re-Usability for float & complex type.
-->Re-Usability is applicable for int only the range 0-256.
Ex:
1) >>> x=[10,20,30,40]
2) >>> b=bytes(x)
3) >>> type(b)
4) <class 'bytes'>
5) >>> b[0]
6) 10
7) >>> b[-1]
22 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
8) 40
9) >>> for i in b:print(i)
10) 10
11) 20
12) 30
13) 40
Conclusion 1:
The only allowed values for byte data type are 0 to 256. BY mistakes if we are trying to
provide any other values then we will get value error.
Ex: >>> x=[10,20,300,40]
>>> b=bytes(x)
ValueError: bytes must be in range(0, 256)
Conclusion 2:
Once we create bytes data type value, we can't change it values, if we are trying to change
we will get an error.
Ex: >>> x=[10,20,30,40]
>>> b=bytes(x)
>>> b[2]=50
TypeError: 'bytes' object does not support item assignment
1) >>> x=[10,20,30,40]
2) >>> b=bytearray(x)
3) >>> for i in b:print(i)
4) 10
5) 20
6) 30
7) 40
8) >>> b[2]=50
9) >>> for i in b:print(i)
10) 10
11) 20
12) 50
13) 40
23 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
8).List Data Type:
If we want to represent a group of values as a single entity where insertion order is
required to preserve and duplicates are allowed then we should go for list data type.
Ex:
1) >>> list=[10,20,'mahesh',True]
2) >>> print(list)
3) [10, 20, 'mahesh', True]
Ex:
1) >>> list=[10,20,30,40]
2) >>> list[0]
3) 10
4) >>> list[-1]
5) 40
6) >>> list[1:3]
7) [20, 30]
8) >>> list[0]=100
9) >>> for i in list:print(i)
10) 100
11) 20
12) 30
13) 40
-->List is growable in nature. i.e based on our requirement we can increase or decrease
the size.
Ex:
1) >>> list=[10,20,30]
2) >>> list.append('mahesh')
3) >>> list
4) [10, 20, 30, 'mahesh']
5) >>> list.remove(20)
6) >>> list
7) [10, 30, 'mahesh']
8) >>> list2=list*2
24 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
9) >>> list2
10) [10, 30, 'mahesh', 10, 30, 'mahesh']
Note:
An order, mutable, heterogenous collection of elements is nothing but a list, where
duplicates also allowed.
Ex:
1) >>> t=(10,20,30,40)
2) >>> type(t)
3) <class 'tuple'>
4) >>> t[0]
5) 10
6) >>> t[0]=100
7) TypeError: 'tuple' object does not support item assignment
8) >>> t.append('mahesh')
9) AttributeError: 'tuple' object has no attribute 'append'
10) >>> t.remove(10)
11) AttributeError: 'tuple' object has no attribute 'remove'
12) >>> t[1:3]
13) (20, 30)
Form-1:range(10)
->Generates numbers from 0-9
Ex: r=range(10)
>>> for i in r:print(i)
Form-2: range(10,20)
-->Generates numbers from 10-19
Ex: r=range(10,20)
>>> for i in r:print(i)
25 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Form-3: range(10,50,5)
-->5 means step(increment value)
>>> for i in r:print(i)
>>>10 15 20 25 30 35 40 45
-->We can access elements present in the range data type by using index.
Ex:
1) >>> r=range(10,20)
2) >>> r[0]
3) 10
4) >>> r[15]
5) IndexError: range object index out of range
6) >>> r[0]=100
7) TypeError: 'range' object does not support item assignment
Ex:
1) >>> l=list(range(10))
2) >>> l
3) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Ex:
1) >>> s={10,20,30}
2) >>> s
3) {10, 20, 30}
4) >>> s[0]
5) TypeError: 'set' object does not support indexing
6) >> s={10,20,30,'mahesh'}
26 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
7) >>> s
8) {'mahesh', 10, 20, 30}
-->set is a growable nature, based on our requirement we can increase or decrease the
size.
1) >>> s.add(40)
2) >>> s
3) {40, 10, 20, 'mahesh', 30}
4) >>> s.remove(20)
5) >>> s
6) {40, 10, 'mahesh', 30}
Ex:
1) >>> s={10,20,30,40}
2) >>> fs=frozenset(s)
3) >>> type(fs)
4) <class 'frozenset'>
5) >>> fs
6) frozenset({40, 10, 20, 30})
7) >>> for i in fs:print(i)
8) 40
9) 10
10) 20
11) 30
12) >>> fs.add(50)
13) AttributeError: 'frozenset' object has no attribute 'add'
14) >>> fs.remove(20)
15) AttributeError: 'frozenset' object has no attribute 'remove'
Ex:
1) >>> d={100:'mahesh',102:'durga',103:'sunny'}
2) >>> type(d)
27 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
3) <class 'dict'>
4) >>> d[100]
5) 'mahesh'
-->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.
1) >>> d[100]='suresh'
2) >>> d
3) {100: 'suresh', 102: 'durga', 103: 'sunny'}
1) >>> d={}
2) >>> type(d)
3) <class 'dict'>
1) >>> d['a']='apple'
2) >>> d['b']='banana'
3) >>> d
4) {'a': 'apple', 'b': 'banana'}
1) >>> s=set()
2) >>> type(s)
3) <class 'set'>
4) >>> s.add(10)
5) >>> s.add(30)
6) >>> s
7) {10, 30}
Note:
-->In general we can use bytes and bytearray data types to represent binary information
like images, video files etc....
-->In python-2 long data type is available. But in python-3 it is not available and we can
represent long values also by using int type only.
-->In python there is no char data type. Hence we can represent char values also by using
str type
28 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
14).None Data Type:
-->None means nothing or No value aasociated.
-->If the value is not available, then to handle such type of cases None introduced.
-->It is some thing like null value in java.
Escape Characters:
-->In string literals we can use escape characters to aasociate a special meaning.
1) >>> s="Durga\nSoftware"
2) >>> print(s)
3) Durga
4) Software
5) >>> s="Durga\tSoftware"
6) >>> print(s)
7) Durga Software
8) >>> s="This is " symbol"
9) SyntaxError: invalid syntax
10) >>> s="This is \" symbol"
11) >>> print(s)
12) This is " symbol
29 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Constants:
-->Constants concept is not applicable in python.
-->But it is convention to use only upper case characters if we don't want to change.
MAX_VALUE=10
-->It is just convention but we can change the value.
30 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
OPERATORS
-->Any person who is doing certain activity is called as an operator.
-->Operator is a symbol that performs certain operations.
-->Python provides the following set of operators.
1).Arithmetic Operators
2).Relational Operators OR Comparision Operators
3).Logical Operators.
4).Bitwise Operators
5).Assignment Operators
6).Special Operators
1).Arithmetic Operators:
+ ==>Addition
- ==>Subtratction
* ==>MUltiplication
/ ==>Division operator
% ==>Modulo operator
Ex:
1) >>> a=10
2) >>> b=2
3) >>> print('a+b=',a+b)
4) a+b=12
5) >>> print('a-b=',a-b)
6) a-b=8
7) >>> print('a*b=',a*b)
8) a*b= 20
9) >>> print('a/b=',a/b)
10) a/b=5.0
11) >>> print('a//b=',a//b)
12) a//b=5
13) >>> print('a%b=',a%b)
14) a%b=0
15) >>> print('a**b=',a**b)
31 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
16) a**b=100
Ex:
1) a=10.5
2) b=2
3) a+b=12.5
4) a-b=8.5
5) a*b=21.0
6) a/b=5.25
7) a//b=5.0
8) a%b=0.5
9) a**b=110.25
Ex:
1) >>> 10/2-->5.0
2) >>> 10//2 -->5
3) >>> 10.0/2-->5.0
4) >>> 10.0//2-->5.0
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
the result is float type.
Note:
-->We can use +, * operators for str data type also.
-->If we want to use + operator for str type then compalsary both arguments should be str
type only otherwise we will get error.
1. >>> "Mahesh"+3
2. TypeError: can only concatenate str (not "int") to str
3. >>> "Mahesh"+"3"
4. 'Mahesh3'
-->If we use * operator for str type then compalsary one argument should be int and other
argument should be str type.
1) >>> "Mahesh"*3
2) 'MaheshMaheshMahesh'
3) >>> 3*"Mahesh"
32 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
4) MaheshMaheshMahesh'
5) >>> "Mahesh"*2.5
6) TypeError: can't multiply sequence by non-int of type 'float'
7) >>> "Mahesh"*"Mahesh"
8) TypeError: can't multiply sequence by non-int of type 'str'
2).Relational Operators:
>, >=, <, <=
Ex:
1) a=10
2) b=20
3) a>b is False
4) a>=b is False
5) a<b is True
6) a<=b is True
Ex:
1) >>> a="mahesh"
2) >>> b="durga"
3) >>> a>b is True
4) >>> a<b is False
5) >>> a="durga"
6) >>> b="darga"
7) >>> a>b is True
8) >>> a="durga"
9) >>> b="Durga"
10) >>> a>b is True
Ex:
1) >>> True>True
2) False
3) >>> True>=True
4) True
5) >>> 10>True
33 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
6) True
7) >>> False>True
8) False
9) >>> 10>'a'
10) TypeError: '>' not supported between instances of 'int' and 'str'
Ex:
1) a=10
2) b=20
3) if(a>b):
4) print("a is greater than b")
5) else:
6) print("a is not grater than b")
Note:
Chaining of relational operators is possible. In the chaining, if all comparisions returns
True then only result is True. If atleast one comparision False then the result is False.
1) >>> 10<20
2) True
3) >>> 10<20<30
4) True
5) >>> 10<20<30<40
6) True
7) >>> 10<20<30<40>50
8) False
3).Equality Operators:
==,!=
-->We can apply these operators for any type even for incompatible types also.
1) >>> 10==20
2) False
3) >>> 10!=20
4) True
5) >>> 10==True
6) False
7) >>> False==False
8) True
9) >>> 'mahesh'=='mahesh'
10) True
34 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
11) >>> 10=='mahesh'
12) False
13) >>> 10==10.0
14) True
15) >>> 10==10.1
16) False
17) >>> 10=='10'
18) False
19) >>> 10.10==10.1
20) True
21) >>> 1==True
22) True
Note: Chaining concept is applicable for equality operators. If atleast one comparision
returns False then the result is False.Otherwise the result is True.
1) >>> 10==20==30==40
2) False
3) >>> 10==5+5==3+7==2*5
4) True
1) >>> (10+2j)==(10+2j)
2) True
3) >>> (10+2j)==(10+5j)
4) False
4).Logical Operators:
and,or,not
-->We can apply for all types.
35 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
For non-boolean types behaviours:
-->0 means false
-->non-zero means True
-->Empty string is always treated as False
x and y:
-->If x evaluates to False return x otherwise return y.
1) >>> 10 and 20
2) 20
3) >>> 0 and 20
4) 0
-->If the 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
1) >>> 10 or 20
2) 10
3) >>> 0 or 20
4) 20
not x:
-->If x evaluates to False then the result is True otherwise False.
Ex:
1) >>> not 10
2) False
3) >>> not ''
4) True
Ex:
36 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
8) 'durgasoft'
9) >>> not "durgasoft"
10) False
11) >>> 10 or 10/0
12) 10
13) >>> 0 or 10/0
14) ZeroDivisionError: division by zero
5).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 data type then we will get an error.
&, |, ^, ~, <<, >>
Ex:
37 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
1==>0 & 0==>1
Ex:
1) >>> print(4&5) 4
2) >>> print(4|5) 5
3) >>> print(4^5) 1
1) >>> print(~4) -5
2) >>> print(~True) -2
Note:
-->The most significant bit acts as sign bit. 0 value represents +ve number where as 1
represent -ve value.
-->Positive numbers will be represented directly in memory where as -ve numbers will be
represented indeirectly in 2's complement form.
Shift Operators:
1) >>> print(10>>2) 2
2) >>> print(-10>>2) -3
Ex:
nd
38 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
5) >>> print(True<<2) 4
6) >>> print(True>>2) 0
6).Assignment Operators:
-->We can use assignment operator to assign a value to the valiable.
Ex: x=10
-->We can combine assignment operator with some other operator to form compound
assignment operator.
Ex: x+=10==>x=x+10
Ex:
x++==>Invalid syntax
++x==>Valid
x--==>Invalid syntax
--x==>Valid
7).Ternary Operator:
-->In java we can use
x=(condition)?First value:Secondvalue
Ex:
1) x=(10<20)?30:40
2) print(x)
3) SyntaxError: invalid syntax(In python)
Ex:
o/p:30
Ex:
1) a,b=10,20
2) x=30 if a>b else 40
39 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
3) print(x)
o/p:40
Note: Bydefault if we enter anything from the keyboard it will be treated as str type,
hence we convert into int.
Ex:
Ex:
o/p:10
o/p:70
8).Special Operators:
-->Python defines the following 2-special operators
1).Identity operator
2).Memebership operator
40 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
1).Identity operator:
We can use identify operators for address comparision. 2-identifty operators are
available.
-->is
-->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.
Ex:
1) a=10
2) b=10
3) print(a is b)==>True
Ex:
1) x=True
2) y=True
3) print(x is y)==>True
Ex:
1) a="mahesh"
2) b="mahesh"
3) print(id(a))
4) print(id(b))
5) print(a is b)
Ex:
1) list1=["one","two","three"]
2) list2=["one","two","three"]
3) print(id(list1))
4) print(id(list2))
5) print(list1 is list2)
6) print(list1 is not list2)
7) print(list1 == list2)
Note: We can use is operator for address comparision where as == operator for content
comparision.
41 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
2).Memebership operator:
We can use membership operators to check whether the given object present in the given
collection.(Ot may be string, list, tuple, set or Dict).
Ex:
1) >>> list=[10,20,30,40]
2) >>> print(10 in list)==>True
3) >>> print(50 in list)==>False
4) >>> print(50 not in list)==>True
Ex:
Operator Precedence:
If multiplr operators present then which operator will be evaluated first is decided by
operator precedence.
Ex:
1) >>> 3+10*2==>23
2) >>> (3+10)*2==>26
Ex:
1) >>> a=30
2) >>> b=20
3) >>> c=10
4) >>> d=5
5) >>> print((a+b)*c/d)==>100.0
6) >>> print((a+b)*(c/d))==>100.0
7) >>> print(a+(b*c)/d)==>70.0
42 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
*,/,%,//==>Multiplication, division,modulo,floor division.
+-==>Addition, subtratcion
<<,>>==>Left & Right shft
&==>Bitwise and
^==>Bitwise x-or
|==>Bitwise or
>,>=,<,<=,==,!= ==>Relational operators & comparision operators
=,+=,-=,*= ==>Assignment operators
is, is not==>identity operators
in, not in==>Membership operators
not==>Logical not
and==>Logical and
or==>Logical or
Ex:
1) 3/2*4+3+(10/5)**3-2
2) ==>3/2*4+3+2.0**3-2
3) ==>3/2*4+3+8.0-2
4) ==>1.5*4+3+8.0-2
5) ==>6.0+3+8.0-2
6) ==>15.0
1) import math
2) print(math.sqrt(16))
3) print(math.pi)
o/p: 4.0
3.14159.......
43 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
-->Once we create alias name , by using that we can access functions and variables of that
module.
Ex:
1) import math as m
2) print(m.sqrt(16))
3) print(m.pi)
-->If we import a member explicitly then it is not required to use module name while
accessing.
Ex:
44 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Input & Output streams
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.
2).input():
input() function can be used to read data directly in our required format. We rae
not required to perform type casting.
Ex:
1) x=input(Enter value")
2) type(x)
3) 10==>int
4) "mahesh"==>str
5) 10.5==>float
6) True==>bool
Note:
-->But in python-3 we have only input() method and raw_input() method is not available.
45 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
5) <class 'str'>
6) Enter some value:1.234
7) <class 'str'>
2).
3).
Q: w.a.p to read employee data from the keyboard and print that data.
46 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Q: w.a.p to read 3 float numbers from the keyboard with , separator and print their sum
Note: split() function can take space as separator bydefault, But we can pass anything as
separator.
eval():
-->eval function take a string and evaluate the result.
1) >>> x=eval("10+20+30")
2) >>>x
3) >>>60
4)
5) x=eval(input("Enter expression :"))
6) print(x)
7) Enter expression :10+2*3/4
8) 11.5
-->eval() can evaluate the input to list, tuple, set etc...based on provided input.
Ex: w.a.p to accept list from the keyboard and diplsy.
nd
47 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Note:
-->split() always accept sting only as a separator.
-->If we are not using eval() then it is treated as str.
Ex:
Note: argv[0] represents name of the program, but not the first command line argument.
argv[1] represents First command line argument.
48 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex: Sum of the arguments.
Note: Usually space is separator between command line arguments. If our command line
arguments itself contains space then we should enclose within double quotes(but not in
single quote).
Note: 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.
Ex:
49 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Note: If we are trying to access command line arguments with out of range index then we
will get an error.
Ex:
Output Streams:
We can use print() function to display output.
Form-2: print(String)
print("Hello world")-->We can use escape characters also
print("Hello \n world")
print("Hello \t world")
-->We can use repetetion operator(*) in the string
print(10*"hello")
print("hello"*10)
Note:
-->If both arguments are string type then + operator acts as concatination operator.
-->If one argument is string type and second is any other type like int then we eill get an
error.
-->If both arguments are number type then + operator avts as arithmetic addition
operator.
50 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Form-3: print() with variable number of arguments
Ex:
1) a,b,c=10,20,30
2) print("The values are: ",a,b,c)
Ex:
1) a,b,c=10,20,30
2) print(a,b,c,sep=',')
3) print(a,b,c,sep=':')
o/p:D:\pythonclasses>py test.py
10,20,30
10:20:30
o/p: Hello
Durga
Soft
1) print("Hello",end=' ')
2) print("Durga",end=' ')
3) print("Soft")
o/p:D:\pythonclasses>py test.py
Hello Durga Soft
Note: The default value of end attribute is \n, which is nothing but new line character.
51 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Form-5:print(object) statement
-->We can pass any object(like list, tuple, set etc) as argument to the print statement.
Ex:
1) l=[10,20,30,40]
2) t=(10,20,30,40)
3) print(l)
4) print(t)
1) s="Mahesh"
2) a=50
3) s1="Selenium"
4) s2="Python"
5) print("Hello",s,"Your age is :",a)
6) print("You are teaching", s1,"and", s2)
Form-7:print(formatted string):
%i====>int
%d===>int
%f===>float
%s===>string type
1) a=10
2) b=20
3) c=30
4) print("a value is %d" %a)
5) print("b value is %d and c value is %d" %(b,c))
o/p: a value is 10
b value is 20 and c value is 30
nd
52 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex:
1) s="Mahesh"
2) list[10,20,30,40]
3) print("Hello %s.....The list of values are %s" %s(s,list))
o/p: Hello Mahesh.....The list of values are [10, 20, 30, 40]
1) name="Mahesh"
2) salary=10000
3) gf="sunny"
4) print("Hello {0} your salary {1} and yor girl friend {2} is waiting".format(name,salar
y,gf))
5) print("Hello {} your salary {} and yor girl friend {} is waiting".format(name,salary,gf
))
6) print("Hello {x} your salary {y} and yor girl friend {z} is waiting".format(z=gf,x=nam
e,y=salary))
o/p: Hello Mahesh your salary 10000 and yor girl friend sunny is waiting
Hello Mahesh your salary 10000 and yor girl friend sunny is waiting
Hello Mahesh your salary 10000 and yor girl friend sunny is waiting
53 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
FLOW CONTROL
-->Flow control describes the order in which statements will be executed at runtime.
1).Conditional Statements:
========================
1).if:
if condition: statement
or
if condition:
statement-1
statement-1
statement-1
-->If condition is true then statements will be executed.
Ex:
1) name=input("Enter Name:")
2) if name=="mahesh":
3) print("Hello mahesh good morning")
4) print("How r you!!!")
54 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Enter Name:mahesh
Hello mahesh good morning
How r you!!!
2).if-else:
if condition:
Action-1
else:
Action-2
-->If condition is true Action-1 will be executed otherwise Axtion-2 will be executed.
Ex:
1) name=input("Enter Name:")
2) if name=="mahesh":
3) print("Hello mahesh good morning")
4) else:
5) print("Hello guest good morning")
6) print("How r you!!!")
3).if-elif-else:
syn:
if condition1:
Action-1
elif condition-2:
Action-2
elif condition-3:
Action-3
else
Default Action
55 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
-->Based on condition the corresponding action will be executed.
Ex:
o/p:D:\pythonclasses>py test.py
Enter your favourite Brand:RC
It is a childrens brand
D:\pythonclasses>py test.py
Enter your favourite Brand:KF
It is not much that kick
D:\pythonclasses>py test.py
Enter your favourite Brand:FO
Buy one get one free
D:\pythonclasses>py test.py
Enter your favourite Brand:karjura
Other brands are not recommended
56 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
6) print("Biggest Number is:",n2)
o/p:D:\pythonclasses>py test.py
Enter First Number:10
Enter Second Number:40
Enter Third Number:20
Biggest Number is: 40
D:\pythonclasses>py test.py
Enter First Number:10.6
Enter Second Number:2.6
Enter Third Number:17.3
Biggest Number is: 17.3
D:\pythonclasses>py test.py
Enter First Number:"mahesh"
Enter Second Number:"durga"
Enter Third Number:"sunny"
Biggest Number is: sunny
1) n=int(input("Enter Number:"))
2) if n>=1 and n<=10:
3) print("The number",n,"is in between 1 to 10")
4) else:
5) print("The number",n,"is not in between 1 to 10")
57 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Q: w.a.p to take a single digit number from the keyboard and print value in english word?
---------------------------------------------------------------------------------------------------------------------
0==>ZERO
3==>THREE
1) n=int(input("Enter Number:"))
2) if n==0:
3) print("ZERO")
4) elif n==1:
5) print("ONE")
6) elif n==2:
7) print("TWO")
8) elif n==3:
9) print("THREE")
10) elif n==4:
11) print("FOUR")
12) elif n==5:
13) print("FIVE")
14) elif n==6:
15) print("SIX")
16) elif n==7:
17) print("SEVEN")
18) elif n==8:
19) print("EIGHT")
20) elif n==9:
21) print("NINE")
22) else:
23) print("Please enter a digit from 0-9")
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.
Syn:
for x in sequence:
Body
58 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex: To print the characters present in the given string.
1) s="Sunny Leone"
2) for x in s:
3) print(x)
1) s="Sunny Leone"
2) i=0
3) for x in s:
4) print("The character present at ",i, "index",x)
5) i=i+1
o/p:
D:\pythonclasses>py test.py
The character present at 0 index S
The character present at 1 index u
The character present at 2 index n
The character present at 3 index n
The character present at 4 index y
The character present at 5 index
The character present at 6 index L
The character present at 7 index e
The character present at 8 index o
The character present at 9 index n
The character present at 10 index e
1) for x in range(10):
2) print("Hello")
1) for x in range(10):
2) print(x)
1) for x in range(21):
2) if(x%2!=0):
3) print(x)
(or)
59 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
1) for x in range(1,21,2):
2) print(x)
1) for x in range(10,0,-1):
2) print(x)
2).while loop:
============
-->If we want to execute a group of statements iteratively until some condition false,
then we should go for while loop.
Syn:
while condition:
body
1. x=1
2. while x<=10:
3. print(x)
4. x+=1
1) n=int(input("Enter Number:"))
2) sum=0
3) i=1
4) while i<=n:
5) sum=sum+i
6) i+=1
7) print("The sum of the first",n,"numbers is:",sum)
Ex: w.a.p to prompt user to enter some name until entering mahesh.
1) name=""
2) while name!="mahesh":
3) name=input("Enter Name:")
4) print("Thanks for confirmation")
Ex:w.a.p to prompt user to enter name & pwd until mahesh & python
1) username=""
2) password=""
3) while (username!="mahesh") or (password!="python"):
60 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
4) username=input("Enter correct username :")
5) password=input("Enter correct pwd:")
6) print("Thanks for confirmation")
Infinite Loops:
=============
1) i=0
2) while True:
3) i=i+1
4) print("Hello",i)
Nested Loops:
============
-->Sometimes we can take a loop inside anopther loop, which are also known as nested
loops
Ex:
1) for i in range(5):
2) for j in range(4):
3) print("i=",i," j=",j)
Alternative way:
1) for i in range(5):
2) for j in range(4):
3) print("i={} and j={}".format(i,j))
Ex:
Alternative way:
61 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
1) n=int(input("Enter some number:"))
2) for i in range(1,n+1):
3) print("* "*i)
Ex:
ALternative way:
Transfer Statements:
===================
1)break:
We can use break statement inside loops to break loop execution based on some
condition.
Ex:
1) for i in range(10):
2) if I == 3:
3) print("processing is enough...plz break")
4) break
5) print(i)
62 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
1
2
processing is enough...plz break
Ex:
1) cart=[10,20,600,60,70]
2) for item in cart:
3) if item>500:
4) print("To place this order insurance must be required")
5) break
6) print(item)
2).continue:
We can use continue statement to skip current iteration and continue next
iteration.
Ex: 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)
Ex:
1) cart=[10,20,600,60,70,550,40]
2) for item in cart:
3) if item>500:
4) print("We can't process this item: ",item)
5) continue
6) print(item)
63 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
o/p:
D:\pythonclasses>py test.py
10
20
We can't process this item: 600
60
70
We can't process this item: 550
40
Ex:
1) numbers=[10,20,0,5,0,30]
2) for n in numbers:
3) if n==0:
4) print("hey how we can devide with zero...just skipping")
5) continue
6) print("100/{}={}".format(n,100/n))
o/p:
D:\pythonclasses>py test.py
100/10=10.0
100/20=5.0
hey how we can devide with zero...just skipping
100/5=20.0
hey how we can devide with zero...just skipping
100/30=3.3333333333333335
1) cart=[10,20,30,40,50]
2) for item in cart:
3) if item>500:
4) print("We can't process this order")
5) break
6) print(item)
7) else:
8) print("Congrats.... all items processed suuccessfully")
64 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
o/p:
D:\pythonclasses>py test.py
10
20
30
40
50
Congrats.... all items processed suuccessfully
Ex:
1) cart=[10,20,30,600,40,50]
2) for item in cart:
3) if item>500:
4) print("We can't process this order")
5) break
6) print(item)
7) else:
8) print("Congrats.... all items processed suuccessfully")
o/p:
D:\pythonclasses>py test.py
10
20
30
We can't process this order
65 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
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
Ex:
if True:
o/P:SyntaxError: unexpected EOF while parsing
Ex: if True:pass
==>Valid
1) for i in range(100):
2) if i%9==0:
3) print(i)
4) else:pass
o/p:
D:\pythonclasses>py test.py
0
9
18
27
36
45
66 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
54
63
72
81
90
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 statement.
Ex:
1) x=10
2) print(x)
3) del x
4) print(x)
-->After deleting a variable we can't access that variable otherwise we will get name error
o/p:
NameError: name 'x' is not defined
Note:
We can delete variables which are pointing to immutable objects. BUt we can't
delete the elements present inside the immutable object.
Ex:
1) s="mahesh"
2) del s==>Valid
3) del s[0]==>Name Error: 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.
Ex:
1) s="mahesh"
2) s=None
3) print(s)==>None
nd
67 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
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 the string DT.
What is a String?
Any sequence of characters within either single quotes or double quotes is
considered as a String.
Syn:
s='mahesh'
s="mahesh"
Note:
In most of other languages 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.
Ex:
1) >>> ch='a'
2) >>> type(ch)
3) <class 'str'>
1) >>>s='''Durga
2) Software
3) Solutions'''
-->We can also use triple quotes to use single quotes or double quotes as symbol inside
the string.
Ex:
68 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
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
Ex:
1) -6- 5 -4 -3 -2-1
2) s = 'm a h e s h'
3) 0 1 2 3 4 5
Ex:
1) s[0]==>m
2) s[-1]==>h
3) s[10]==>String index out of range.
Q: w.ap to accept some string from the keyboard and display its characters by index
wise(both +ve and -ve)
o/p:
D:\pythonclasses>py test.py
Enter some string:mahesh
The character present at Positive index 0 and Negative index -6 is m
The character present at Positive index 1 and Negative index -5 is a
The character present at Positive index 2 and Negative index -4 is h
The character present at Positive index 3 and Negative index -3 is e
The character present at Positive index 4 and Negative index -2 is s
The character present at Positive index 5 and Negative index -1 is h
69 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
2).Accessing characters by using slice operator:
==========================================
Syn:
s[Begin index:End index:step]
-->Beginindex: From where we have to consider slice(substring)
-->Endindex:We have to terminate the slice(substring) at endindex-1.
-->Step:Increment 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.
Ex:
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
70 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
In backward direction:
--------------------------------
Default value for Begin:-1
Default value for end:-(length of string+1)
Note: Either forward or backward directions, we can both +ve and -ve values for begin and
end index.
Ex:
1) >>> s='0123456789'
2) >>> s[2:8:1] '234567'
3) >>> s[2:8:-1] ''
4) >>> s[-1:-6:-1] '98765'
5) >>> s[2:-5:1] '234'
6) >>> s[-5:0:-9] '5'
7) >>> s[:0:-1] '987654321'
1) Ex: print("Durga"+"Soft")==>DurgaSoft
2) print("DurgaSoft"*2)==>DurgaSoftDurgaSoft
Note:
--------
-->To use + operator for strings, compulsory both arguments should be str type.
-->To use * operator for strings, compulsory one argument should be str and other
argument should be int.
1) s="mahesh"
2) print(lens(s))==>6
71 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Q: w.a.p to access each character of string in forward direction and backward direction by
using while loop?
Alternative ways:
------------------------
Checking Membership:
====================
-->We can check whether the character or string is the memebr of another string or not by
using in and not in operators.
72 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex:
1) s="mahesh"
2) print('m' in s)==>True
3) print('z' in s)==>False
Program:
-------------
Comparision of Strings:
=====================
-->We can use comparision operators(<, <=,>,>=) and equality operators(==, !=) for strings.
-->Comparision will be performed based on alphabatical order.
Ex:
Ex:
1) l1=["A","B","C"]
2) l2=["A","B","C"]
3) l3=l2
4) print(id(l1))==>2774045844040
5) print(id(l2))==>2774045844104
6) print(l1 is l2)==>False
7) print(l2 is l3)==>True
8) print(l1 == l2)==>True
73 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
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
Ex:
Finding Substrings:
==================
-->We can use the following 4-methods
1).find():
------------
Syn:
s.find(substring)
-->Returns index of the first occurenece of the given substring. If it is not available then we
will get -1.
74 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex:
o/p:D:\pythonclasses>py test.py
9
1
-1
24
Note:
Bydefault find() method can search total string. we can also specify the boundaries to
search.
Syn:
s.find(substring,begin,end)
Ex:
1) s="maheshdurgasunny"
2) print(s.find("a"))
3) print(s.find("a",5,15))
4) print(s.find("z",5,15))
o/p:
1
10
-1
index():
----------
index() method is exactly same as find() method except that if the specified
substring is not available then we eill get ValueError.
Ex:
1) s="python"
2) s.index("z")==>ValueError
Ex:
75 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
3) try:
4) n=s.index(subs)
5) except ValueError:
6) print("Substring is not found in main string")
7) else:
8) print("Sub string is found in main string",n)
o/p:
D:\pythonclasses>py test.py
Enter some string: learning python is easy
Enter sub string: python
Sub string is found in main string 9
D:\pythonclasses>py test.py
Enter some string: learning python is easy
Enter sub string: java
Substring is not found in main string
o/p:D:\pythonclasses>py test.py
Enter main string: abbabcabbabdefa
Enter sub string: a
Found at position 0
Found at position 3
Found at position 6
Found at position 9
Found at position 14
76 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Counting substring the given string:
================================
-->We can find the number of occurances 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.
ex:
1) s="ababababaababa"
2) print(s.count("a"))
3) print(s.count("ab"))
4) print(s.count("a",3,10))
o/p:D:\pythonclasses>py test.py
8
6
4
o/p:D:\pythonclasses>py test.py
Learning python is easy
1) s="ababababababa"
2) s1=s.replace("a","b")
3) print(s1)
o/p:D:\pythonclasses>py test.py
bbbbbbbbbbbbb
Q:String objects are immutable then how we can change the content by using replace()
method?
Once we creates string object, we can't change the content. This non changable
behaviour is nothing but immutability. If we are trying to change the content by using any
nd
77 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
method, then with those changes a new object will be created and changes won't be
happened in existing object.
Hence with replace() method also a new object got created but existing object
won't be changed.
Ex:
1) s="abab"
2) s1=s.replace("a","b")
3) print(s, " is available at: ",id(s))
4) print(s1, " is available at: ",id(s1))
o/p:D:\pythonclasses>py test.py
abab is available at: 2086080298880
bbbb is available at: 2086080295296
-->In the above example, original object is available and we can see new object which was
created because of replace() method.
Splitting of string:
=================
-->We can split the given string according to specified separator by using split() method.
Syn: l=s.split(separator)
-->The default separator is space. The return type of split() method is list.
Ex:
o/p:D:\pythonclasses>py test.py
['Durga', 'Software', 'Solutions']
Durga
Software
Solutions
Ex:
1) s="29-09-2018"
2) l=s.split('-')
3) for x in l:
4) print(x)
o/p:D:\pythonclasses>py test.py
29
78 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
09
2018
Joining of Strings:
================
-->We can join a group of strings (list or tuple) wrt the given separator.
Syn: s=separator.join(group of strings)
Ex:
1) t=('sunny','bunny','chinny')
2) s='-'.join(t)
3) print(s)
o/p:sunny-bunny-chinny
Ex:
1) l=['hyderabd','bangalore','chennai','dubai']
2) s=':'.join(l)
3) print(s)
o/p:hyderabd:bangalore:chennai:dubai
o/p:D:\pythonclasses>py test.py
LEARNING PYTHON IS VERY EASY
nd
79 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
learning python is very easy
LEARNING pYTHON IS VERY eASY
Learning Python Is Very Easy
Learning python is very easy
Ex:
o/p:D:\pythonclasses>py test.py
True
False
True
2).isalpha():Returns True if all the characters are only alphabate symbols(a-z, A-Z)
4).islower():Returns True if all the characters are lower case alphabet symbols.
5).isupper():Returns True if all the characters are upper case alphabet symbols.
1) print('Mahesh3333'.isalnum())#True
2) print('Mahesh3333'.isalpha())#False
3) print('Mahesh'.isalpha())#True
4) print('Mahesh'.isdigit())#False
80 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
5) print('123456'.isdigit())#True
6) print('abc'.islower())#True
7) print('abc123'.islower())#True
8) print('ABC'.isupper())#True
9) print('Learning Python is Easy'.istitle())#False
10) print('Learning Python Is Easy'.istitle())#True
11) print(' '.isspace())#True
Demo Program:
==============
o/p:D:\pythonclasses>py test.py
Enter any character:9
Alpha Numeric Character
It is a digit
D:\pythonclasses>py test.py
Enter any character:a
Alpha Numeric Character
Alphabet Character
Lower case alphabet character
D:\pythonclasses>py test.py
Enter any character:A
Alpha Numeric Character
Alphabet Character
Upper case alphabet character
81 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
D:\pythonclasses>py test.py
Enter any character:
It is space character
D:\pythonclasses>py test.py
Enter any character:#
It is a special character
1) name="Mahesh"
2) salary=10000
3) age=50
4) print("{}'s salary is {} and his age is {}".format(name,salary,age))
5) print("{0}'s salary is {1} and his age is {2}".format(name,salary,age))
6) print("{x}'s salary is {y} and his age is {z}".format(z=age,y=salary,x=name))
o/p:
Mahesh's salary is 10000 and his age is 50
Mahesh's salary is 10000 and his age is 50
Mahesh's salary is 10000 and his age is 50
1st way:
-----------
2nd way:
------------
82 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
3rd way:
------------
4th way:
------------
nd
83 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Q: w.a.p to print characters at odd position ans even position for the given string.
1stway:
-----------
2nd way:
-------------
1) s1='mahesh'
2) s2='durga'
3) o/p:mdauhregsah
4)
5) s1=input("Enter First String: ")
6) s2=input("Enter Second String: ")
7) output=''
8) i,j=0,0
9) while i<len(s1) or j<len(s2):
10) if i<len(s1):
11) output=output+s1[i]
12) i=i+1
13) if j<len(s2):
14) output=output+s2[j]
15) j+=1
16) print(output)
84 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Q: w.a.p to sort the characters of the string and first alphabet symbols followed by
numeric values.
i/p: B4A1D3
o/p: ABD134
85 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
9) print(output)
Q:w.a.p to remove the duplicate characters from the given input string?
i/p:ABCDCDEADDB
o/p:ABCDE
1way:
--------
2nd way:
------------
Q:w.a.p to find the occurences of each character present in the given string.
i/p:ABCDCBAB
o/p:A=2, B=3, C=2, D=1
1) s=input("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
8) for k,v in d.items():
9) print("{}={}".format(k,v))
1) d={100:'mahesh',200:'durga',300:'sunny'}
2) print(d.keys())
3) for k,v in d.items():
4) print("{}={}".format(k,v))
86 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
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 is preserved.
-->Duplicates 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 the list elements will be palced with in square brackets and with comma separator.
-->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 +ve and -ve indexes. +ve index means from left to right where as
-ve index means right to left.
Ex:
1) l=[10,"A","B",20,30,True]
2)
3) -6 -5 -4 -3 -2 -1
4) 10 A B 20 30 True
5) 0 1 2 3 4 5
1) list=[ ]
2) print(list)
3) print(type(list))
1) list=[10,20,30,40]
1) list=eval(input("Enter List:"))
2) print(list)
3) print(type(list))
87 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
4).with list() function:
1) l=list(range(10))
2) print(l)
3) print(type(l))
Ex:
1) s="mahesh"
2) l=list(s)
3) print(l)
Note:
Sometimes we can create list inside another list, such type of lists are called as
nested lists.
Ex: [10,20,[30,40]]
1) list=[10,20,30,40]
2)
3) print(list[0])==>10
4) print(list[-1])==>40
5) print(list[10])==>List index out of range
88 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
stop-->It indicates the index where slice has to end.
default value is max alloed index of lisr i.e length of the list.
step-->increment value
default value is 1.
Ex:
1) n=[1,2,3,4,5,6,7,8,9,10]
2) print(n[2:7:2])
3) print(n[4::2])
4) print(n[3:7])
5) print(n[8:2:-2])
6) print(n[4:100])
o/p:D:\pythonclasses>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 create a list object, we can modify its content. Hence list objects are mutable.
Ex:
1) n=[10,20,30,40]
2) print(n)
3) n[1]=333
4) print(n)
o/p:[10,20,30,40]
[10,333,30,40]
1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) i=0
3) while i<len(n):
89 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
4) print(n[i])
5) i=i+1
1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) for i in n:
3) print(i)
1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) for i in n:
3) if i%2==0:
4) print(i)
1) l=["A","B","C"]
2) x=len(l)
3) for i in range(x):
4) print(l[i], "is available at +ve index: ",i,"and at -ve index: ",i-x)
o/p:D:\pythonclasses>py test.py
A is available at +ve index: 0 and at -ve index: -3
B is available at +ve index: 1 and at -ve index: -2
C is available at +ve index: 2 and at -ve index: -1
1) l=[10,20,30,40]
2) len(l)==>4
2.count():
It returns the number of occurences of specified item in the list
90 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex:
1) n=[1,2,2,2,2,3,3]
2) print(n.count(1))==>1
3) print(n.count(2))==>4
4) print(n.count(3))==>2
3.index():
It returns index of first occurance of the specified element.
Ex:
1) l=[1,2,2,3,3,4]
2) print(l.index(1))==>0
3) print(l.index(2))==>1
4) print(l.index(3))==>3
5) print(l.index(4))==>5
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.
1) >>> l=[ ]
2) >>> l [ ]
3) >>> l.append("A")
4) >>> l.append("B")
5) >>> l.append("C")
6) >>> l ['A', 'B', 'C']
Ex: To add all elements to list upto 100 which are divisible by 10
1) list=[ ]
2) for i in range(101):
3) if i%10==0:
4) list.append(i)
5) print(list)
o/p:D:\pythonclasses>py test.py
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
91 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
2).insert() function:
---------------------------
To insert an item at specified index position.
Ex:
1) >>> n=[1,2,3,4]
2) >>> n.insert(1,333)
3) >>> n [1, 333, 2, 3, 4]
Ex:
1) >>> n=[1,2,3,4]
2) >>> n.insert(10,777)
3) >>> n.insert(-10,999)
4) >>>print(n) [999, 1, 2, 3, 4, 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.
3).extend() function:
-----------------------------
-->To add all items of one list to another list.
Syn: l1.extend(l2)
-->All items present in l2 will be added to l1.
Ex:
1) order1=["Chicken","Mutton","Fish"]
2) order2=["RC","KF","FO"]
3) order1.extend(order2)
4) print(order1)
o/p:D:\pythonclasses>py test.py
['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']
92 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex:
1) order=["Chicken","Mutton","Fish"]
2) order.extend("mushroom")
3) print(order)
o/p:D:\pythonclasses>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 occurence will be removed.
Ex:
1) n=[10,20,30,10,30]
2) n.remove(10)
3) print(n)
o/p:D:\pythonclasses>py test.py
[20, 30, 10, 30]
-->If the specified item not present in the list we will get ValueError
Ex:
1) n=[10,20,30]
2) n.remove(50)
3) print(n)
Note:
Hence before using remove() method first we have to check specified element present in
the list or not by using in operator.
Ex:
1) l=[10,20,30,40,10,30]
2) x=int(input("Enter element to be removed:"))
3) if x in l:
4) l.remove(x)
5) print("Removed successfully...")
6) else:
7) print("Specified element is not available")
93 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
5).pop() function:
------------------------
-->It removes and returne the last element of the list.
-->This is only the function which manipulates list and returns some element.
Ex:
1) n=[10,20,30,40]
2) print(n.pop())
3) print(n.pop())
4) print(n)
o/p:D:\pythonclasses>py test.py
40
30
[10, 20]
-->If the list is empty then pop() function raises indexerror.
Ex:
1) n=[ ]
2) print(n.pop())
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.
1) n=[10,20,30,40,50,60]
2) print(n.pop())#60
3) print(n.pop(1))#20
4) print(n.pop(10))
o/p:D:\pythonclasses>py test.py
60
20
IndexError: pop index out of range
94 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Differences between remove() and pop():
remove() pop()
1.We can use to remove specified 1.We can use to remove last element
element from the list. from the list.
2.It can't return any value. 2.It returned removed element.
3.If specified element not available then 3.If list is empty then we will get an
we wilget ValueError. error.IndexError.
Note:
List objects are dynamic i.e based on our requirement we can increase and
decrease the size.
append(),insert(),extend()==>For increasing size/growable nature
remove(),pop()==>For decreasing size/shrinking nature
1) n=[10,20,30,40]
2) n.revrse()
3) print(n)
o/p: [40,30,20,10]
2.sort() function:
In list by default insertion order is preserved. If we want to sort the elements of list
according to default natural sorting order then we should go for sort() method.
Ex:
1) n=[20,10,40,30]
2) n.sort()
3) print(n)
o/p:[10,20,30,40]
95 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex:
1) n=["Banana","Cat","Apple"]
2) n.sort()
3) print(n)
1) n=[20,10,"B","A"]
2) n.sort()
3) print(n)
Note: In python-2 list contains both numbers and strings then sort() function first sort
numbers followed by strings
Ex:
1) n=[20,10,"B","A"]
2) n.sort()
3) print(n)
o/p:[10,20,"A","B"]
-->But in python-3 it is invalid.
1) n=[10,30,20,40]
2) n.sort()
3) print(n)==>[10,20,30,40]
4) n.sort(reverse=True)
5) print(n)==>[40,30,2010]
6) n.sort(reverse=False)
7) print(n)==>[10,20,30,40]
96 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Aliasing and cloning of List objects:
================================
The process of giving another reference variable to the existing list is called as
aliasing.
Ex:
1) x=[10,20,30,40]
2) y=x
3) y[1]=333
4) print(x)
5) print(y)
o/p:D:\pythonclasses>py test.py
[10, 333, 30, 40]
[10, 333, 30, 40]
-->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.
-->To overcome this problem we should go for cloning.
-->The process of creating exactly duplicate independent object is called as cloning.
-->We can implement cloning by using slice operator or by using copy() function.
1) x=[10,20,30,40]
2) y=x[:]
3) y[1]=333
4) print(x)
5) print(y)
o/p:D:\pythonclasses>py test.py
[10, 20, 30, 40]
[10, 333, 30, 40]
1) x=[10,20,30,40]
2) y=x.copy()
3) y[1]=333
4) print(x)
nd
97 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
5) print(y)
o/p:D:\pythonclasses>py test.py
[10, 20, 30, 40]
[10, 333, 30, 40]
1).Contactination operator(+):
We can use + to concatinate 2 lists into a single list.
Ex:
1) a=[10,20,30]
2) b=[40,50,60]
3) c=a+b
4) print("c:",c)
o/p:D:\pythonclasses>py test.py
c: [10, 20, 30, 40, 50, 60]
Ex:
1) a=[10,20,30]
2) b=[40,50,60]
3) c=a.extend(b)
4) print("a:",a)
5) print("b:",b)
6) print("c:",c)
o/p:D:\pythonclasses>py test.py
a: [10, 20, 30, 40, 50, 60]
b: [40, 50, 60]
c: None
Note:
To use + operator compulsory both arguments should be list objects, otherwise we will
get an error.
98 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex:
c=a+40==>TypeError: can only concatenate list (not "int") to list
c=a+[40]==>valid
2).Repetition operator(*):
-----------------------------------
We can use repetition operator * to repeat the elements of list specified number of
times.
Ex:
1) x=[10,20,30]
2) y=x*3
3) print(y)==>[10,20,30,10,20,30]
1) x=["Dog","Cat","Rat"]
2) y=["Dog","Cat","Rat"]
3) z=["DOG","CAT","RAT"]
4) print(x==y)==>True
5) print(x==z)==>False
6) print(x!=z)==>True
Note:
Whenever we are using relational operator(<,<=,>,>=) between list objects, only first
element comparision will be performed.
Ex:
1) x=[50,40,20]
2) y=[10,20,30,40,50,60]
3) print(x>y)==>True
4) print(x>=y)==>True
5) print(x<y)==>False
6) print(x<=y)==>False
Ex:
1) x=["Dog","Cat","Rat"]
2) y=["Rat","Cat","Dog"]
3) print(x>y)==>False
4) print(x>=y)==>False
5) print(x<y)==>True
99 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
6) print(x<=y)==>True
Membership operators:
====================
We can check whether element is a memeber of the list or not by using
memebership operators.
-->in operator
-->not in operator
clear() function:
-----------------------
We can use clear() function to remove all elements of list.
Ex:
1) n=[10,20,30,40]
2) print(n)
3) n.clear()
4) print(n)
o/p:D:\pythonclasses>py test.py
[10, 20, 30, 40]
[]
Nested Lists:
============
Sometimes we can take one list inside another list. Such type of lists are called as
nested lists.
Ex:
1) n=[10,20,[30,40]]
2) print(n)
3) print(n[0])
4) print(n[1])
5) print(n[2][0])
6) print(n[2][0])
o/p:D:\pythonclasses>py test.py
[10, 20, [30, 40]]
10
20
30
40
100 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Note:
We can access nested list elements by using index just like accessing multi
dimensional array elements.
1) n=[[10,20,30],[40,50,60],[70,80,90]]
2) print(n)
3) print("Elements by row wise:")
4) for r in n:
5) print(r)
6) print("Elements by Matrix style:")
7) for i in range(len(n)):
8) for j in range(len(n[i])):
9) print(n[i][j],end=' ')
10) print()
o/p:D:\pythonclasses>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
101 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
List Comprehensions
It is very easy and compact way of creating list objects from any iterable objects (like
list,tuple,dict,range etc...) based on some condition.
Syn:
list=[expression for items in list if condition]
Ex: Print first 10-numbers squares in list format.
o/p:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Normal program:
-----------------------
1) l=[ ]
2) for x in range(11):
3) l.append(x*x)
4) print(l)
By using comprehensions:
-------------------------------------
print [2 4 8 16 32]
--------------------------
1) words=["Chiranjeevi","Nag","Venkatesh","Balaiah"]
2) l=[x[0] for x in words]
3) print(l)
102 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex:
----
1) num1=[10,20,30,40]
2) num2=[30,40,50,60]
3) num3=[x for x in num1 if x not in num2]
4) print(num3)
5) num4=[x for x in num1 if x in num2]
6) print(num4)
Ex:
1) i/p: durgasoftwaresolutions
2) ['u','a','o','e','i']
3) vowels=['a','e','i','o','u']
4) word=input("Enter the word to search for vosels:")
5) found=[]
6) for letter in word:
7) if letter in vowels:
8) if letter not in found:
9) found.append(letter)
10) print(found)
103 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Tuple Data Structure
-->Tuple is exactly same as List except that it is immutable. i.e once we create tuple object,
we can't perform any changes in that object.
-->Hence tuple is read only version of list.
-->If our data is fixed and never changes then we should go for tuple.
-->Insertion order is preserved.
-->Duplicates are allowed.
-->Heterogeneous objects are allowed.
-->We can preserve insertion order and we can differentiate duplicate objects by using
index. Hence index will play very important role in Tuple also.
-->We can represent tuple elements within parenthesis and with comma separator.
Parenthesis are optional but recommended to use.
Ex:
1. t=10,20,30,40
2. print(t)
3. print(type(t))
o/p:D:\pythonclasses>py test.py
(10, 20, 30, 40)
<class 'tuple'>
t=()
print(type(t))==>tuple
Note: We have to take special care about single valued tuple. COmpulsory the value
should ends with comma, otherwise it is not treated as tuple.
Ex:
1. t=10
2. print(t)
3. print (type(t))
o/p:D:\pythonclasses>py test.py
10
<class 'int'>
104 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex:
1. t=10,
2. print(t)
3. print (type(t))
o/p:D:\pythonclasses>py test.py
(10,)
<class 'tuple'>
Q:Which of the following are valid:
1.t=()==>V
2.t=10,20,30,40==>V
3.t=10==>Invalid
4.t=10,==>V
5.t=(10)==>Invalid
6.t=(10,)==>V
7.=t=(10,20,30)==>V
Tuple Creation:
---------------------
1.t=():
Creation of empty tuple
2.t=(10,) or t=10,
Creation of single valued tuple, paranthesis are optional, should ends with comma.
3.t=10,20,30 or t=(10,20,30)
Creatin of multiple values tupl & parenthesis are optional.
1. l=[10,20,30,40]
2. t=tuple(l)
3. print(t)
4. print(type(t))
o/p:D:\pythonclasses>py test.py
(10, 20, 30, 40)
<class 'tuple'>
Ex:
1. t=tuple(range(10,20,2))
2. print(t)
105 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
o/p:D:\pythonclasses>py test.py
(10, 12, 14, 16, 18)
1. t=(10,20,30,40)
2. print(t[0])==>10
3. print(t[-1])==>40
4. print(t[100])==>IndexError
1. t=(10,20,30,40,50,60)
2. print(t[2:5])
3. print(t[2:100])
4. print(t[::2])
o/p:
(30, 40, 50)
(30, 40, 50, 60)
(10, 30, 50)
Tuple Vs immutability:
====================
-->Once we create tuple, we can't change its content.
-->Hence tuple objects are immutable.
Ex:
1. t=(10,20,30,40,50)
2. t[1]=60==>TypeError: 'tuple' objects does not support item assignment.
1.concatination operator(+):
1. t1=(10,20,30,40)
2. t2=(10,20,50,60)
3. t3=t1+t2
106 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
4. print(t3)
1. t1=(10,20,30,40)
2. t2=t1*2
3. print(t2)
1. t=(10,20,30,40)
2. len(t)==>4
2.count():
To return number of occurences of given element in the tuple.
Ex:
1. t=(10,20,30,10,10)
2. t.count(10)==>3
3).index():
-->Returns index of first occurence of the given element.
-->If the specified element is not available then we will get ValueError.
Ex:
1. t=(10,20,30,30,10,40)
2. t.index(30)==>2
3. t.index(50)==>ValueError
4.sorted():
To sort elements based on default natural sorting order.
Ex:
1. t=(40,20,50,10,30)
2. t1=sorted(t)
3. print(t)
107 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
4. print(t1)
o/p:
(40, 20, 50, 10, 30)
[10, 20, 30, 40, 50]==>After sorting it will return as list
Ex:
1. t=(40,20,50,10,30)
2. t1=tuple(sorted(t))
3. print(t)
4. print(t1)
o/p:
(40, 20, 50, 10, 30)
(10, 20, 30, 40, 50)
Ex:
1. t1=sorted(t,reverse=True)
2. print(t1)==>[50,40,30,20,10]
1. t=(40,20,50,10,30)
2. print(min(t))==>10
3. print(max(t))==>50
Ex:
1. t="Mahesh"
2. print(min(t))==>M
3. print(max(t))==>s
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
108 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex:
1. t1=(10,20,30)
2. t2=(40,50,50)
3. t3=(10,20,30)
4. print(cmp(t1,t2))#-1
5. print(cmp(t1,t3))#0
6. print(cmp(t2,t3))#+1
1. a=10
2. b=20
3. c=30
4. d=40
5. t=a,b,c,d
6. print(t)
1. t=(10,20,30,40)
2. a,b,c,d=t
3. print("a=",a,"b=",b,"c=",c,"d=",d)
o/p:
a= 10 b= 20 c= 30 d= 40
Note:
At the time of tuple unpacking the number if variables and number of values
should be same. otherwise we will get an error.
Ex:
1. t=(10,20,30,40)
2. a,b,c=t
3. print("a=",a,"b=",b,"c=",c)
109 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
o/p:ValueError: too many values to unpack (expected 3)
Tuple Comprehension:
--------------------------------
Tuple comprehension is not supported by python.
Ex:
t=(x**2 for x in range(1,6))
-->Here we are not getting tuple object and we are getting generator object
Ex:
o/p:
<class 'generator'>
1
4
9
16
25
Q: w.a.p to take tuple of numbers from the keyboard and print sum and average?
o/p:
Enter Tuple Of Numbers:(10,20,30)
The Sum is: 60
The Average : 20.0
110 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Difference between List and Tuple
List Tuple
1.List a group of comma separated values 1.Tuple is a group of comma
within square brackets and square brackets separated values within parenthesis
are mandatory. parenthesis are optional.
Ex: l=[10,20,30] Ex: t=(10,20,30) or t=10,20,30
2.List objects are mutable i.e once we 2.Tuple objects are immutable i.e
creates list object we can perform any once we creates tuple objects we
changes in that object. can't change it content.
ex:l[1]=50 Ex:t[1]=50-->ValueError
3.If the content is not fixed and keep on 3.If the content is fixed and never
changing then we should go for list. changes then we should go for tuple.
4.Comprehensions are available. 4.There is no comprehensions.
111 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Set Data Structure
-->If we want to represent a group of unique values as a single entity then we should go
for set.
-->Duplicates are not allowed.
-->Insertion order is not preserved. But we can sort the elements.
-->Indexing and slicing not allowed for the set.
-->Heterogeneous elements are allowed.
-->Set objects are mutable i.e once we create set object we can perform any changes in
that object based on our requirement.
-->We can represent set elements with curly braces and with comma separation.
-->We can apply mathematical operations like union, intersection, difference etc on set
objects.
1. s={10,20,30,40}
2. print(s)
3. print(type(s))
o/p:
{40,10,20,30}
<class 'set'>
-->We can create set objects by using set() function.
s=set(any sequence)
Ex:
l=[10,20,30,40,10,20]
s=set(l)
print(s)
Ex:
s=set(range(5))
print(s)
s={ }==>It treated as dictionary but not an empty set.
Ex:
s={ }
print(type(s))
o/p: <class 'dict'>
112 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex:
1. s=set()
2. print(s)
3. print(type(s))
o/p:
set()
<class 'set'>
1. s={10,20,30}
2. s.add(40)
3. print(s)
2.update(x,y,z):
-->To add mutiple items to the set.
-->Arguments are not individual elements and these are iterable elements like list,
range etc..
-->All elements present in the given iterable objects will be added to the set.
Ex:
1. s={10,20,30}
2. l=[40,50,60]
3. s.update(l,range(5))
4. print(s)
113 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
3.copy():
-->Returns copy of the set
-->It is cloned object.
Ex:
1. s={10,20,30}
2. s1=s.copy()
3. print(s1)
4.pop():
It removes and returns some random element from the set.
Ex:
1. s={10,20,30,40}
2. print(s)
3. print(s.pop())
4. print(s)
o/p:
{40, 10, 20, 30}
40
{10, 20, 30}
5.remove(x):
-->It removes specified element from the set.
-->If the specified element not present in the set then we will get KeyError.
Ex:
1. s={40,20,30,10}
2. s.remove(30)
3. print(s)==>{40,20,10}
4. s.remove(50)==>KeyError:50
6.discard(x):
-->It removes specified element from the set.
-->If the specified element not present in the set then we won't get any error.
Ex:
1. s={40,20,30,10}
2. s.discard(30)
3. print(s)==>{40,20,10}
4. s.discard(50)
5. print(s)==>{40,20,30,10}
114 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
7.clear():
-->To remove all elements from the set.
Ex:
1. s={10,20,30}
2. print(s)
3. s.clear()
4. print(s)
o/p:
{10,20,30}
set()
Ex:
1. x={10,20,30,40}
2. y={30,40,50,60}
3. print(x.union(y))#{40, 10, 50, 20, 60, 30}
4. print(x|y) #{40, 10, 50, 20, 60, 30}
2).intersection():
x.intersection(y) or x & y
-->Returns common elements present in both x and y
Ex:
1. x={10,20,30,40}
2. y={30,40,50,60}
3. print(x.intersection(y))#{40, 30}
4. print(x&y)#{40, 30}
3).difference():
x.difference(y) or x-y
-->Returns the elements present in x but not in y.
Ex:
1. x={10,20,30,40}
2. y={30,40,50,60}
3. print(x.difference(y))#{10, 20}
4. print(x-y)#{10, 20}
115 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
5. print(y-x)#{50, 60}
4).symmetric_difference():
x.symmetric_difference(y) or x^y
-->Returns element present in either x or y but not in both.
Ex:
1. x={10,20,30,40}
2. y={30,40,50,60}
3. print(x.symmetric_difference(y))#{10, 50, 20, 60}
4. print(x^y)#{10, 50, 20, 60}
1. s=set("mahesh")
2. print(s)
3. print('m' in s)
4. print('z' in s)
Set comprehension:
----------------------------
-->set comprehension is possible.
1. s={10,20,30,40}
2. print(s[0]) TypeError: 'set' object does not support indexing
3. print(s[1:3]) TypeError: 'set' object does not support indexing
116 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Q: w.a.p to eliminate duplicates present in the list.
Approach-1:
Approach-2:
o/p:
D:\pythonclasses>py test.py
Enter List Of Values:[10,20,20,10,30,40]
[10, 20, 30, 40]
o/p:D:\pythonclasses>py test.py
Enter word to serach for vowels : mahesh
The different vowels present in mahesh are: {'e', 'a'}
117 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
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 key-value pairs then we should go for
dictionary.
Ex:
rollno-----name
phone number---address
ip address----domain name
Note:
In C++ and java Dictionaries are known as "Map" where as in perl and Ruby it is
knonw as "Hash"
1. d={}
2. d1=dict()
3. print(type(d))
4. d[100]="Mahesh"
5. d[200]="Durga"
6. d[300]="Sunny"
7. print(d)#{100: 'Mahesh', 200: 'Durga', 300: 'Sunny'}
-->If we know the data in advance then we can create dictionary as follows
d={100:'mahesh',200:'durga',300:'sunny'}
d={key:value,key:value}
118 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
How to access data from the dictionary?
--------------------------------------------------------
-->We can access data by using index.
d={100:"mahesh",200:"durga",300:"sunny"}
print(d[100])==>mahesh
print(d[300])==>Sunny
-->We can prevent this by checking whether key is already available or not by using
has_key() function or by using in operator.
-->But has_key() function is available in python-2 but not in python-3. Hence compulsory
we have to use in operator.
Ex:
if 400 in d:
print(d[400])
Q: w.a.p to enter name and percentage marks in a dictionary and display information on
the screen.
1. rec={ }
2. n=int(input("Enter Number Of Students: "))#3
3. i=1
4. while i<=n:
5. name=input("Enter Student Name:")
6. marks=int(input("Enter % of Marks:"))
7. rec[name]=marks
8. i=i+1
9. print("Name of the student","\t","% of marks")
10. for x in rec:
11. print("\t",x,"\t\t",rec[x])
o/p:D:\pythonclasses>py test.py
Enter Number Of Students: 3
Enter Student Name:Mahesh
Enter % of Marks:90
Enter Student Name:Durga
Enter % of Marks:98
119 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Enter Student Name:Sunny
Enter % of Marks:100
Name of the student % of marks
Mahesh 90
Durga 98
Sunny 100
1. d={100:"mahesh",200:"durga",300:"sunny"}
2. print(d)
3. d[400]="bunny"
4. print(d)
5. d[100]="chinny"
6. print(d)
o/p:D:\pythonclasses>py test.py
{100: 'mahesh', 200: 'durga', 300: 'sunny'}
{100: 'mahesh', 200: 'durga', 300: 'sunny', 400: 'bunny'}
{100: 'chinny', 200: 'durga', 300: 'sunny', 400: 'bunny'}
1. d={100:"mahesh",200:"durga",300:"sunny"}
2. print(d)
3. del d[300]
4. print(d)
5. del d[400]
6. print(d)
o/p:D:\pythonclasses>py test.py
{100: 'mahesh', 200: 'durga', 300: 'sunny'}
{100: 'mahesh', 200: 'durga'}
KeyError: 400
120 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
d.clear():
------------
To remove all entries from the dictionary.
Ex:
1. d={100:"mahesh",200:"durga",300:"sunny"}
2. print(d)
3. d.clear()
4. print(d)
o/p:D:\pythonclasses>py test.py
{100: 'mahesh', 200: 'durga', 300: 'sunny'}
{}
del d:
--------
To delete total dictionary. Now we can't access d.
Ex:
1. d={100:"mahesh",200:"durga",300:"sunny"}
2. print(d)
3. del d
4. print(d)
o/p:D:\pythonclasses>py test.py
{100: 'mahesh', 200: 'durga', 300: 'sunny'}
NameError: name 'd' is not defined
121 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
o/p:D:\pythonclasses>py test.py
{100: 'mahesh', 200: 'durga'}
{100: 'Mahesh', 200: 'Durga'}
{100: 'MAHESH', 200: 'DURGA'}
2).len():
Returns the number of items in the dictionary.
3).clear():
To remove all the 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.
Ex:
1. d={100:"mahesh",200:"durga",300:"sunny"}
2. print(d[100])#mahesh
3. print(d[400])#KeyError:400
4. print(d.get(300))#sunny
5. print(d.get(400))#None
6. print(d.get(100,"Guest"))#mahesh
7. print(d.get(400,"Guest"))#Guest
5).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.
Ex:
1. d={100:"mahesh",200:"durga",300:"sunny"}
2. print(d)
3. print(d.pop(300))
4. print(d)
5. d.pop(400)
122 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
o/p:D:\pythonclasses>py test.py
{100: 'mahesh', 200: 'durga', 300: 'sunny'}
sunny
{100: 'mahesh', 200: 'durga'}
KeyError: 400
6).popitem():
It removes an arbitrary item(key-value) from the dictionary and return it.
Ex:
1. d={100:"mahesh",200:"durga",300:"sunny"}
2. print(d)
3. print(d.popitem())
4. print(d)
o/p:D:\pythonclasses>py test.py
{100: 'mahesh', 200: 'durga', 300: 'sunny'}
{100: 'mahesh', 200: 'durga'}
7).keys():
It returns all keys associated with dictionary.
Ex:
1. d={100:"mahesh",200:"durga",300:"sunny"}
2. print(d.keys())
3. for k in d.keys():
4. print(k)
o/p:D:\pythonclasses>py test.py
dict_keys([100, 200, 300])
100
200
300
8).values():
It returns all values associated with dictionary.
Ex:
1. d={100:"mahesh",200:"durga",300:"sunny"}
2. print(d.values())
123 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
3. for v in d.values():
4. print(v)
o/p:D:\pythonclasses>py test.py
dict_values(['mahesh', 'durga', 'sunny'])
mahesh
durga
sunny
9).items():
It returns list of tupes represented key-value pairs.
[(k,v),(k,v),(k,v)]
Ex:
1. d={100:"mahesh",200:"durga",300:"sunny"}
2. for k,v in d.items():
3. print(k,"--",v)
o/p:D:\pythonclasses>py test.py
100 -- mahesh
200 -- durga
300 -- sunny
10).copy():
To create exactly duplicate dictionary (cloned copy)
Ex:
1. d={100:"mahesh",200:"durga",300:"sunny"}
2. d1=d.copy()
3. print(id(d))
4. print(id(d1))
o/p:D:\pythonclasses>py test.py
2791188556752
2791188556824
11).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.
Ex:
1. d={100:"mahesh",200:"durga",300:"sunny"}
2. print(d.setdefault(400,"bunny"))
3. print(d)
124 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
4. print(d.setdefault(100,"bunny"))
5. print(d)
o/p:D:\pythonclasses>py test.py
bunny
{100: 'mahesh', 200: 'durga', 300: 'sunny', 400: 'bunny'}
mahesh
{100: 'mahesh', 200: 'durga', 300: 'sunny', 400: 'bunny'}
12).update(): d.update(x)
All items in the dictionary x will added to dictionary d.
Ex:
1. d={100:"mahesh",200:"durga",300:"sunny"}
2. d1={'a':"apple",'b':"banana",'c':"cat"}
3. d.update((d1))
4. print(d)
5. d.update([(333,"A"),(999,"B")])
6. print(d)
o/p:D:\pythonclasses>py test.py
{100: 'mahesh', 200: 'durga', 300: 'sunny', 'a': 'apple', 'b': 'banana', 'c': 'cat'}
{100: 'mahesh', 200: 'durga', 300: 'sunny', 'a': 'apple', 'b': 'banana', 'c': 'cat', 333: 'A', 999:
'B'}
Q: w.a.p to take dictionary from the keyboard and print sum of values.
sol:
1. d=eval(input("Enter Dictionary:"))
2. s=sum(d.values())
3. print("Sum:",s)
o/p:D:\pythonclasses>py test.py
Enter Dictionary:{'A':100,'B':200,'C':300}
Sum: 600
Q:w.a.p to find number of occurances of each letter present in the given string?
sol:
125 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
7. for k,v in d.items():
8. #print(k,"occurs",v,"times")
9. print("{} occured {}".format(k,v))
o/p:D:\pythonclasses>py test.py
Enter any word:mississippi
{'m': 1, 'i': 4, 's': 4, 'p': 2}
['i', 'm', 'p', 's']
m occured 1
i occured 4
s occured 4
p occured 2
Q: w.a.p to find number of occurances of each vowel present in the given string
sol:
o/p:D:\pythonclasses>py test.py
Enter some string:abaiobeioeiaieus
a occured 3 times
e occured 3 times
i occured 4 times
o occured 2 times
u occured 1 times
Q:w.a.p to accept student name and marks from the keyboard and creates a dictionary,
also display student marks by taking student name as input?
126 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
9) name=input("Enter student name to get marks:")
10) marks=d.get(name,-1)
11) if marks==-1:
12) print("Student not found")
13) else:
14) print("The marks of",name,"are",marks)
15) option=input("Do you want to find another student marks[Yes|No]")
16) if option=="No":
17) break
18) print("Thanks for using our application")
o/p:D:\pythonclasses>py test.py
Enter the number of students:3
Enter student name:durga
Enter marks:90
Enter student name:mahesh
Enter marks:98
Enter student name:sunny
Enter marks:100
{'durga': '90', 'mahesh': '98', 'sunny': '100'}
Enter student name to get marks:sunny
The marks of sunny are 100
Do you want to find another student marks[Yes|No]Yes
Enter student name to get marks:bunny
Student not found
Do you want to find another student marks[Yes|No]Yes
Enter student name to get marks:mahesh
The marks of mahesh are 98
Do you want to find another student marks[Yes|No]No
Thanks for using our application
Dictionary comprehension:
---------------------------------------
-->Comprehension concept applicable for dictionary also.
Ex:
o/p:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
127 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
FUNCTIONS
If a group of statements is repeatedly required then it is not recommended to
write these statements every time separately. 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 re-writting. THis unit is nothing but a function.
-->The main advantage of functions is code -Re-usability.
Note:In other languages functions are known as methods, procedures,subroutines etc...
1).Built in Functions:
------------------------------
The functions which are coming along with python s/w automatically, are called as
built in functions or pre-defined functions.
Ex:
id(), type(), input(), eval().........
1. def wish():
2. print("Hello gud mng.............")
3. wish()
128 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
4. wish()
5. wish()
o/p:D:\pythonclasses>py test.py
Hello gud mng.............
Hello gud mng.............
Hello gud mng.............
Parameters:
-----------------
Parameters are inputs to the function. If a function contains parameters, then at
the time of calling, compulsory we should provide values, otherwise we will get error.
Ex: write a function to take name of the student as input and print wish message by name
1. def wish(name):
2. print("Hello", name," gud mng.............")
3. wish("Durga")
4. wish("Guest")
o/p:D:\pythonclasses>py test.py
Hello Durga gud mng.............
Hello Guest gud mng.............
Ex: write a function to take number as input and print its square value.
1. def squareit(number):
2. print("the square of", number," is:",number**2)
3. squareit(4)
4. squareit(5)
o/p:D:\pythonclasses>py test.py
the square of 4 is: 16
the square of 5 is: 25
Return Statement:
--------------------------
Function can take input values as parameters and executes business logic, and
returns output to the caller with the return statement.
1. def add(x,y):
2. return x+y
3. result=add(10,20)
129 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
4. print("The sum is:",result)
5. print("The sum is:",add(10,20))
o/p:D:\pythonclasses>py test.py
The sum is: 30
The sum is: 30
-->If we are not writing return statement then default return value is None.
Ex:
1. def f1():
2. print("hello")
3. f1()
4. print(f1())
o/p:D:\pythonclasses>py test.py
hello
hello
None
1. def even_odd(num):
2. if num%2==0:
3. print(num,"is even number")
4. else:
5. print(num,"is odd number")
6. even_odd(10)
7. even_odd(15)
o/p:D:\pythonclasses>py test.py
10 is even number
15 is odd number
1. def fact(num):
2. result=1
3. while num>=1:
4. result=result*num
5. num=num-1
6. return result
7. print(fact(5))
8. for i in range(1,5):
9. print("The factorial ",i,"is",fact(i))
130 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
o/p:D:\pythonclasses>py test.py
120
The factorial 1 is 1
The factorial 2 is 2
The factorial 3 is 6
The factorial 4 is 24
Ex:
1. def sum_sub(a,b):
2. sum=a+b
3. sub=a-b
4. return sum,sub
5. x,y=sum_sub(100,50)
6. print("sum is: ",x)
7. print("sub is: ",y)
o/p:D:\pythonclasses>py test.py
sum is: 150
sub is: 50
Ex:
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(t)
9. print(type(t))
10. print("The Results are:")
11. for i in t:
12. print(i)
o/p:D:\pythonclasses>py test.py
(150, 50, 5000, 2.0)
<class 'tuple'>
131 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
The Results are:
150
50
5000
2.0
Types of arguments:
-----------------------------
def f1(a,b):
--------
--------
---------
f1(10,20)
1.positional arguments:
----------------------------------
These are the arguments passed to function in correct positional order
Ex:
1. def sub(a,b):
2. print(a-b)
3. sub(100,200)
4. sub(200,100)
132 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
2).keyword arguments:
--------------------------------
We can pass argument values by keyword i.e by parameter name.
Ex:
1. def wish(name,msg):
2. print("Hello",name,msg)
3. wish(name="Mahesh",msg="gud mng....")
4. wish(msg="gud mng....",name="Mahesh")
o/p:D:\pythonclasses>py test.py
Hello Mahesh gud mng....
Hello Mahesh gud mng....
-->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 take keyword arguments, otherwise we will
get an error.
Ex:
1. def wish(name,msg):
2. print("Hello",name,msg)
3. wish("Mahesh","Gud Mng......")==>Valid
4. wish("Mahesh",msg="Gud Mng.....")==>Valid
5. wish(name="Mahesh","Gud Mng........")==>Invalid
3.Default argument:
----------------------------
Sometimes we can provide default values for our positional arguments
Ex:
1. def wish(name="Mahesh"):
2. print("Hello",name,"Gud Mng.....")
3. wish()
4. wish("Durga")
o/p:D:\pythonclasses>py test.py
Hello Mahesh Gud Mng.....
Hello Durga Gud Mng.....
133 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
-->If we are not passing any name then only default value will be considered.
1. def sum(*n):
2. total=0
3. for i in n:
4. total=total+i
5. print("Sum is:",total)
6. sum()
7. sum(10,20)
8. sum(10,20,30)
9. sum(10,20,30,40)
o/p:D:\pythonclasses>py test.py
Sum is: 0
Sum is: 30
Sum is: 60
Sum is: 100
Ex:
1. def f1(n1,*s):
2. print(n1)
3. for i in s:
4. print(i)
5. f1(10)
6. f1(10,20,30,40)
7. f1(10,"A",20,"B")
o/p:D:\pythonclasses>py test.py
10
10
20
30
40
134 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
10
A
20
B
Note: After variable length argument, if we are taking any other arguments then we
should provide values as keyword arguments.
Ex:
1. def f1(*s,n1):
2. for i in s:
3. print(i)
4. print(n1)
5. f1(10,20,"A",n1=30)
o/p:D:\pythonclasses>py test.py
10
20
A
30
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 **.
Syn: f1(**n)
-->We can call this function by passing any number of keyword arguments. Internally
these keyword arguments will be stored inside a dictionary.
Ex:
1. def display(**kwargs):
2. for k,v in kwargs.items():
3. print(k,"=",v)
4. display(n1=10,n2=20,n3=30)
5. display(rno=100,name="Mahesh",marks=90,subject="selenium")
o/p:D:\pythonclasses>py test.py
n1 = 10
n2 = 20
n3 = 30
rno = 100
name = Mahesh
marks = 90
subject = selenium
135 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Case Study:
==========
def f(arg1,arg2,arg3=4,arg4=8):
print(arg1,arg2,arg3,arg4)
1.f(3,2)#3 2 4 8
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'
Types of Variables:
--------------------------
Python supports two types of variables.
-->Global Variable
-->Local Variable
Global variable:
----------------------
-->The variables which are declared outside the function are called as global variables.
-->These variables can be accessed in all functions of that module.
136 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex:
1. a=10#global variable
2. def f1():
3. print('f1:',a)
4. def f2():
5. print('f2:',a)
6. f1()
7. f2()
o/p:
10
10
Local Variable:
---------------------
-->The variables which are declared inside a function are called as local variables.
-->Local variables are available only for the function in which we declared it. i.e from
outside of function we can't access.
Ex:
1. def f1():
2. a=10
3. print('f1:',a)
4. def f2():
5. print('f2:',a)
6. f1()
7. f2()
o/p:
f1: 10
NameError: name 'a' is not defined
global keyword:
----------------------
We can use global keyword for the following 2 purposes
-->To delcare global variable inside a function.
-->To make global variable available to the function so that we can perform required
modifications.
Ex:
1. a=10
2. def f1():
3. a=333
137 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
4. print('f1:',a)
5. def f2():
6. print('f2:',a)
7. f1()
8. f2()
o/p:D:\pythonclasses>py test.py
f1: 333
f2: 10
Ex:
1. a=10#global
2. def f1():
3. global a
4. a=333#local
5. print('f1:',a)
6. def f2():
7. print('f2:',a)
8. f1() f2()
9. f2() f1()
Ex:
1. def f1():
2. global a
3. a=10
4. print('f1:',a)
5. def f2():
6. print('f2:',a)
7. f1()
8. f2()
o/p:D:\pythonclasses>py test.py
f1: 10
f2: 10
Note: If the global variable and local variable having same name then we can access global
variable inside a function as follows.
138 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex:
1. a=10#global variable
2. def f1():
3. a=333#local variable
4. print('f1:',a)
5. print(globals()['a'])
6. f1()
o/p:D:\pythonclasses>py test.py
f1: 333
10
Recursive Functions:
------------------------------
A function that calls itself is known as Recursive Function.
Ex:
factorial(3):3*factorial(2)
3*2*factorial(1)
3*2*1*factorial(0)
factorial(n):n*factorial(n-1)
1. def factorial(n):
2. if n=0:
3. result=1
4. else:
5. result=n*factorial(n-1)
6. return result
7. print("Factorial of 4 is: ",factorial(4))
8. print("Factorial of 0 is: ",factorial(0))
o/p:D:\pythonclasses>py test.py
Factorial of 4 is: 24
Factorial of 0 is: 1
139 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Anonymous Functions:
=====================
-->Sometimes we can declare a function without name, such type of nameless functions
are called as anonymous functions or lamda functions.
-->The main advantage 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
1. s=lambda n:n*n
2. print("The square of 3 is:",s(3))
3. print("The square of 5 is:",s(5))
o/p:D:\pythonclasses>py test.py
The square of 3 is: 9
The square of 5 is: 25
1. s=lambda a,b:a+b
2. print("The sum of 10 and 20 is:",s(10,20))
3. print("The sum of 100 and 200 is:",s(100,200))
o/p:D:\pythonclasses>py test.py
140 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
The sum of 10 and 20 is: 30
The sum of 100 and 200 is: 300
o/p:D:\pythonclasses>py test.py
The biggest of 10 and 20 is: 20
The biggest of 100 and 200 is: 200
Note:
Lambda function internally returns expression value and we are not required to
wrtite return statement explicitly.
Some times we can pass function as argument to another function. In such case
lambda functions are best choice.
-->We can use lambda functions very commonly with filter(), map() and reduce()
functions,bcoz these functions expect function as aegument.
1).filter function:
------------------------
We can use filter() function to filter values from the given sequence based on some
condition.
Syn:
filter(function,sequence)
-->Where function argument is responsible to perform conditional check sequence can be
list or tuple or string.
1. def isEven(n):
2. if n%2==0:
3. return True
4. else:
5. return False
6. l=[0,5,10,15,20,25,30]
7. print(type(filter(isEven,l)))
141 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
8. l1=list(filter(isEven,l))
9. print(l1)
o/p:D:\pythonclasses>py test.py
<class 'filter'>
[0, 10, 20, 30]
1. l=[0,5,10,15,20,25,30]
2. l1=list(filter(lambda x:x%2==0,l))
3. print(l1)
4. l2=list(filter(lambda x:x%2!=0,l))
5. print(l2)
o/p:D:\pythonclasses>py test.py
[0, 10, 20, 30]
[5, 15, 25]
2).map() function:
---------------------------
For every element present in the given sequenece, apply some functionality and
generate new element with the required modifications. For this requirement we should go
for map() function.
Ex: For every element present in the list perform double and generate new list of doubles
Syn:
map(function,sequenec)
-->The function can be applied on each element of sequence and generates new sequence.
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]
142 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
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]
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.
Syn:
map(lambda x,y:x*y,l1,l2)
x is from l1 and y is from l2
Ex:
1. l1=[1,2,3,4]
2. l2=[2,3,4,5]
3. l3=list(map(lambda x,y:x*y,l1,l2))
4. print(l3)
3).reduce() function:
-----------------------------
reduce() function reduces sequence of elements into a single element by applying
the specified function.
Syn:
reduce(function, sequence)
-->reduce() function present in functools module and hence we should write import
statement.
Ex:
o/p:150
143 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex:
o/p:12000000
Ex:
o/p:5050
Nested functions:
===============
Ex:
----
1. def f1():
2. def inner(a,b):
3. print("The sum:",a+b)
4. print("The average:",(a+b)/2)
5. print()
6. inner(10,20)
7. inner(20,30)
8. inner(100,200)
9. f1()
o/p:D:\pythonclasses>py test.py
The sum: 30
The average: 15.0
The sum: 50
The average: 25.0
144 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex:
----
1) def outer():
2) print("outer function started")
3) def inner():
4) print("ineer function started")
5) print("outer function returning inner function")
6) return inner
7) f1=outer()
o/p:D:\pythonclasses>py test.py
outer function started
outer function returning inner function
f1=outer()
f1()
o/p:D:\pythonclasses>py test.py
outer function started
outer function returning inner function
ineer function started
145 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Function Decorators
Decorator is a function which can take a function as a argument and extend its
functionality and returns modified function with extended functionality.
The main objective decorator function is we can extend the functionality of existing
functions without modifies that function.
Decorators help to make our code shorter and more pythonic. This concept is veryhelpful
while developing web applications with Django.
Ex:
def wish(name):
print("Hello",name,"Good morning.........")
-->This function can always print same output for any name.
Hello Mahesh Good morning.........
Hello Durga 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 with out touching wish() function by using decorator.
Ex:
----
1) def decor(func):
2) def inner(name):
3) if name=="Sunny":
4) print("Hello Sunny Bad Morning.....")
5) else:
6) func(name)
7) return inner
8) @decor
9) def wish(name):
10) print("Hello",name,"Good morning.........")
11) wish("Mahesh")
12) wish("Durga")
13) wish("Sunny")
146 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
o/p:D:\pythonclasses>py test.py
Hello Mahesh Good morning.........
Hello Durga 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 with out decorator:
----------------------------------------------------------------------------------------------
Ex:
----
1) def decor(func):
2) def inner(name):
3) if name=="Sunny":
4) print("Hello Sunny Bad Morning.....")
5) else:
6) func(name)
7) return inner
8)
9) def wish(name):
10) print("Hello",name,"Good morning.........")
11)
12) decorfunction=decor(wish)
13) wish("Mahesh") #decorator wont be executed
14) wish("Sunny") #decorator wont be executed
o/p:D:\pythonclasses>py test.py
Hello Mahesh Good morning.........
Hello Sunny Good morning.........
Ex:
-----
1) def smart_division(func):
2) def inner(a,b):
3) print("We are deviding",a,"with",b)
147 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
4) if b==0:
5) print("OOP's ..can't divide with zero")
6) else:
7) return func(a,b)
8) return inner
9)
10) @smart_division
11) def division(a,b):
12) return a/b
13) print(division(20,2))
14) print(division(20,0))
-->with decorator we won't get any error. In this casse output is:
D:\pythonclasses>py test.py
We are dividing 20 with 2
10.0
We are dividing 20 with 0
OOP's ..can't devide with zero
None
Decorator Chaining
----------------------------
We can define multiple decorators for the same function and all these decorators will
perform decorator chaining.
Ex:
@decor1
@decor
def num():
-->For num() function we are applying 2 decorator functions. First inner decorator will
work and then outer decorator.
148 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex:
-----
1. def decor1(func):
2. def inner():
3. x=func()
4. return x*x
5. return inner
6.
7. def decor(func):
8. def inner():
9. x=func()
10. return 2*x
11. return inner
12.
13. @decor1
14. @decor
15. def num():
16. return 10
17. print(num())
o/p:D:\pythonclasses>py test.py
400
149 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Generators
-->Generator is a function which is responsible to generate a sequence of values.
-->We can write generator function just like ordinary functions, but it uses "yield"
keyword to return values.
1) def mygen():
2) yield 'A'
3) yield 'B'
4) yield 'C'
5) g=mygen()
6) print(type(g))
7) print(next(g))
8) print(next(g))
9) print(next(g))
o/p:D:\pythonclasses>py test.py
<class 'generator'>
A
B
C
Ex-2:
-------
1) def countdown(num):
2) print("start countdown")
3) while (num>0):
4) yield num
5) num=num-1
6) values=countdown(5)
7) for i in values:
8) print(i)
150 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
o/p:D:\pythonclasses>py test.py
start countdown
5
4
3
2
1
1) def firstn(num):
2) i=1
3) while i<=num:
4) yield i
5) i=i+1
6) values=firstn(5)
7) for x in values:
8) print(x)
9) print(type(values))
o/p:D:\pythonclasses>py test.py
1
2
3
4
5
1) def fib():
2) a,b=0,1
3) while True:
4) yield a
5) a,b=b,a+b
6) for x in fib():
7) if x>100:
151 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
8) break
9) print(x)
o/p:D:\pythonclasses>py test.py
0 1 1 2 3 5 8 13 21 34 55 89
152 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
MODULES
-->A group of functions, variables and classes saved into a file, which is nothing but
module.
-->Every python file(.py) acts as module.
-->Advantages of modules are: Reusability, Readability & Maintainability.
Ex: maheshmath.py
----------------------------
1) x=333
2) def add(a,b):
3) return a+b
4) def product(a,b):
5) return(a*b)
-->py maheshmath.py
-->maheshmath module contains one variable and 2 functions.
-->If we want to use memebers of the 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) import maheshmath
2) print(maheshmath.x)
3) print(maheshmath.add(10,20))
4) print(maheshmath.product(10,20))
o/p:
333
30
200
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
__pycache__ folder
153 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Renaming a module at the time of import(module aliasing):
-----------------------------------------------------------------------------------
Ex:
import maheshmath as m
-->Here maheshmath is original module name and m is alias name.
-->We can access memebrs by using alias name m.
test.py
---------
1) import maheshmath as m
2) print(m.x)
3) print(m.add(10,20))
4) print(m.product(10,20))
from......import:
----------------------
-->We can import a particular member of module by using from....import
-->The main advantage of this is we can access memebrs directly without using module
name.
Ex:
----
member aliasing:
------------------------
154 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
-->Once we defined as alias name, we should use alias name only and we should not use
original name.
Ex:
1) import modulename
2) import module1,module2,module3
3) import module1 as m
4) import module1 as m1,module2 as m2,module3 as m3
5) from module import memeber
6) from module import memeber1,member2,member3
7) from module import memeber1 as x
8) from module import *
Reloading a Module:
----------------------------
-->Bydefault module will be loaded only once eventhough we are importing multiple
times.
Ex: module1.py
----------------------
print("This is from module1")
test.py
----------
1) import module1
2) import module1
3) import module1
4) import module1
5) print("This is test module")
o/p:
This is from module1
This is from test module
-->In the above program test module will be loaded only once eventhough we are
importing multiple times.
155 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
-->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)
Ex:
-----
1) import time
2) import module1
3) print("program entering into sleeping state")
4) time.sleep(30)
5) import module1
6) print("This is last line of the program")
o/p:D:\pythonclasses>py test.py
This is from module1
program entering into sleeping state
This is last line of the program
Ex:
----
1) import time
2) from imp import reload
3) import module1
4) print("program entering into sleeping state")
5) time.sleep(30)
6) reload(module1)
7) print("program entering into sleeping state")
8) time.sleep(30)
9) reload(module1)
10) print("This is last line of the program")
o/p:
This is from module1
program entering into sleeping state
This is first module1
program entering into sleeping state
This is second module1
This is last line of the program
156 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
-->The main advantage of explicit module reloading is we can ensure that updated version
is always available to our program.
Ex:test.py
--------------
1) x=333
2) def add(a,b):
3) return a+b
4) print(dir())
o/p:D:\pythonclasses>py test.py
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', 'add', 'x']
maheshmath.py
----------------------
1) x=333
2) def add(a,b):
3) return a+b
4) def product(a,b):
5) return(a*b)
test.py
---------
1) import maheshmath
2) print(dir(maheshmath))
o/p:D:\pythonclasses>py test.py
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'add', 'product', 'x']
157 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Note: For every module at the time of execution python interpreter will add some special
properties automatically for internal use.
-->Based on our requirement we can access these properties also in our program.
Ex: test.py
---------------
1) print(__builtins__)
2) print(__cached__)
3) print(__doc__)
4) print(__file__)
5) print(__loader__)
6) print(__name__)
7) print(__package__)
8) print(__spec__)
o/p:D:\pythonclasses>py test.py
<module 'builtins' (built-in)>
None
None
test.py
<_frozen_importlib_external.SourceFileLoader object at 0x000001F562583CF8>
__main__
None
None
158 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Ex: module1.py
----------------------
1) def f1():
2) if __name__=="__main__":
3) print("The code executed directly as a program")
4) print("The value of __name__:",__name__)
5) else:
6) print("The code executed indirectly as a module from some other module")
7) print("The value of __name__:",__name__)
8) f1()
o/p:D:\pythonclasses>py module1.py
The code executed directly as a program
The value of __name__: __main__
test.py
----------
1) import module1
2) module1.f1()
o/p:D:\pythonclasses>py test.py
The code executed indirectly as a module from some other module
The value of __name__: module1
The code executed indirectly as a module from some other module
The value of __name__: module1
Ex:
----
159 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Note: We can find help of any module by using help() function
Ex:
1) import math
2) help(math)
1).random():
-----------------
This function always generates some float value between 0 and 1(not inclusive).
0<x<1
Ex:
o/p:D:\pythonclasses>py test.py
0.7690917847505055
0.12958902402812178
0.4865336117685294
0.21174369485166067
0.22533721686631736
0.24270745076560807
0.6156350105877338
0.3588237251403473
0.5609192891678808
0.46565274922504374
2).randint():
-----------------
To generate random integer between two given numbers(inclusive)
Ex:
160 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
3) print(randint(1,100))#Generates random int values between 1 and
100(inclusive)
o/p:D:\pythonclasses>py test.py
70
88
20
73
16
8
27
72
80
71
o/p:D:\pythonclasses>py test.py
420863
352322
626559
689042
735553
3).uniform():
------------------
-->It returns random float values between 2-given numbers(not inclusive)
Ex:
-----
o/p:D:\pythonclasses>py test.py
1.456481671599132
8.262379808015648
161 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
8.294591177579873
2.4766196390802415
3.9929683121049644
6.908124318470733
5.113015507787097
1.9677692845675518
8.48400436311528
7.760067312991328
4).randrange([start],stop,[step]):
--------------------------------------------
-->Returns a random number from the range.
start<=x<stop
-->start argument is optional and default value is 0.
-->step argument is optional and default value is 1.
Ex 1:
-------
Ex 2:
--------
Ex 3:
--------
162 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
5).choice():
---------------
-->It wont return random number.
-->It will return a random object from the given list or tuple,str.
Ex 1:
-------
Ex 2:
-------
Ex 3:
-------
o/p:D:\pythonclasses>py test.py
TypeError: 'set' object does not support indexing
Ex 4:
-------
Ex: To generate random pwd of 6-length where as 1,3,5 are aplhabate symbols and 2,4,6
are digits.
nd
163 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
3) print(chr(randint(65,65+25)),randint(0,9),chr(randint(65,65+25)),randint(0,9
),chr(randint(65,65+25)),randint(0,9),sep='')
o/p:D:\pythonclasses>py test.py
L0Z4J6
X1M8N6
A8L2U1
V7O2Z5
S9U2S1
164 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
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
can be empty.
-->A package can contains sub packages also.
-->Python 3.3 has implicitly namespace packages that allows to create a package without
__init__.py file.
Ex1:
-----
D:\pythonclasses
|--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.modul1.f1()
165 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
test.py(version-2):
-------------------------
from pack1.module1 import f1
f1()
Ex 2:
-------
D:\pythonclasses
|--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 module 2 present in com.durgasoft")
test.py:
----------
o/p:
Hello this is from module1 present in com
Hello this is from module 2 present in com.durgasoft
166 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in