Python
Python
Python Notes
Introduction
Python is a general purpose high level programminglanguage.
Python was developed by Guido Van Rossam in 1989 while working atNational
Research Institute atNetherlands.
ButofficiallyPythonwasmadeavailabletopublicin1991.TheofficialDateof Birthfor
Python is : Feb 20th1991.
Java:
C:
1) #include<stdio.h>
2) void main()
3) {
4) print("Helloworld");
5) }
Python:
print("Hello World")
[Type here]
Java:
C:
1) #include <stdio.h>
2)
3) void main()
4){
5) int a,b;
6) a=10;
7) b=20;
8) printf("The Sum:%d",(a+b));
9) }
Python:
1)a=10
2)b=20
3) print("The Sum:",(a+b))
Guido developed Python language by taking almost all programming features from
different languages
We can use everywhere. The most common important application areas are
Note:
Features of Python:
1. Simple and easy tolearn:
Python is a simple programming language. When we read Python program,we can feel like
reading english statements.
The syntaxes are very simple and only 30+ kerywords are available.
When compared with other languages, we can write programs with very less number of
lines. Hence more readability and simplicity.
We can reduce development and cost of the project.
Its source code is open,so that we can we can customize based on our requirement.
Python is high level programming language and hence it is programmer friendly language.
Being a programmer we are not required to concentrate low level activities like memory
management and security etc..
4. PlatformIndependent:
Once we write a Python program,it can run on any platform without rewriting once again.
Internally PVM is responsible to convert into machine understandable form.
5. Portability:
Python programs are portable. ie we can migrate from one platform to another platform
very easily. Python programs will provide same results on any paltform.
6. DynamicallyTyped:
In Python we are not required to declare type for variables. Whenever we are assigning
the value, based on value, type will be allocated automatically.Hence Python is considered
as dynamically typed language.
But Java, C etc are Statically Typed Languages b'z we have to provide type at the beginning
only.
This dynamic typing nature will provide more flexibility to the programmer.
Python language supports both Procedure oriented (like C, pascal etc) and object oriented
(like C++,Java) features. Hence we can get benefits of both like security and reusability etc
8. Interpreted:
We are not required to compile Python programs explcitly. Internally Python interpreter
will take care that compilation.
If compilation fails interpreter raised syntax errors. Once compilation success then PVM
(Python Virtual Machine) is responsible to execute.
9. Extensible:
10. Embedded:
11. ExtensiveLibrary:
etc...
Limitations of Python:
1. Performance wise not up to the mark b'z it is interpretedlanguage.
2. Not using for mobileApplications
Flavors of Python:
1. CPython:
It is the standard flavor of Python. It can be used to work with C lanugage Applications
2. Jython orJPython:
It is for Java Applications. It can run on JVM
3. IronPython:
It is for C#.Net platform
4. PyPy:
The main advantage of PyPy is performance will be improved because JIT compiler is
available inside PVM.
5. RubyPython
For Ruby Platforms
6. AnacondaPython
It is specially designed for handling large volume of data processing.
...
[Type here]
Python Versions:
Current versions
Python3.6.1 Python2.7.13
[Type here]
Identifiers
A name in Python program is called identifier.
It can be class name or function name or module name or variable name.
a = 10
By mistake if we are using any other symbol like $ then we will get syntax error.
cash = 10√
ca$h =20
2. Identifier should not starts withdigit
123total
total123 √
total=10
TOTAL=999
print(total)#10
print(TOTAL)#999
[Type here]
Identifier:
1. Alphabet Symbols (Either Upper case OR Lowercase)
1) 123total
2) total123√
3) java2share √
4) ca$h
5) _abc_abc_√
6) def
7) if
Note:
Eg: add
[Type here]
Reserved Words
In Python some words are reserved to represent some meaning or functionality. Such type
of words are called Reserved words.
True,False,None
and, or,not,is
if,elif,else
while,for,break,continue,return,in,yield
try,except,finally,raise,assert
import,from,as,class,def,pass,global,nonlocal,lambda,del,with
Note:
1. All Reserved words in Python contain only alphabetsymbols.
2. Except the following 3 reserved words, all contain only lower case alphabetsymbols.
True
False
None
Eg: a= true
a=True√
Data Types
Data Type represent the type of data present inside a variable.
In Python we are not required to specify the type explicitly. Based on value provided,the
type will be assigned automatically.Hence Python is Dynamically Typed Language.
10
a =10 a
a =20
20
a
a =10
b =10 10
b
1.type()
to check the type of variable
2. id()
to get address of object
[Type here]
3. print()
to print the value
We can use int data type to represent whole numbers (integral values)
Eg:
a=10
type(a) #int
Note:
In Python2 we have long data type to represent very large integral values.
But in Python3 there is no long type explicitly and we can represent long values also by
using int type only.
1. Decimalform
2. Binaryform
3. Octalform
4. Hexa decimalform
1. Decimalform(base-10):
2. Binaryform(Base-2):
Eg: a = 0B1111
a =0B123
a=b111
3. OctalForm(Base-8):
Eg: a=0o123
a=0o786
4. Hexa DecimalForm(Base-16):
The allowed digits are : 0 to 9, a-f (both lower and upper cases are allowed)
Literal value should be prefixed with 0x or 0X
Eg:
a =0XFACE
a=0XBeef
a =0XBeer
Note: Being a programmer we can specify literal values in decimal, binary, octal and hexa
decimal forms. But PVM will always provide values only in decimal form.
a=10
b=0o10
c=0X10
d=0B10
print(a)10
print(b)8
print(c)16
print(d)2
Base Conversions
Python provide the following in-built functions for base conversions
1. bin():
Eg:
1) >>>bin(15)
2) '0b1111'
3) >>>bin(0o11)
4) '0b1001'
5) >>>bin(0X10)
6) '0b10000'
2. oct():
Eg:
1) >>> oct(10)
2) '0o12'
3) >>> oct(0B1111)
4) '0o17'
5) >>> oct(0X123)
6) '0o443'
3. hex():
Eg:
1) >>> hex(100)
2) '0x64'
3) >>> hex(0B111111)
4) '0x3f'
5) >>> hex(0o12345)
6) '0x14e5'
Eg: f=1.234
type(f)float
We can also represent floating point values by using exponential form (scientific notation)
Eg: f=1.2e3
print(f)1200.0
instead of 'e' we can use 'E'
The main advantage of exponential form is we can represent big values in less memory.
***Note:
We can represent int values in decimal, binary, octal and hexa decimal forms. But we can
represent float values only by using decimal form.
Eg:
1) >>> f=0B11.01
2) File "<stdin>", line1
3) f=0B11.01
[Type here]
4) ^
5) SyntaxError: invalid syntax
6)
7) >>> f=0o123.456
8) SyntaxError: invalidsyntax
9)
10) >>> f=0X123.456
11) SyntaxError: invalid syntax
j2 = -1
a + bj
j=
RealPart ImaginaryPart
Eg:
3+5j
10+5.5j
0.5+0.1j
In the real part if we use int value then we can specify that either by decimal,octal,binary
or hexa decimal form.
But imaginary part should be specified only by using decimal form.
1) >>> a=0B11+5j
2) >>> a
3) (3+5j)
4) >>> a=3+0B11j
5) SyntaxError: invalidsyntax
1) >>> a=10+1.5j
2) >>> b=20+2.5j
3) >>> c=a+b
4) >>>print(c)
5) (30+4j)
6) >>> type(c)
7) <class 'complex'>
[Type here]
Note: Complex data type has some inbuilt attributes to retrieve the real part and
imaginary part
c=10.5+3.6j
c.real==>10.5
c.imag==>3.6
We can use complex type generally in scientific Applications and electrical engineering
Applications.
4. bool datatype:
b=True
type(b) =>bool
Eg:
a=10
b=20
c=a<b
print(c)==>True
True+True==>2
True-False==>1
str type:
str represents String data type.
s1='venkat'
s1="venkat"
By using single quotes or double quotes we cannot represent multi line string literals.
s1="venkat
[Type here]
soft"
s1='''venkat
soft'''
We can also use triple quotes to use single quote or double quote in our String.
Slicing of Strings:
slice means a piece
[ ] operator is called slice operator,which can be used to retrieve parts of String.
In Python Strings follows zero based index.
The index can be either +ve or -ve.
+ve index means forward direction from Left to Right
-ve index means backward direction from Right to Left
-5 -4 -3 -2 -1
v e n k Y
0 1 2 3 4
1) >>> s="venky"
2) >>> s[0]
3) 'v'
4) >>> s[1]
5) 'e'
6) >>> s[-1]
7) 'y'
8) >>> s[40]
1) >>> s[1:40]
2) 'enky'
3) >>> s[1:]
4) 'enky'
5) >>> s[:4]
6) 'venk'
7) >>> s[:]
8) 'venky'
9) >>>
10)
11)
12) >>> s*3
13) 'venkyvenkyvenky'
14)
15) >>> len(s)
16) 5
Note:
1. In Python the following data types are considered as Fundamental Datatypes
int
float
complex
bool
str
2. In Python,we can represent char values also by using str type and explicitly char type
is not available.
Eg:
1) >>> c='a'
2) >>> type(c)
3) <class 'str'>
3. long Data Type is available in Python2 but not in Python3. In Python3 long values also
we can represent by using int typeonly.
4. In Python we can present char Value also by using st rType and explicitly char Type
is not available.
[Type here]
Type Casting
We can convert one type value to another type. This conversion is called Type casting or
Type conversion.
The following are various inbuilt functions for type casting.
1. int()
2. float()
3. complex()
4. bool()
5. str()
1.int():
We can use this function to convert values from other types to int
Eg:
1) >>> int(123.987)
2) 123
3) >>> int(10+5j)
4) TypeError: can't convert complex to int
5) >>> int(True)
6) 1
7) >>> int(False)
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("0B1111")
16) ValueError: invalid literal for int() with base 10: '0B1111'
Note:
2. float():
We can use float() function to convert other type values to float type.
1) >>> float(10)
2) 10.0
3) >>> float(10+5j)
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'
15) >>> float("0B1111")
16) ValueError: could not convert string to float: '0B1111'
Note:
1. We can convert any type value to float type except complextype.
2. Whenever we are trying to convert str type to float type compulsary str shouldbe
either integral or floating point literal and should be specified only inbase-10.
3. complex():
Form-1:complex(x)
We can use this function to convert x into complex number with real part x and imaginary
part 0.
Eg:
1) complex(10)==>10+0j
2) complex(10.5)===>10.5+0j
3) complex(True)==>1+0j
4) complex(False)==>0j
5) complex("10")==>10+0j
6) complex("10.5")==>10.5+0j
7) complex("ten")
8) ValueError: complex() arg is a malformed string
[Type here]
Form-2: complex(x,y)
We can use this method to convert x and y into complex number such that x will be real
part and y will be imaginary part.
Eg: complex(10,-2)==>10-2j
complex(True,False)==>1+0j
4. bool():
We can use this function to convert other type values to bool type.
Eg:
1) bool(0)==>False
2) bool(1)==>True
3) bool(10)===>True
4) bool(10.5)===>True
5) bool(0.178)==>True
6) bool(0.0)==>False
7) bool(10-2j)==>True
8) bool(0+1.5j)==>True
9) bool(0+0j)==>False
10) bool("True")==>True
11) bool("False")==>True
12) bool("")==>False
[Type here]
5. str():
We can use this method to convert other type values to str type
Eg:
1) >>> str(10)
2) '10'
3) >>> str(10.5)
4) '10.5'
5) >>> str(10+5j)
6) '(10+5j)'
7) >>> str(True)
8) 'True'
In Python if a new object is required, then PVM wont create object immediately. First it
will check is any object available with the required content or not. If available then
existing object will be reused. If it is not available then only a new object will be created.
The advantage of this approach is memory utilization and performance will be improved.
But the problem in this approach is,several references pointing to the same object,by
usingonereferenceifweareallowedtochangethecontentintheexistingobjectthen the
remaining references will be effected. To prevent this immutability concept isrequired.
According to this once creates an object we are not allowed to change content. If we are
trying to change with those changes a new object will be created.
Eg:
1) >>>a=10
2) >>> b=10
3) >>> a isb
4) True
5) >>>id(a)
6) 1572353952
7) >>>id(b)
8) 1572353952
9) >>>
bytes data type represens a group of byte numbers just like an array.
Eg:
1) x = [10,20,30,40]
2) b = bytes(x)
3) type(b)==>bytes
4) print(b[0])==> 10
5) print(b[-1])==> 40
6) >>>for i in b : print(i)
7)
8) 10
9) 20
10) 30
11) 40
Conclusion 1:
The only allowed values for byte data type are 0 to 256. By mistake if we are trying to
provide any other values then we will get value error.
Conclusion 2:
Once we creates bytes data type value, we cannot change its values,otherwise we will get
TypeError.
Eg:
1) >>> x=[10,20,30,40]
2) >>> b=bytes(x)
3) >>> b[0]=100
4) TypeError: 'bytes' object does not support item assignment
Eg 1:
1) x=[10,20,30,40]
2) b = bytearray(x)
3) for i in b : print(i)
4) 10
[Type here]
5) 20
6) 30
7) 40
8) b[0]=100
9) for i in b:print(i)
10) 100
11)20
12) 30
13)40
Eg 2:
1) >>> x =[10,256]
2) >>> b = bytearray(x)
3) ValueError: byte must be in range(0, 256)
Eg:
1) list=[10,10.5,'venkat',True,10]
2) print(list) #[10,10.5,'venkat',True,10]
Eg:
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) ...
11) 100
12) 20
13) 30
[Type here]
14) 40
list is growable in nature. i.e based on our requirement we can increase or decrease the
size.
1) >>> list=[10,20,30]
2) >>> list.append("venkat")
3) >>> list
4) [10, 20, 30, 'venkat']
5) >>> list.remove(20)
6) >>> list
7) [10, 30, 'venkat']
8) >>> list2=list*2
9) >>> list2
10) [10, 30, 'venkat', 10, 30, 'venkat']
Note: An ordered, mutable, heterogenous collection of eleemnts is nothing but list, where
duplicates also allowed.
Eg:
1) t=(10,20,30,40)
2) type(t)
3) <class 'tuple'>
4) t[0]=100
5) TypeError: 'tuple' object does not support item assignment
6) >>> t.append("venkat")
7) AttributeError: 'tuple' object has no attribute'append'
8) >>> t.remove(10)
9) AttributeError: 'tuple' object has no attribute'remove'
Form-1:range(10)
generate numbers from 0 to 9
Eg:
r=range(10)
for i in r:print(i) 0 to9
Form-2:range(10,20)
r = range(10,20)
for i in r:print(i) 10 to19
Form-3:range(10,20,2)
r = range(10,20,2)
for i in r:print(i) 10,12,14,16,18
We can access elements present in the range Data Type by using index.
r=range(10,20)
r[0]==>10
r[15]==>IndexError: range object index out of range
Eg:
r[0]=100
TypeError: 'range' object does not support item assignment
Eg:
1) >>> l =list(range(10))
2) >>> l
3) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Eg:
1) s={100,0,10,200,10,'venkat'}
2) s # {0, 100, 'venkat', 200,10}
3) s[0] ==>TypeError: 'set' object does not support indexing
4)
5) set is growable in nature, based on our requirement we can increase or decrease the size.
6)
7) >>> s.add(60)
8) >>> s
9) {0, 100, 'venkat', 200, 10, 60}
10) >>> s.remove(100)
11) >>> s
12) {0, 'venkat', 200, 10, 60}
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) ...
9) 40
10) 10
11)20
12) 30
13)
14) >>> fs.add(70)
15) AttributeError: 'frozenset' object has no attribute 'add'
16) >>> fs.remove(10)
17) AttributeError: 'frozenset' object has no attribute 'remove'
[Type here]
Eg:
d={101:'venkat',102:'ravi',103:'shiva'}
Duplicate keys are not allowed but values can be duplicated. If we are trying to insert an
entry with duplicate key then old value will be replaced with new value.
Eg:
1. >>> d={101:'venkat',102:'ravi',103:'shiva'}
2. >>> d[101]='sunny'
3. >>> d
4. {101: 'sunny', 102: 'ravi', 103: 'shiva'}
5.
6. We can create empty dictionary as follows
7. d={ }
8. We can add key-value pairs as follows
9. d['a']='apple'
10. d['b']='banana'
11. print(d)
Note:
1. In general we can use bytes and bytearray data types to represent binaryinformation
like images,video filesetc
2. In Python2 long data type is available. But in Python3 it is not available and we can
represent long values also by using int typeonly.
3. In Python there is nochar data type. Hence we can represent char values also by using
strtype.
[Type here]
<class 'set'>
frozenset To represent an unordered Immutable >>> s={11,2,3,'Venkat',100,'Ramu'}
collection of unique objects >>> fs=frozenset(s)
>>> type(fs)
<class 'frozenset'>
Dict To represent a group of key Mutable >>>
value pairs d={101:'venkat',102:'ramu',103:'hari'}
>>> type(d)
<class 'dict'>
print(m1())
None
Escape Characters:
In String literals we can use esacpe characters to associate a special meaning.
1) >>>s="venkat\nsoftware"
2) >>>print(s)
3) venkat
4) software
5) >>> s="venkat\tsoftware"
6) >>>print(s)
7) venkat software
8) >>> s="This is " symbol"
9) File "<stdin>", line1
10) s="This is "symbol"
11) ^
12) SyntaxError: invalid syntax
13) >>> s="This is \" symbol"
14) >>>print(s)
15) This is " symbol
[Type here]
1) \n==>NewLine
2) \t===>Horizontaltab
3) \r ==>CarriageReturn
4) \b===>Backspace
5) \f===>FormFeed
6) \v==>Verticaltab
7) \'===>Singlequote
8) \"===>Doublequote
9) \\===>back slash symbol
....
Constants:
Constants concept is not applicable in Python.
But it is convention to use only uppercase characters if we don’t want to change value.
MAX_VALUE=10
Operators
Operator is a symbol that performs certain operations.
Python provides the following set of operators
1. ArithmeticOperators
2. Relational Operators or ComparisonOperators
3. Logicaloperators
4. Bitwiseoeprators
5. Assignmentoperators
6. Special operators
1. Arithmetic Operators:
+ ==>Addition
- ==>Subtraction
* ==>Multiplication
/ ==>Division operator
% ===>Modulo operator
Eg:test.py:
1) a=10
2) b=2
3) print('a+b=',a+b)
4) print('a-b=',a-b)
5) print('a*b=',a*b)
6) print('a/b=',a/b)
7) print('a//b=',a//b)
8) print('a%b=',a%b)
9) print('a**b=',a**b)
[Type here]
Output:
Eg:
1) a = 10.5
2) b=2
3)
4) a+b= 12.5
5) a-b= 8.5
6) a*b= 21.0
7) a/b= 5.25
8) a//b= 5.0
9) a%b= 0.5
10) a**b= 110.25
Eg:
10/2==>5.0
10//2==>5
10.0/2===>5.0
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
result is float type.
Note:
1) >>>"venkat"+10
2) TypeError: must be str, not int
3) >>>"venkat"+"10"
4) 'venkat10'
[Type here]
If we use * operator for str type then compulsory one argument should be int and other
argument should be str type.
2*"venkat
"
"venkat"*
2
2.5*"venkat" ==>TypeError: can't multiply sequence by non-int of type 'float'
"venkat"*"venkat"==>TypeError: can't multiply sequence by non-int of type
'str'
10/0
10.0/0
.....
Relational Operators:
>,>=,<,<=
Eg 1:
1) a=10
2) b=20
3) print("a > b is",a>b)
4) print("a >= b is ",a>=b)
5) print("a < b is",a<b)
6) print("a <= b is ",a<=b)
7)
8) a > b is False
9) a >= b is False
10) a < b is True
11) a <= b is True
Eg 2:
1) a="venkat"
2) b="venkat"
3) print("a > b is",a>b)
4) print("a >= b is ",a>=b)
5) print("a < b is",a<b)
[Type here]
Eg:
1) print(True>True) False
2) print(True>=True) True
3) print(10 >True) True
4) print(False > True) False
5)
6) print(10>'venkat')
7) TypeError: '>' not supported between instances of 'int' and'str'
Eg:
1) a=10
2) b=20
3) if(a>b):
4) print("a is greater thanb")
5) else:
6) print("a is not greater thanb")
Eg:
1) 10<20 ==>True
2) 10<20<30 ==>True
3) 10<20<30<40 ==>True
4) 10<20<30<40>50 ==>False
equality operators:
== , !=
We can apply these operators for any type even for incompatible types also
1) >>>10==20
2) False
3) >>> 10!=20
[Type here]
4) True
5) >>> 10==True
6) False
7) >>> False==False
8) True
9) >>>"venkat"=="venkat"
10) True
11) >>> 10=="venkat"
12) False
Eg:
1) >>> 10==20==30==40
2) False
3) >>> 10==10==10==10
4) True
Logical Operators:
and, or ,not
and ==>If both arguments are True then only result isTrue
or ====>If atleast one arugemnt is True then result is True
not ==>complement
0 means False
non-zero means True
empty string is always treated as False
x and y:
Eg:
10 and 20
0 and 20
x or y:
10 or 20 ==> 10
0 or 20 ==> 20
not x:
not 10==>False
not 0 ==>True
Bitwise Operators:
We can apply these operators bitwise.
These operators are applicable only for int and boolean types.
By mistake if we are trying to apply for any other type then we will get Error.
&,|,^,~,<<,>>
print(4&5) ==>valid
print(10.5 & 5.6) ==>
TypeError: unsupported operand type(s) for &: 'float' and 'float'
& ==> If both bits are 1 then only result is 1 otherwise result is 0
| ==> If atleast one bit is 1 then result is 1 otherwise result is 0
^ ==>If bits are different then only result is 1 otherwise result is 0
~ ==>bitwise complement operator
1==>0 &0==>1
<< ==>Bitwise Left shift
>> ==>Bitwise Right Shift
print(4&5) ==>4
print(4|5) ==>5
print(4^5) ==>1
Operator Description
& If both bits are 1 then only result is 1 otherwise result is 0
| If atleast one bit is 1 then result is 1 otherwise result is 0
^ If bits are different then only result is 1 otherwise result is 0
~ bitwise complement operator i.e 1 means 0 and 0 means 1
>> Bitwise Left shift Operator
<< Bitwise Right shift Operator
Note:
The most significant bit acts as sign bit. 0 value represents +ve number where as 1
represents -ve value.
positive numbers will be repesented directly in the memory where as -ve numbers will be
represented indirectly in 2's complement form.
Shift Operators:
<< Left shift operator
After shifting the empty cells we have to fill with zero
print(10<<2)==>40
0 0 0 0 1 0 1 0
0 0 1 0 1 0 0 0
[Type here]
After shifting the empty cells we have to fill with sign bit.( 0 for +ve and 1 for -ve)
print(10>>2) ==>2
0 0 0 0 1 0 1 0
0 0 0 0 0 0 1 0
Assignment Operators:
We can use assignment operator to assign value to the variable.
Eg:
x=10
We can combine asignment operator with some other operator to form compound
assignment operator.
The following is the list of all possible compound assignment operators in Python
+=
-=
*=
/=
%=
//=
**=
&=
|=
^=
[Type here]
>>=
<<=
Eg:
1) x=10
2) x+=20
3) print(x) ==>30
Eg:
1) x=10
2) x&=5
3) print(x) ==>0
Ternary Operator:
Syntax:
x = firstValue if condition else secondValue
If condition is True then firstValue will be considered else secondValue will be considered.
Eg 1:
1) a,b=10,20
2) x=30 if a<b else 40
3) print(x) #30
Eg 2:Read two numbers from the keyboard and print minimum value
Output:
Enter First Number:10
Enter Second Number:30
Minimum Value: 10
1) a=int(input("Enter FirstNumber:"))
2) b=int(input("Enter Second Number:"))
3) c=int(input("Enter Third Number:"))
4) min=a if a<b and a<c else b if b<c else c
5) print("Minimum Value:",min)
Eg:
Output:D:\python_classes>p
y test.py Enter First
Number:10
Enter Second Number:10
Both numbers are equal
D:\python_classes>py test.py
Enter First Number:10
Enter Second Number:20
First Number is Less than Second Number
D:\python_classes>py test.py
Enter First Number:20
Enter Second Number:10
First Number Greater than Second Number
[Type here]
Special operators:
Python defines the following 2 special operators
1. IdentityOperators
2. Membership operators
1. Identity Operators
We can use identity operators for address comparison.
2 identity operators are available
1. is
2. isnot
Eg:
1) a=10
2) b=10
3) print(a is b) True
4) x=True
5) y=True
6) print( x is y) True
Eg:
1) a="venkat"
2) b="venkat"
3) print(id(a))
4) print(id(b))
5) print(a is b)
Eg:
1) list1=["one","two","three"]
2) list2=["one","two","three"]
3) print(id(list1))
4) print(id(list2))
5) print(list1 is list2) False
6) print(list1 is not list2) True
7) print(list1 == list2) True
[Type here]
Note:
We can use is operator for address comparison where as == operator for content
comparison.
2. Membership operators:
We can use Membership operators to check whether the given object present in the
given collection.(It may be String,List,Set,Tuple or Dict)
Eg:
Eg:
1) list1=["sunny","bunny","chinny","pinny"]
2) print("sunny" in list1)True
3) print("tunny" in list1)False
4) print("tunny" not in list1)True
Operator Precedence:
If multiple operators present then which operator will be evaluated first is decided by
operator precedence.
Eg:
print(3+10*2) 23
print((3+10)*2) 26
() Parenthesis
** exponential operator
~,- Bitwise complement operator,unary minus operator
*,/,%,// multiplication,division,modulo,floor division
+,- addition,subtraction
<<,>>Left and Right Shift
&bitwise And
[Type here]
^ Bitwise X-OR
| Bitwise OR
>,>=,<,<=, ==, != ==>Relational or Comparison operators
=,+=,-=,*=... ==>Assignment operators
is , is not Identity Operators
in , not in Membership operators
not Logical not
and Logical and
or Logical or
Eg:
1) 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
8)
9)
10) 3/2*4+3+(10/5)**3-2
11) 3/2*4+3+2.0**3-2
12)3/2*4+3+8.0-2
13)1.5*4+3+8.0-2
14) 6.0+3+8.0-2
15) 15.0
[Type here]
If we want to use any module in Python, first we have to import that module.
importmath
importmath
print(math.sqrt(16))
print(math.pi)
4.0
3.141592653589793
import math as m
Once we create alias name, by using that we can access functions and variables of that
module
import math as m
print(m.sqrt(16))
print(m.pi)
If we import a member explicitly then it is not required to use module name while
accessing.
1. raw_input()
2. input()
1. raw_input():
This function always reads the data from the keyboard in the form of String Format. We
have to convert that string type to our required type by using the corresponding type
casting methods.
Eg:
x=raw_input("Enter First Number:")
print(type(x)) It will always print str type only for any inputtype
2. input():
input() function can be used to read data directly in our required format.We are not
required to perform type casting.
x=input("Enter Value)
type(x)
10 ===> int
"venkat"===>st
r 10.5===>float
True==>bool
***Note:But in Python 3 we have only input() method and raw_input() method is not
available.
Python3 input() function behaviour exactly same as raw_input() method of Python2. i.e
every input value is treated as str type only.
Eg:
1) >>> type(input("Entervalue:"))
2) Enter value:10
3) <class 'str'>
4)
5) Enter value:10.5
6) <class 'str'>
7)
8) Enter value:True
9) <class 'str'>
Q. Write a program to read 2 numbers from the keyboard and print sum.
-----------------------------------------------------
1) x=int(input("Enter FirstNumber:"))
2) y=int(input("Enter Second Number:"))
3) print("The Sum:",x+y)
-----------------------------------------------------------
Q. Write a program to read Employee data from the keyboard and print that data.
Note: split() function can take space as seperator by default.But we can pass
anything asseperator.
Q. Write a program to read 3 float numbers from the keyboard with , seperator and print
their sum.
eval():
eval Function take a String and evaluate the Result.
Eg: x = eval(“10+20+30”)
print(x)
Output:60
eval() can evaluate the Input to list, tuple, set, etc based the provided Input.
Eg: Write a Program to accept list from the keynboard on the display
1) l = eval(input(“EnterList”))
2) print (type(l))
3) print(l)
Within the Python Program this Command Line Arguments are available in argv. Which is
present in SYS Module.
test.py 10 20 30
Note: argv[0] represents Name of Program. But not first Command Line Argument.
argv[1] represent First Command Line Argument.
import argv
print(type(argv))
D:\Python_classes\py test.py
Note1: usually space is seperator between command line arguments. If our command line
argument itself contains space then we should enclose within double quotes(but not
single quotes)
Eg:
Note2:Within the Python program command line arguments are available in the String
form. Based on our requirement,we can convert into corresponding type by using type
casting methods.
Eg:
4)
5) D:\Python_classes>py test.py 10 20
6) 1020
7) 30
Note3: If we are trying to access command line arguments with out of range index then
we will get Error.
Eg:
Note:
In Python there is argparse module to parse command line arguments and display some
help messages whenever end user enters wrong input.
input()
raw_input()
output statements:
We can use print() function to display output.
Form-2:
1) print(String):
2) print("Hello World")
3) We can use escape characters also
4) print("Hello \n World")
5) print("Hello\tWorld")
6) We can use repetetion operator (*) in the string
7) print(10*"Hello")
8) print("Hello"*10)
9) We can use + operator also
10) print("Hello"+"World")
[Type here]
Note:
If both arguments are String type then + operator acts as concatenation operator.
If one argument is string type and second is any other type like int then we will get Error
If both arguments are number type then + operator acts as arithmetic additionoperator.
Note:
1) print("Hello"+"World")
2) print("Hello","World")
3)
4) HelloWorld
5) HelloWorld
By default output values are seperated by space.If we want we can specify seperator by
using "sep" attribute
1. a,b,c=10,20,30
2. print(a,b,c,sep=',')
3. print(a,b,c,sep=':')
4.
5. D:\Python_classes>py test.py
6. 10,20,30
7. 10:20:30
1. print("Hello")
2. print("Venkat")
3. print("Soft")
Output:
1. Hello
2. Venkat
3. Soft
1. print("Hello",end=' ')
2. print("welcome to",end=' ')
3. print("Python Learning")
Note: The default value for end attribute is \n,which is nothing but new line character.
Form-5:print(object) statement:
We can pass any object (like list,tuple,set etc)as argument to the print() statement.
Eg:
1. l=[10,20,30,40]
2. t=(10,20,30,40)
3. print(l)
4. print(t)
Form-6:print(String,variable list):
We can use print() statement with String and any number of arguments.
Eg:
1. s="Venkat"
2. a=35
3. s1="java"
4. s2="Python"
5. print("Hello",s,"Your Age is",a)
6. print("You are teaching",s1,"and",s2)
Output:
Form-7:print(formatted string):
%i====>int
%d====>int
%f=====>float
%s======>String type
[Type here]
Syntax:
1) a=10
2) b=20
3) c=30
4) print("a value is %i" %a)
5) print("b value is %d and c value is %d" %(b,c))
6)
7) Output
8) a value is 10
9) b value is 20 and c value is 30
Eg2:
1) s="Venkat"
2) list=[10,20,30,40]
3) print("Hello %s ...The List of Items are %s" %(s,list))
4)
5) Output Hello Venkat ...The List of Items are [10, 20, 30,40]
Eg:
1) name="Venkat"
2) salary=10000
3) gf="Sunny"
4) print("Hello {0} your salary is {1} and Your Friend {2} is waiting".format(name,salary,gf))
5) print("Hello {x} your salary is {y} and Your Friend {z} is waiting".format(x=name,y=salary,z=
gf))
6)
7) Output
8) Hello Venkat your salary is 10000 and Your Friend Sunny is waiting
9) Hello Venkat your salary is 10000 and Your Friend Sunny is waiting
[Type here]
FlowControl
Flow control describes the order in which statements will be executed at runtime.
Control Flow
1) if 1) break 1) for
2) if-elif 2) continue 2) while
3) if-elif-else 3) pass
I. ConditionalStatements
1) if
if condition : statement
or
if condition :
statement-1
statement-2
statement-3
If condition is true then statements will be executed.
[Type here]
Eg:
1) name=input("Enter Name:")
2) if name=="venkat" :
3) print("Hello Venkat”)
“”)MorningMMorning")
4) print("How are you!!!")
5)
6) D:\Python_classes>py test.py
7) Enter Name:venkat
8) Hello Venkat
9) How are you!!!
10)
11) D:\Python_classes>py test.py
12) Enter Name:Ravi
13) How are you!!!
2) if-else:
if condition :
Action-1
else :
Action-2
if condition is true then Action-1 will be executed otherwise Action-2 will be executed.
Eg:
1) name=input("Enter Name:")
2) if name=="venkat" :
3) print("Hello venkat GoodMorning")
4) else:
5) print("Hello Guest GoodMoring")
6) print("How are you!!!")
7)
8) D:\Python_classes>py test.py
9) Enter Name:venkat
10) Hello venkat Good Morning
11) How are you!!!
12)
13) D:\Python_classes>py test.py
14) Enter Name:Ravi
15) Hello Guest Good Moring
16) How are you!!!
[Type here]
3) if-elif-else:
Syntax:
if condition1:
Action-1
elif condition2:
Action-2
elif condition3:
Action-3
elif condition4:
Action-4
...
else:
Default Action
Eg:
Note:
Q. Write a program to find biggest of given 2 numbers from the commad prompt?
Q. Write a program to find biggest of given 3 numbers from the commad prompt?
1) n=int(input("EnterNumber:"))
2) if n>=1 and n<=10 :
3) print("The number",n,"is in between 1 to10")
4)else:
5) print("The number",n,"is not in between 1 to10")
Q. Write a program to take a single digit number from the key board and print is value in
English word?
1) 0==>ZERO
2) 1 ==>ONE
3)
4) n=int(input("Enter a digit from o to 9:"))
5) if n==0 :
6) print("ZERO")
7) elifn==1:
8) print("ONE")
9) elifn==2:
10) print("TWO")
11) elifn==3:
12) print("THREE")
13) elifn==4:
14) print("FOUR")
15) elifn==5:
16) print("FIVE")
17) elifn==6:
18) print("SIX")
19) elifn==7:
20) print("SEVEN")
21) elifn==8:
22) print("EIGHT")
23) elifn==9:
24) print("NINE")
25) else:
26) print("PLEASE ENTER A DIGIT FROM 0 TO9")
[Type here]
II. IterativeStatements
If we want to execute a group of statements multiple times then we should go for
Iterative statements.
1. forloop
2. whileloop
1) forloop:
If we want to execute some action for every element present in some sequence(it may be
string or collection)then we should go for for loop.
Syntax:
for x in sequence :
body
1) s="Sunny Leone"
2) for x in s :
3) print(x)
4)
5)Output
6)S
7)u
8)n
9)n
10) y
11)
12) L
13) e
14) o
15) n
16) e
[Type here]
1) for x in range(10) :
2) print("Hello")
1) for x in range(11):
print(x)
1) for x in range(21):
2) if(x%2!=0):
print(x)
1) for x in range(10,0,-1):
2) print(x)
[Type here]
1) list=eval(input("Enter List:"))
2) sum=0;
3) for x inlist:
4) sum=sum+x;
5) print("TheSum=",sum)
6)
7) D:\Python_classes>py test.py
8) Enter List:[10,20,30,40]
9) The Sum= 100
10)
11) D:\Python_classes>py test.py
12) Enter List:[45,67]
13) The Sum= 112
2) whileloop:
If we want to execute a group of statements iteratively until some condition false,then we
should go for while loop.
Syntax:
while condition :
body
1) x=1
2) while x <=10:
3) print(x)
4) x=x+1
1) n=int(input("Enternumber:"))
2)sum=0
3)i=1
4) while i<=n:
5) sum=sum+i
6) i=i+1
7) print("The sum of first",n,"numbers is:",sum)
[Type here]
Eg: write a program to prompt user to enter some name until entering Venkat
1) name=""
2) while name!="venkat":
3) name=input("Enter Name:")
4) 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 another loop,which are also known as nested loops.
Eg:
1) for i in range(4):
2) for j inrange(4):
3) print("i=",i,"j=",j)
4)
5)Output
6) D:\Python_classes>py test.py
7) i=0 j=0
8) i=0 j=1
9) i=0 j=2
10)i=0 j=3
11)i=1 j=0
12)i=1 j=1
13)i=1 j=2
14)i=1 j=3
15)i=2 j=0
16)i=2 j=1
17)i=2 j=2
18)i=2 j=3
19)i=3 j=0
20)i=3 j=1
21)i=3 j=2
22)i=3 j=3
[Type here]
1)*
2) * *
3) * * *
4) * * * *
5) * * * * *
6) * * * * * *
7) * * * * * * *
8)
9) n = int(input("Enter number of rows:"))
10) for i in range(1,n+1):
11) for j inrange(1,i+1):
12) print("*",end=" ")
13) print()
Alternative way:
1) *
2) **
3) ***
4) * * **
5) * * * * *
6) * * * * **
7) * * * * * * *
8)
9) n = int(input("Enter number of rows:"))
10) for i in range(1,n+1):
11) print(" " *(n-i),end="")
12) print("* "*i)
[Type here]
Eg:
1) for i inrange(10):
2) if(i==7):
3) print("processing is enough..plz break")
4) break
5) print(i)
6)
7) D:\Python_classes>py test.py
8)0
9)1
10) 2
11)3
12) 4
13)5
14) 6
15) processing is enough..plz break
Eg:
1) cart=[10,20,600,60,70]
2) for item in cart:
3) ifitem>500:
4) print("To place this order insurence must be required")
5) break
6) print(item)
7)
8) D:\Python_classes>py test.py
9)10
10) 20
11) To place this order insurence must be required
[Type here]
2) continue:
We can use continue statement to skip current iteration and continue next iteration.
1) for i in range(10):
2) ifi%2==0:
3) continue
4) print(i)
5)
6) D:\Python_classes>py test.py
7) 1
8)3
9) 5
10) 7
11) 9
Eg2:
1) cart=[10,20,500,700,50,60]
2) for item in cart:
3) ifitem>=500:
4) print("We cannot process this item :",item)
5) continue
6) print(item)
7)
8)Output
9) D:\Python_classes>py test.py
10) 10
11) 20
12) We cannot process this item : 500
13) We cannot process this item : 700
14) 50
15) 60
Eg3:
1) numbers=[10,20,0,5,0,30]
2) for n in numbers:
3) ifn==0:
4) print("Hey how we can divide with zero..just skipping")
5) continue
6) print("100/{} ={}".format(n,100/n))
7)
[Type here]
8)Output
9)
10) 100/10 = 10.0
11) 100/20 = 5.0
12) Hey how we can divide with zero..just skipping
13) 100/5 = 20.0
14) Hey how we can divide with zero..just skipping
15) 100/30 = 3.3333333333333335
Inside loop execution,if break statement not executed ,then only else part will be
executed.
Eg:
1)cart=[10,20,30,40,50]
2) for item in cart:
3) ifitem>=500:
4) print("We cannot process this order")
5) break
6) print(item)
7)else:
8) print("Congrats ...all items processed successfully")
9)
10) Output
11) 10
12) 20
13) 30
14) 40
15) 50
16) Congrats ...all items processed successfully
Eg:
1) cart=[10,20,600,30,40,50]
2) for item in cart:
3) if item>=500:
4) print("We cannot process this order")
5) Break
6) print(item)
7) else:
8) print("Congrats ...all items processed successfully")
[Type here]
9)
10) Output
11) D:\Python_classes>py test.py
12) 10
13) 20
14) We cannot process this order
Q. What is the difference between for loop and while loop in Python?
3) passstatement:
pass is a keyword in Python.
In our programming syntactically if block is required which won't do anything then we can
define that empty block with pass keyword.
pass
|- It is an empty statement
|- It is null statement
|- It won't do anything
Eg:
if True:
SyntaxError: unexpected EOF while parsing
if True: pass
==>valid
def m1():
SyntaxError: unexpected EOF while parsing
[Type here]
Sometimes in the parent class we have to declare a function with empty body and child
class responsible to provide proper implementation. Such type of empty body we can
define by using pass keyword. (It is something like abstract method in java)
Eg:
def m1(): pass
Eg:
1) for i inrange(100):
2) ifi%9==0:
3) print(i)
4) else:pass
5)
6) D:\Python_classes>py test.py
7)0
8)9
9)18
10) 27
11) 36
12) 45
13) 54
14) 63
15) 72
16) 81
17) 90
18) 99
del statement:
Eg:
1) x=10
2)print(x)
3) delx
[Type here]
After deleting a variable we cannot access that variable otherwise we will get NameError.
Eg:
1)x=10
2) del x
3)print(x)
Note:
We can delete variables which are pointing to immutable objects.But we cannot delete
the elements present inside immutable object.
Eg:
1)s="venkat"
2)print(s)
3) del s==>valid
4) del s[0] ==>TypeError: 'str' object doesn't support item deletion
In the case del, the variable will be removed and we cannot access that variable(unbind
operation)
1)s="venkat"
2) del s
3) print(s) ==>NameError: name 's' is notdefined.
But in the case of None assignment the variable won't be removed but the corresponding
object is eligible for Garbage Collection(re bind operation). Hence after assigning with
None value,we can access that variable.
1) s="venkat"
2) s=None
3) print(s) #None
[Type here]
What is String?
Any sequence of characters within either single quotes or double quotes is considered as a String.
Syntax:
s='venkat'
s="venkat
”
Note:In most of other languges like C, C++,Java, a single character with in single quotes is treated
as char data type value. But in Python we are not having char data type.Hence it is treated as
String only.
Eg:
>>> ch='a'
>>> type(ch)
<class 'str'>
Eg:
>>>
s='''venkat
software
solutions'''
We can also use triple quotes to use single quotes or double quotes as symbol inside String literal.
Eg:
s='This is ' single quote symbol' ==>invalid
s='This is \' single quote symbol' ==>valid
s="This is ' single quote symbol"====>valid
s='This is " double quotes symbol' ==>valid
s='The "Python Notes" by 'venkat' is very helpful' ==>invalid
s="The "Python Notes" by 'venkat' is very helpful"==>invalid
s='The \"Python Notes\" by \'venkat\' is very helpful'
==>valid s='''The "Python Notes" by 'venkat' is very helpful'''
==>valid
[Type here]
1. By usingindex
2. By using sliceoperator
1. By usingindex:
Eg:
s='venky'
Eg:
>>> s='venky'
>>> s[0]
'v'
>>> s[4]
'y'
>>> s[-1]
'y'
>>> s[10]
IndexError: string index out of range
Note:If we are trying to access characters of a string with out of range index then we will get
error saying : IndexError
Q. Write a program to accept some string from the keyboard and display its characters by
index wise(both positive and nEgative index)
test.py:
Output:D:\python_classes>p
y test.py Enter Some
String:venky
[Type here]
Syntax:s[bEginindex:endindex:step]
Note:If we are not specifying bEgin index then it will consider from bEginning of the string.
If we are not specifying end index then it will consider up to end of the string
The default value for step is 1
Eg:
if +ve then it should be forward direction(left to right) and we have to consider bEgin to end-1
if -ve then it should be backward direction(right to left) and we have to consider bEgin toend+1
[Type here]
***Note:
In the backward direction if end value is -1 then result is always empty.
In the forward direction if end value is 0 then result is always empty.
In forward direction:
default value for bEgin:0
default value for end: length of string
default value for step:+1
In backward direction:
default value for bEgin: -1
default value for end: -(length of string+1)
Note:Either forward or backward direction, we can take both +ve and -ve values for bEgin and
end index.
print("venkat"+"soft")
#venkatsoft print("venkat"*2)
#venkatvenkat
Note:
1. To use + operator for Strings, compulsory both arguments should be strtype
2. To use * operator for Strings, compulsory one argument should be str and other argument
should beint
Eg:
s='venkat'
print(len(s)) #5
[Type here]
Q.Writeaprogramtoaccesseachcharacterofstringinforwardandbackwarddirection by using
whileloop?
Alternativeways:
1) s="Learning Python is very easy !!!"
2) print("Forward direction")
3) for i in s:
4) print(i,end='')
5)
6) print("Forward direction")
7) for i in s[::]:
8) print(i,end='')
9)
10) print("Backward direction")
11) for i in s[::-1]:
12) print(i,end='')
Checking Membership:
We can check whether the character or string is the member of another string or not by using in
and not in operators
s='venkat'
print('v' in s) #True
print('z' in s) #False
Program:
Output:
D:\python_classes>py test.py
Enter main
string:venkatsoftwaresolutions
Enter sub string:venkat
venkat is found in main string
D:\python_classes>py test.py
Enter main
string:venkatsoftwaresolutions
Enter sub string:python
python is not found in main string
Comparison of Strings:
We can use comparison operators (<,<=,>,>=) and equality operators(==,!=) for strings.
Eg:
Output:
D:\python_classes>py test.py
Enter first string:venkat
Enter Second
string:venkat
Both strings are equal
D:\python_classes>py test.py
Enter first string: deepu
Enter Second string:ravi
First String is less than Second String
D:\python_classes>py test.py
Enter first string:venkat
Enter Second string:anil
First String is greater than Second String
[Type here]
Eg:
Finding Substrings:
We can use the following 4 methods
1. find():
s.find(substring)
Returns index of first occurrence of the given substring. If it is not available then we will get -1
Eg:
2) print(s.find("Python")) #9
3) print(s.find("Java")) # -1
4) print(s.find("r"))#3
5) print(s.rfind("r"))#21
Note:By default find() method can search total string. We can also specify the boundaries to
search.
s.find(substring,bEgin,end)
Eg:
1) s="venkyravipavanshiva"
2) print(s.find('a'))#4
3) print(s.find('a',7,15))#10
4) print(s.find('z',7,15))#-1
index() method:
index() method is exactly same as find() method except that if the specified substring is not
available then we will get ValueError.
Eg:
Output:
D:\python_classes>py test.py
Enter main string:learning python is very easy
Enter sub string:python
substring found
D:\python_classes>py test.py
Enter main string:learning python is very easy
Enter sub string:java
substring not found
[Type here]
Output:
D:\python_classes>py test.py
Enter main string:abbababababacdefg
Enter sub string:a
Found at position 0
Found at position 3
Found at position 5
Found at position 7
Found at position 9
Found at position 11
D:\python_classes>py test.py
Enter mainstring:abbababababacdefg
Enter substring:bb
Found at position1
Eg:
1) s="abcabcabcabcadda"
2) print(s.count('a'))
3) print(s.count('ab'))
4) print(s.count('a',3,7))
[Type here]
Output:
6
4
2
Eg1:
s="Learning Python is very difficult"
s1=s.replace("difficult","easy")
print(s1)
Output:
Learning Python is very easy
s="ababababababab"
s1=s.replace("a","b")
print(s1)
Output:bbbbbbbbbbbbbb
Q. String objects are immutable then how we can change the content by
using replace() method.
Once we creates string object, we cannot change the content.This non changeable behaviour is
nothing but immutability. If we are trying to change the content by using any method, then with
those changes a new object will be created and changes won't be happend in existing object.
Hence with replace() method also a new object got created but existing object won't be changed.
Eg:
s="abab"
s1=s.replace("a","b")
print(s,"is available at :",id(s))
print(s1,"is available at :",id(s1))
Output:
abab is available at : 4568672
bbbb is available at : 4568704
[Type here]
In the above example, original object is available and we can see new object which was created
because of replace() method.
Splitting of Strings:
We can split the given string according to specified seperator by using split() method.
l=s.split(seperator)
The default seperator is space. The return type of split() method is List
Eg1:
1) s="venkat softwaresolutions"
2) l=s.split()
3) for x inl:
4) print(x)
Output:
venkat
software
solutions
Eg2:
1) s="22-02-2018"
2) l=s.split('-')
3) for x inl:
4) print(x)
Output:
22
02
2018
Joining of Strings:
We can join a group of strings(list or tuple) wrt the given seperator.
s=seperator.join(group of strings)
Eg:t=('sunny','bunny','chin
ny') s='-'.join(t)
print(s)
Output: sunny-bunny-chinny
[Type here]
Eg2:
l=['hyderabad','singapore','london','dubai']
s=':'.join(l)
print(s)
hyderabad:singapore:london:dubai
Eg:
s='learning Python is very Easy'
print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.capitalize())
Output:
LEARNING PYTHON IS VERYEASY
learning python is very easy
LEARNING pYTHON IS VERYeASY
Learning Python Is Very Easy
Learning python is very easy
1. s.startswith(substring)
2. s.endswith(substring)
Eg:
s='learning Python is very easy'
print(s.startswith('learning'))
print(s.endswith('learning'))
print(s.endswith('easy'))
[Type here]
Output:
True
False
True
Eg:
print('Venkat786'.isalnum()) #True
print('venkat786'.isalpha()) #False
print('venkat'.isalpha()) #True
print('venkat'.isdigit()) #False
print('786786'.isdigit()) #True
print('abc'.islower()) #True
print('Abc'.islower()) #False
print('abc123'.islower()) #True
print('ABC'.isupper())#True
print('Learning python is Easy'.istitle()) #False
print('Learning Python Is Easy'.istitle()) #True
print(' '.isspace()) #True
Demo Program:
D:\python_classes>py test.py
Enter any character:7
Alpha Numeric Character
it is a digit
D:\python_classes>py test.py
Enter any character:a
Alpha Numeric Character
Alphabet character
Lower case alphabet character
D:\python_classes>py test.py
Enter any character:$
Non Space Special Character
D:\python_classes>py test.py
Enter any character:A
Alpha Numeric Character
Alphabet character
Upper case alphabet character
Eg:
name='venka
t'
salary=10000
age=48
print("{} 's salary is {} and his age is {}".format(name,salary,age))
print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
print("{x}'ssalaryis{y}andhisageis{z}".format(z=age,y=salary,x=name))
Output:
venkat 's salary is 10000 and his age is
48 venkat 's salary is 10000 and his age
is 48 venkat 's salary is 10000 and his
age is 48
[Type here]
1st Way:
2nd Way:
3rdWay:
Output:
Enter Some String:Learning Python is very easy!!
easy!!! very is Python Learning
[Type here]
Q4. Write a program to print characters at odd position and even position for the
givenString?
1st Way:
2nd Way:
s1="ravi"
s2="reja"
output:rtaevjia
[Type here]
Output:
Enter First String:venkat
Enter Second String:ravisoft
druarvgiasoft
Q6. Write a program to sort the characters of the string and first alphabet
symbolsfollowed by numeric values
input:B4A1D3
Output:ABD134
input: a4b3c2
output: aaaabbbcc
7) else:
8) output=output+previous*(int(x)-1)
9) print(output)
input:a4k3b2
output:aeknbd
Q9. Write a program to remove duplicate characters from the given input string?
input:ABCDABBCDABBBCCCDDEEEF
output:ABCDEF
Q10. Write a program to find the number of occurrences of each character present in
thegiven String?
input:ABCABCABBCDE
output:A-3,B-4,C-3,D-1,E-1
The main objective of format() method to format string into meaningful output form.
name='venkat'
salary=10000
age=48
print("{} 's salary is {} and his age is {}".format(name,salary,age))
print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
print("{x}'ssalaryis{y}andhisageis{z}".format(z=age,y=salary,x=name))
Output:
venkat 's salary is 10000 and his age is
48 venkat 's salary is 10000 and his age
is 48 venkat 's salary is 10000 and his
age is 48
Case-2:Formatting Numbers
d--->Decimal IntEger
f ---- >Fixed point number(float).The default precision is6
b-->Binary format
o-- >OctalFormat
x-->Hexa Decimal Format(Lower case)
X-->Hexa Decimal Format(Upper case)
Eg-1:
print("The intEger number is: {}".format(123))
print("The intEger number is: {:d}".format(123))
print("The intEger number is: {:5d}".format(123))
print("The intEger number is: {:05d}".format(123))
Output:
The intEger number is: 123
The intEger number is: 123
The intEger number is: 123
The intEger number is: 00123
Eg-2:
print("The float number is: {}".format(123.4567))
print("The float number is: {:f}".format(123.4567))
[Type here]
Output:
The float number is: 123.4567
The float number is: 123.456700
The float number is: 123.457
The float number is: 0123.457
The float number is: 0123.450
The float number is: 786786123.450
Note:
{:08.3f}
print("Binary Form:{0:b}".format(153))
print("Octal Form:{0:o}".format(153))
print("Hexa decimal Form:{0:x}".format(154))
print("Hexa decimal Form:{0:X}".format(154))
Output:
Binary Form:10011001
Octal Form:231
Hexa decimal Form:9a
Hexa decimal Form:9A
Note:We can represent only int values in binary, octal and hexadecimal and it is not possible for
float values.
Note:
{:5d} It takes an intEger argument and assigns a minimum width of 5.
{:8.3f} It takes a float argument and assigns a minimum width of 8 including "." and after decimal
point excatly 3 digits are allowed with round operation if required
{:05d} The blank places can be filled with 0. In this place only 0 allowed.
[Type here]
{:+d} and{:+f}
Using plus for -ve numbers there is no use and for -ve numbers - sign will come automatically.
Output:
int value with sign:+123
int value with sign:-123
float value with sign:+123.456000
float value with sign:-123.456000
Ex:
1) print("{:5d}".format(12))
2) print("{:<5d}".format(12))
3) print("{:<05d}".format(12))
4) print("{:>5d}".format(12))
5) print("{:>05d}".format(12))
6) print("{:^5d}".format(12))
7) print("{:=5d}".format(-12))
8) print("{:^10.3f}".format(12.23456))
9) print("{:=8.3f}".format(-12.23456))
Output:
12
12
12000
12
00012
12
-12
[Type here]
12.235
- 12.235
Similar to numbers, we can format String values also with format() method.
s.format(string)
Eg:
1) print("{:5d}".format(12))
2) print("{:5}".format("rat"))
3) print("{:>5}".format("rat"))
4) print("{:<5}".format("rat"))
5) print("{:^5}".format("rat"))
6) print("{:*^5}".format("rat")) #Instead of * we can use any character(like +,$,a etc)
Output:
12
rat
rat
rat
rat
*rat*
Note:For numbers default alignment is right where as for strings default alignment is left
1) print("{:.3}".format("venkatsoftware"))
2) print("{:5.3}".format("venkatsoftware"))
3) print("{:>5.3}".format("venkatsoftware"))
4) print("{:^5.3}".format("venkatsoftware"))
5) print("{:*^5.3}".format("venkatsoftware"))
Output:
dur
dur
dur
dur
*dur*
1) person={'age':48,'name':'venkat'}
2) print("{p[name]}'s age is: {p[age]}".format(p=person))
[Type here]
Output:
venkat's age is: 48
Note: p is alias name of dictionary
person dictionary we are passing as keyword argument
Eg:
1) person={'age':48,'name':'venkat'}
2) print("{name}'s age is: {age}".format(**person))
Output:
venkat's age is: 48
Eg:
1) class Person:
2) age=48
3) name="venkat"
4) print("{p.name}'s age is :{p.age}".format(p=Person()))
Output:
venkat's age is :48
Eg:
1) class Person:
2) def init(self,name,age):
3) self.name=name
4) self.age=age
5) print("{p.name}'s age is :{p.age}".format(p=Person('venkat',48)))
6) print("{p.name}'s age is :{p.age}".format(p=Person('Ravi',50)))
Note:Here Person object is passed as keyword argument. We can access by using its reference
variable in the template string
1) string="{:{fill}{align}{width}}"
2) print(string.format('cat',fill='*',align='^',width=5))
3) print(string.format('cat',fill='*',align='^',width=6))
4) print(string.format('cat',fill='*',align='<',width=6))
5) print(string.format('cat',fill='*',align='>',width=6))
[Type here]
Output:
*cat*
*cat**
cat***
***cat
1) num="{:{align}{width}.{precision}f}"
2) print(num.format(123.236,align='<',width=8,precision=2))
3) print(num.format(123.236,align='>',width=8,precision=2))
Output:
123.24
123.24
1) import datetime
2) #datetime formatting
3) date=datetime.datetime.now()
4) print("It's now:{:%d/%m/%Y %H:%M:%S}".format(date))
Output:It's now:09/03/201812:36:26
Case-12:Formatting complexnumbers
1) complexNumber=1+2j
2) print("Real Part:{0.real} and Imaginary Part:{0.imag}".format(complexNumber))
We can differentiate duplicate elements by using index and we can preserve insertion
order by using index. Hence index will play very important role.
Python supports both positive and negative indexes. +ve index means from left to right
where as negative index means right to left
-6 -5 -4 -3 -2 -1
10 A B 20 30 10
0 1 2 3 4 5
1) list=[]
2) print(list)
3) print(type(list))
4)
5) []
6) <class 'list'>
3. With dynamicinput:
1) list=eval(input("Enter List:"))
2) print(list)
3) print(type(list))
4)
5) D:\Python_classes>py test.py
6) Enter List:[10,20,30,40]
7) [10, 20, 30, 40]
8) <class 'list'>
4. With list()function:
1) l=list(range(0,10,2))
2) print(l)
3) print(type(l))
4)
5) D:\Python_classes>py test.py
6) [0, 2, 4, 6, 8]
7) <class 'list'>
Eg:
1) s="durga"
2) l=list(s)
3) print(l)
4)
5) D:\Python_classes>py test.py
6) ['d', 'u', 'r', 'g', 'a']
5. with split()function:
1) s="Learning Python is very very easy !!!"
2) l=s.split()
3) print(l)
4) print(type(l))
5)
6) D:\Python_classes>py test.py
7) ['Learning', 'Python', 'is', 'very', 'very', 'easy', '!!!']
8) <class 'list'>
Note:
Sometimes we can take list inside another list,such type of lists are called nested lists.
[10,20,[30,40]]
[Type here]
1. By usingindex:
list=[10,20,30,40]
-4 -3 -2 -1
10 20 30 40
list
0 1 2 3
print(list[0]) ==>10
print(list[-1]) ==>40
print(list[10]) ==>IndexError: list index out of range
2. By using sliceoperator:
Syntax:
list2= list1[start:stop:step]
Eg:
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])
[Type here]
7)
8) Output
9) D:\Python_classes>py test.py
10) [3, 5, 7]
11) [5, 7, 9]
12) [4, 5, 6, 7]
13) [9, 7, 5]
14) [5, 6, 7, 8, 9, 10]
List vs mutability:
Once we creates a List object,we can modify its content. Hence List objects are mutable.
Eg:
1) n=[10,20,30,40]
2) print(n)
3) n[1]=777
4) print(n)
5)
6) D:\Python_classes>py test.py
7) [10, 20, 30, 40]
8) [10, 777, 30, 40]
1. By using whileloop:
1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) i=0
3) while i<len(n):
4) print(n[i])
5) i=i+1
6)
7) D:\Python_classes>py test.py
8) 0
9)1
10) 2
11)3
12) 4
13)5
14) 6
15)7
16) 8
17)9
[Type here]
18) 10
2. By using forloop:
1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) for n1 in n:
3) print(n1)
4)
5) D:\Python_classes>py test.py
6) 0
7)1
8) 2
9) 3
10) 4
11)5
12) 6
13)7
14) 8
15)9
16) 10
1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) for n1 in n:
3) if n1%2==0:
4) print(n1)
5)
6) D:\Python_classes>py test.py
7) 0
8) 2
9) 4
10) 6
11)8
12) 10
1. len():
returns the number of elements present in the list
Eg: n=[10,20,30,40]
print(len(n))==>4
2. count():
It returns the number of occurrences of specified item in the list
1) n=[1,2,2,2,2,3,3]
2) print(n.count(1))
3) print(n.count(2))
4) print(n.count(3))
5) print(n.count(4))
6)
7) Output
8) D:\Python_classes>py test.py
9) 1
10) 4
11) 2
12) 0
3. index()function:
Eg:
1) n=[1,2,2,2,2,3,3]
2) print(n.index(1)) ==>0
3) print(n.index(2)) ==>1
4) print(n.index(3)) ==>5
5) print(n.index(4)) ==>ValueError: 4 is not inlist
Note:If the specified element not present in the list then we will get ValueError.Hence
before index() method we have to check whether item present in the list or not by using in
operator.
print( 4 in n)==>False
[Type here]
1. append()function:
We can use append() function to add item at the end of the list.
Eg:
1) list=[]
2) list.append("A")
3) list.append("B")
4) list.append("C")
5) print(list)
6)
7) D:\Python_classes>py test.py
8) ['A', 'B', 'C']
Eg: To add all elements to list upto 100 which are divisible by 10
1) list=[]
2) for i in range(101):
3) ifi%10==0:
4) list.append(i)
5) print(list)
6)
7)
8) D:\Python_classes>py test.py
9) [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
2. insert()function:
1) n=[1,2,3,4,5]
2) n.insert(1,888)
3) print(n)
4)
5) D:\Python_classes>py test.py
6) [1, 888, 2, 3, 4, 5]
Eg:
1) n=[1,2,3,4,5]
2) n.insert(10,777)
3) n.insert(-10,999)
4) print(n)
5)
[Type here]
6) D:\Python_classes>pytest.py
7) [999, 1, 2, 3, 4, 5, 777]
Note:If the specified index is greater than max index then element will be inserted at last
position. If the specified index is smaller than min index then element will be inserted at
first position.
3. extend()function:
l1.extend(l2)
all items present in l2 will be added tol1
Eg:
1) order1=["Chicken","Mutton","Fish"]
2) order2=["RC","KF","FO"]
3) order1.extend(order2)
4) print(order1)
5)
6) D:\Python_classes>py test.py
7) ['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']
Eg:
1) order=["Chicken","Mutton","Fish"]
2) order.extend("Mushroom")
3) print(order)
4)
5) D:\Python_classes>py test.py
6) ['Chicken', 'Mutton', 'Fish', 'M', 'u', 's', 'h', 'r', 'o', 'o', 'm']
4. remove()function:
We can use this function to remove specified item from the list.If the item present
multiple times then only first occurrence will be removed.
[Type here]
1) n=[10,20,10,30]
2) n.remove(10)
3) print(n)
4)
5) D:\Python_classes>py test.py
6) [20, 10, 30]
If the specified item not present in list then we will get ValueError
1) n=[10,20,10,30]
2) n.remove(40)
3) print(n)
4)
5) ValueError: list.remove(x): x not in list
Note:Hence before using remove() method first we have to check specified element
present in the list or not by using in operator.
5. pop()function:
Eg:
1) n=[10,20,30,40]
2) print(n.pop())
3) print(n.pop())
4) print(n)
5)
6) D:\Python_classes>py test.py
7) 40
8) 30
9) [10, 20]
Eg:
1) n=[]
2) print(n.pop()) ==> IndexError: pop from empty list
[Type here]
Note:
1. pop() is the only function which manipulates the list and returns somevalue
2. In general we can use append() and pop() functions to implement stackdatastructure
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)) ==>IndexError: pop index out of range
remove() pop()
1) We can use to remove special element 1) We can use to remove last element
from the List. from the List.
2) It can’t return any value. 2) It returned removed element.
3) If special element not available then we 3) If List is empty then we get Error.
get VALUE ERROR.
Note:
List objects are dynamic. i.e based on our requirement we can increase and decrease the
size.
1. reverse():
1) n=[10,20,30,40]
2) n.reverse()
3) print(n)
4)
5) D:\Python_classes>py test.py
6) [40, 30, 20, 10]
2. sort()function:
In list by default insertion order is preserved. If want to sort the elements of list according
to default natural sorting order then we should go for sort() method.
1) n=[20,5,15,10,0]
2) n.sort()
3) print(n) #[0,5,10,15,20]
4)
5) s=["Dog","Banana","Cat","Apple"]
6) s.sort()
7) print(s)#['Apple','Banana','Cat','Dog']
Note:To use sort() function, compulsory list should contain only homogeneous elements.
otherwise we will get TypeError
Eg:
1) n=[20,10,"A","B"]
2) n.sort()
3) print(n)
4)
5) TypeError: '<' not supported between instances of 'str' and'int'
Note:In Python 2 if List contains both numbers and Strings then sort() function first sort
numbers followed by strings
1) n=[20,"B",10,"A"]
2) n.sort()
[Type here]
3) print(n)# [10,20,'A','B']
Eg:
1. n=[40,10,30,20]
2. n.sort()
3. print(n) ==>[10,20,30,40]
4. n.sort(reverse=True)
5. print(n) ===>[40,30,20,10]
6. n.sort(reverse=False)
7. print(n) ==>[10,20,30,40]
Eg:
1) x=[10,20,30,40]
2) y=x 10 20 30 40
3) print(id(x)) x
4) print(id(y)) y
The problem in this approach is by using one reference variable if we are changing
content,then those changes will be reflected to the other reference variable.
1) x=[10,20,30,40]
2) y=x 10 20 30 40
3) y[1]=777 x 777
4) print(x)==>[10,777,30,40] y
1. By using sliceoperator:
1) x=[10,20,30,40]
2) y=x[:]
3) y[1]=777
4) print(x) ==>[10,20,30,40]
5) print(y) ==>[10,777,30,40]
10 20 30 40
x
10 20 30 40
777
y
2. By using copy()function:
1) x=[10,20,30,40]
2) y=x.copy()
3) y[1]=777
4) print(x) ==>[10,20,30,40]
5) print(y) ==>[10,777,30,40]
10 20 30 40
x
10 20 30 40
777
y
1. Concatenationoperator(+):
1) a=[10,20,30]
2) b=[40,50,60]
3) c=a+b
4) print(c) ==>[10,20,30,40,50,60]
Eg:
2. RepetitionOperator(*):
We can use repetition operator * to repeat elements of list specified number of times
Eg:
1) x=[10,20,30]
2) y=x*3
3) print(y)==>[10,20,30,10,20,30,10,20,30]
Eg:
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
[Type here]
Note:
Whenever we are using comparison operators(==,!=) for List objects then the following
should be considered
1. The number of elements
2. The order ofelements
3. The content of elements (casesensitive)
Eg:
1. x=[50,20,30]
2. y=[40,50,60,100,200]
3. print(x>y) True
4. print(x>=y) True
5. print(x<y) False
6. print(x<=y) False
Eg:
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
6. print(x<=y) True
Membership operators:
We can check whether element is a member of the list or not by using memebership
operators.
in operator
not inoperator
Eg:
1. n=[10,20,30,40]
2. print (10 in n)
3. print (10 not inn)
4. print (50 in n)
5. print (50 not inn)
6.
7. Output
[Type here]
8. True
9. False
10. False
11. True
clear() function:
Eg:
1. n=[10,20,30,40]
2. print(n)
3. n.clear()
4. print(n)
5.
6. Output
7. D:\Python_classes>py test.py
8. [10, 20, 30, 40]
9. []
Nested Lists:
Sometimes we can take one list inside another list. Such type of lists are called nested
lists.
Eg:
1. n=[10,20,[30,40]]
2. print(n)
3. print(n[0])
4. print(n[2])
5. print(n[2][0])
6. print(n[2][1])
7.
8. Output
9. D:\Python_classes>py test.py
10. [10, 20, [30, 40]]
11. 10
12. [30, 40]
13. 30
14. 40
Note:We can access nested list elements by using index just like accessing multi
dimensional array elements.
[Type here]
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 inrange(len(n[i])):
9) print(n[i][j],end='')
10) print()
11)
12) Output
13) D:\Python_classes>py test.py
14) [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
15) Elements by Row wise:
16) [10, 20, 30]
17) [40, 50, 60]
18) [70, 80, 90]
19) Elements by Matrix style:
20) 10 20 30
21) 40 50 60
22) 70 80 90
List Comprehensions:
It is very easy and compact way of creating list objects from any iterable objects(like
list,tuple,dictionary,range etc) based on some condition.
Syntax:
list=[expression for item in list if condition]
Eg:
Eg:
1) words=["Balaiah","Nag","Venkatesh","Chiranjeevi"]
2) l=[w[0] for w in words]
3) print(l)
4)
5) Output['B', 'N', 'V', 'C']
Eg:
1) num1=[10,20,30,40]
2) num2=[30,40,50,60]
3) num3=[ i for i in num1 if i not in num2]
4) print(num3) [10,20]
5)
6) common elements present in num1 and num2
7) num4=[i for i in num1 if i in num2]
8) print(num4) [30, 40]
Eg:
1) vowels=['a','e','i','o','u']
2) word=input("Enter the word to search for vowels: ")
3) found=[]
4) for letter in word:
5) if letter invowels:
6) if letter not in found:
7) found.append(letter)
8) print(found)
9) print("The number of different vowels present in",word,"is",len(found))
10)
11)
12) D:\Python_classes>py test.py
[Type here]
list out all functions of list and write a program to use these functions
[Type here]
Eg:
1. t=10,20,30,40
2. print(t)
3. print(type(t))
4.
5. Output
6. (10, 20, 30, 40)
7. <class 'tuple'>
8.
9. t=()
10. print(type(t)) # tuple
Note:We have to take special care about single valued tuple.compulsary the value
should ends with comma,otherwise it is not treated as tuple.
Eg:
1. t=(10)
2. print(t)
3. print(type(t))
4.
5. Output
6. 10
7. <class 'int'>
[Type here]
Eg:
1. t=(10,)
2. print(t)
3. print(type(t))
4.
5. Output
6. (10,)
7. <class 'tuple'>
1. t=()
2. t=10,20,30,40
3. t=10
4. t=10,
5. t=(10)
6. t=(10,)
7.t=(10,20,30,40)
Tuple creation:
1. t=()
creation of empty tuple
2. t=(10,)
t=10,
creation of single valued tuple ,parenthesis are optional,should ends with comma
3.t=10,20,30
t=(10,20,30)
creation of multi values tuples & parenthesis are optional
1. By usingindex:
1. t=(10,20,30,40,50,60)
2. print(t[0]) #10
3. print(t[-1]) #60
4. print(t[100]) IndexError: tuple index out ofrange
2. By using sliceoperator:
1. t=(10,20,30,40,50,60)
2. print(t[2:5])
3. print(t[2:100])
4. print(t[::2])
5.
6. Output
7. (30, 40,50)
8. (30, 40, 50, 60)
9. (10, 30,50)
Tuple vs immutability:
Once we creates tuple,we cannot change its content.
Hence tuple objects are immutable.
Eg:
t=(10,20,30,40)
t[1]=70 TypeError: 'tuple' object does not support itemassignment
1. ConcatenationOperator(+):
1. t1=(10,20,30)
2. t2=(40,50,60)
3. t3=t1+t2
4. print(t3) #(10,20,30,40,50,60)
[Type here]
1. t1=(10,20,30)
2. t2=t1*3
3. print(t2) #(10,20,30,10,20,30,10,20,30)
1. len()
To return number of elements present in the tuple
Eg:
t=(10,20,30,40)
print(len(t))#4
2. count()
To return number of occurrences of given element in the tuple
Eg:
t=(10,20,10,10,20)
print(t.count(10)) #3
3. index()
returns index of first occurrence of the given element.
If the specified element is not available then we will get ValueError.
Eg:
t=(10,20,10,10,20)
print(t.index(10)) #0
print(t.index(30)) ValueError: tuple.index(x): x not in tuple
4. sorted()
To sort elements based on default natural sorting order
1. t=(40,10,30,20)
2. t1=sorted(t)
3. print(t1)
4. print(t)
5.
6. Output
7. [10, 20, 30,40]
8. (40, 10, 30, 20)
t1=sorted(t,reverse=True)
print(t1) [40, 30, 20, 10]
These functions return min and max values according to default natural sorting order.
Eg:
1. t=(40,10,30,20)
2. print(min(t)) #10
3. print(max(t)) #40
6. cmp():
Eg:
1. t1=(10,20,30)
2. t2=(40,50,60)
3. t3=(10,20,30)
4. print(cmp(t1,t2)) # -1
5. print(cmp(t1,t3)) # 0
6. print(cmp(t2,t3)) # +1
Eg:
a=10
b=20
c=30
d=40
t=a,b,c,d
print(t) #(10, 20, 30, 40)
Here a,b,c,d are packed into a tuple t. This is nothing but tuple packing.
[Type here]
Eg:
1. t=(10,20,30,40)
2. a,b,c,d=t
3. print("a=",a,"b=",b,"c=",c,"d=",d)
4.
5. Output
6. a= 10 b= 20 c= 30 d= 40
Note:At the time of tuple unpacking the number of variables and number of values
shouldbesame. ,otherwise we will getValueError.
Eg:
t=(10,20,30,40)
a,b,c=t #ValueError: too many values to unpack (expected3)
Tuple Comprehension:
Tuple Comprehension is not supported by Python.
Here we are not getting tuple object and we are getting generator object.
Q. Write a program to take a tuple of numbers from the keyboard and print its sum and
average?
In both cases insertion order is preserved, duplicate objects are allowed, heterogenous
objects are allowed, index and slicing are supported.
List Tuple
1) List is a Group of Comma separeated 1) Tuple is a Group of Comma separeated
Values within Square Brackets and Square Values within Parenthesis and Parenthesis
Brackets are mandatory. are optional.
Eg: i = [10, 20, 30, 40] Eg: t = (10, 20, 30, 40)
t = 10, 20, 30, 40
2) List Objects are Mutable i.e. once we 2) Tuple Objeccts are Immutable i.e. once
creates List Object we can perform any we creates Tuple Object we cannot change
changes in that Object. its content.
Eg: i[1] = 70 t[1] = 70 ValueError: tuple object does
not support item assignment.
3) If the Content is not fixed and keep on 3) If the content is fixed and never changes
changing then we should go for List. then we should go for Tuple.
4) List Objects can not used as Keys for 4) Tuple Objects can be used as Keys for
Dictionries because Keys should be Dictionries because Keys should be
Hashable and Immutable. Hashable and Immutable.
[Type here]
Set DataStructure
If we want to represent a group of unique values as a single entity thenwe should go
for set.
Duplicates are notallowed.
Insertion order is not preserved.But we can sort theelements.
Indexing and slicing not allowed for theset.
Heterogeneous elements areallowed.
Setobjectsaremutablei.eoncewecreatessetobjectwecanperformanychangesin that
object based on ourrequirement.
We can represent set elements within curly braces and with commaseperation
We can apply mathematical operations like union,intersection,difference etc onset
objects.
1. s={10,20,30,40}
2. print(s)
3. print(type(s))
4.
5. Output
6. {40, 10, 20, 30}
7. <class 'set'>
s=set(any sequence)
Eg 1:
1. l = [10,20,30,40,10,20,10]
2. s=set(l)
3. print(s) # {40, 10, 20, 30}
Eg 2:
1. s=set(range(5))
2. print(s) #{0, 1, 2, 3, 4}
Eg:
1. s={}
2. print(s)
3. print(type(s))
4.
5. Output
6. {}
7. <class 'dict'>
Eg:
1. s=set()
2. print(s)
3. print(type(s))
4.
5. Output
6. set()
7. <class 'set'>
Eg:
1. s={10,20,30}
2. s.add(40);
3. print(s) #{40, 10, 20, 30}
2. update(x,y,z):
Eg:
1. s={10,20,30}
2. l=[40,50,60,10]
3. s.update(l,range(5))
4. print(s)
[Type here]
5.
We can use add() to add individual item to the Set,where as we can use update() function
to add multiple items to Set.
add() function can take only one argument where as update() function can take any
number of arguments but all arguments should be iterable objects.
1.s.add(10)
2. s.add(10,20,30) TypeError: add() takes exactly one argument (3given)
3. s.update(10) TypeError: 'int' object is not iterable
4.s.update(range(1,10,2),range(0,10,2))
3. copy():
s={10,20,30}
s1=s.copy()
print(s1)
4. pop():
Eg:
1. s={40,10,30,20}
2. print(s)
3. print(s.pop())
4. print(s)
5.
6. Output
7. {40, 10, 20, 30}
8. 40
9. {10, 20, 30}
[Type here]
5. remove(x):
s={40,10,30,20}
s.remove(30)
print(s) # {40, 10,20}
s.remove(50) ==>KeyError: 50
6. discard(x):
s={10,20,30}
s.discard(10)
print(s) ===>{20, 30}
s.discard(50)
print(s) ==>{20,30}
7.clear():
1. s={10,20,30}
2. print(s)
3. s.clear()
4. print(s)
5.
6. Output
7. {10, 20, 30}
8. set()
[Type here]
x.union(y) ==>We can use this function to return all elements present in both sets
x.union(y)or x|y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.union(y)) #{10, 20, 30, 40, 50,60}
print(x|y) #{10, 20, 30, 40, 50,60}
2. intersection():
x.intersection(y) orx&y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.intersection(y)) #{40,30}
print(x&y) #{40, 30}
3. difference():
x.difference(y) or x-y
returns the elements present in x but not in y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.difference(y)) #{10, 20}
print(x-y) #{10,20}
print(y-x) #{50,60}
[Type here]
4. symmetric_difference():
x. symmetric_difference(y) or x^y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.symmetric_difference(y)) #{10, 50, 20,60}
print(x^y) #{10, 50, 20,60}
1. s=set("venkat")
2. print(s)
3. print('d' in s)
4. print('z' in s)
5.
6. Output
7. {'u', 'g', 'r', 'd', 'a'}
8. True
9. False
Set Comprehension:
Set comprehension is possible.
s={x*xforx in range(5)}
print(s) #{0, 1, 4, 9,16}
Approach-1:
Approach-2:
Eg:
rollno --- name
phone number--address
ipaddress -- domainname
Note:In C++ and Java Dictionaries are known as "Map" where as in Perl and Ruby it is
known as "Hash"
d[100]="venkat
" d[200]="ravi"
d[300]="shiva"
print(d) #{100: 'venkat', 200: 'ravi', 300: 'shiva'}
d={key:value, key:value}
[Type here]
d={100:'venkat' ,200:'ravi',
300:'shiva'} print(d[100])
#venkat
print(d[300]) #shiva
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 only in Python 2 but not in Python 3. Hence
compulsory we have to use in operator.
if 400 in d:
print(d[400])
If the key is not available then a new entry will be added to the dictionary with the
specified key-value pair
If the key is already available then old value will be replaced with new value.
Eg:
1. d={100:"venkat",200:"ravi",300:"shiva"}
2. print(d)
3. d[400]="pavan"
4. print(d)
5. d[100]="sunny"
6. print(d)
7.
8. Output
9. {100: 'venkat', 200: 'ravi', 300: 'shiva'}
10. {100: 'venkat', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
11. {100: 'sunny', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
Eg:
1. d={100:"venkat",200:"ravi",300:"shiva"}
2. print(d)
3. del d[100]
4. print(d)
5. del d[400]
6.
7. Output
8. {100: 'venkat', 200: 'ravi', 300: 'shiva'}
[Type here]
d.clear()
Eg:
1. d={100:"venkat",200:"ravi",300:"shiva"}
2. print(d)
3. d.clear()
4. print(d)
5.
6. Output
7. {100: 'venkat', 200: 'ravi', 300: 'shiva'}
8. {}
del d
Eg:
1. d={100:"venkat",200:"ravi",300:"shiva"}
2. print(d)
3. del d
4. print(d)
5.
6. Output
7. {100: 'venkat', 200: 'ravi', 300: 'shiva'}
8. NameError: name 'd' is not defined
To create a dictionary
2. len()
3. clear():
4. get():
d.get(key)
If the key is available then returns the corresponding value otherwise returns None.It
wont raise any error.
d.get(key,defaultvalue)
If the key is available then returns the corresponding value otherwise returns default
value.
Eg:
d={100:"venkat",200:"ravi",300:"shiva
"} print(d[100]) ==>venkat
print(d[400]) ==>KeyError:400
print(d.get(100)) ==venkat
print(d.get(400)) ==>None
print(d.get(100,"Guest")) ==venkat
print(d.get(400,"Guest")) ==>Guest
3. pop():
d.pop(key)
It removes the entry associated with the specified key and returns the corresponding
value
If the specified key is not available then we will get KeyError
Eg:
1) d={100:"venkat",200:"ravi",300:"shiva"}
2) print(d.pop(100))
3) print(d)
4) print(d.pop(400))
5)
6) Output
[Type here]
7) venkat
8) {200: 'ravi', 300: 'shiva'}
9) KeyError: 400
4. popitem():
Eg:
1) d={100:"venkat",200:"ravi",300:"shiva"}
2) print(d)
3) print(d.popitem())
4) print(d)
5)
6) Output
7) {100: 'venkat', 200: 'ravi', 300: 'shiva'}
8) (300, 'shiva')
9) {100: 'venkat', 200: 'ravi'}
5. keys():
Eg:
1) d={100:"venkat",200:"ravi",300:"shiva"}
2) print(d.keys())
3) for k in d.keys():
4) print(k)
5)
6) Output
7) dict_keys([100, 200, 300])
8) 100
9) 200
10) 300
6. values():
Eg:
1. d={100:"venkat",200:"ravi",300:"shiva"}
2. print(d.values())
3. for v in d.values():
4. print(v)
5.
6. Output
7. dict_values(['venkat', 'ravi', 'shiva'])
8. venkat
9. ravi
10. shiva
7. items():
[(k,v),(k,v),(k,v)]
Eg:
1. d={100:"venkat",200:"ravi",300:"shiva"}
2. for k,v in d.items():
3. print(k,"--",v)
4.
5. Output
6. 100 -- venkat
7. 200 -- ravi
8. 300 -- shiva
8. copy():
d1=d.copy();
9. setdefault():
d.setdefault(k,v)
If the key is already available then this function returns the corresponding value.
If the key is not available then the specified key-value will be added as new item to the
dictionary.
[Type here]
Eg:
1. d={100:"venkat",200:"ravi",300:"shiva"}
2. print(d.setdefault(400,"pavan"))
3. print(d)
4. print(d.setdefault(100,"sachin"))
5. print(d)
6.
7. Output
8. pavan
9. {100: 'venkat', 200: 'ravi', 300: 'shiva', 400:'pavan'}
10. venkat
11. {100: 'venkat', 200: 'ravi', 300: 'shiva', 400:'pavan'}
10. update():
d.update(x)
All items present in the dictionary x will be added to dictionary d
Q. Write a program to take dictionary from the keyboard and print the sum
of values?
1. d=eval(input("Enter dictionary:"))
2. s=sum(d.values())
3. print("Sum= ",s)
4.
5. Output
6. D:\Python_classes>py test.py
7. Enter dictionary:{'A':100,'B':200,'C':300}
8. Sum= 600
Q. Write a program to accept student name and marks from the keyboard
and creates a dictionary. Also display student marks by taking student name
as input?
Dictionary Comprehension:
Comprehension concept applicable for dictionaries also.
FUNCTIONS
If a group of statements is repeatedly required then it is not recommended to write these
statements everytime seperately.We have to define these statements as a single unit and
we can call that unit any number of times based on our requirement withoutrewriting.
This unit is nothing but function.
1. Built inFunctions
2. User DefinedFunctions
1. Built inFunctions:
The functions which are coming along with Python software automatically,are called built
in functions or pre definedfunctions
Eg:
id()
type()
input()
eval()
etc..
2. User DefinedFunctions:
The functions which are developed by programmer explicitly according to business
requirements ,are called user defined functions.
def function_name(parameters) :
""" docstring"""
----
-----
return value
[Type here]
test.py:
1) defwish():
2) print("Hello GoodMorning")
3) wish()
4) wish()
5) wish()
Parameters
Parameters are inputs to the function. If a function contains parameters,then at the time
of calling,compulsory we should provide values otherwise,otherwise we will get error.
Eg: Write a function to take name of the student as input and print wish message by
name.
1. def wish(name):
2. print("Hello",name," Good Morning")
3. wish("Venkat")
4. wish("Ravi")
5.
6.
7. D:\Python_classes>py test.py
8. Hello Venkat Good Morning
9. Hello Ravi GoodMorning
Eg: 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*number)
3. squareIt(4)
4. squareIt(5)
5.
6. D:\Python_classes>py test.py
7. The Square of 4 is 16
8. The Square of 5 is 25
[Type here]
Return Statement:
Function can take input values as parameters and executes business logic, and returns
output to the caller with return statement.
If we are not writing return statement then default return value is None
Eg:
1. def f1():
2. print("Hello")
3. f1()
4. print(f1())
5.
6. Output
7. Hello
8. Hello
9. None
1) def fact(num):
2) result=1
3) whilenum>=1:
4) result=result*num
5) num=num-1
6) returnresult
7) for i in range(1,5):
8) print("The Factorial of",i,"is:",fact(i))
9)
10) Output
11) D:\Python_classes>py test.py
12) The Factorial of 1 is : 1
13) The Factorial of 2 is : 2
14) The Factorial of 3 is : 6
15) The Factorial of 4 is : 24
Eg1:
1) def sum_sub(a,b):
2) sum=a+b
3) sub=a-b
4) returnsum,sub
5) x,y=sum_sub(100,50)
6) print("The Sum is :",x)
7) print("The Subtraction is :",y)
8)
9) Output
10) The Sum is : 150
11) The Subtraction is : 50
Eg2:
1) def calc(a,b):
2) sum=a+b
3) sub=a-b
4) mul=a*b
5) div=a/b
6) return sum,sub,mul,div
7) t=calc(100,50)
8) print("The Results are")
[Type here]
9) for i in t:
10) print(i)
11)
12) Output
13) The Results are
14) 150
15) 50
16) 5000
17) 2.0
Types of arguments
def f1(a,b):
------
------
------
f1(10,20)
1. positional arguments
2. keyword arguments
3. default arguments
4. Variable lengtharguments
1. positional arguments:
def sub(a,b):
print(a-b)
sub(100,200)
sub(200,100)
The number of arguments and position of arguments must be matched. If we change the
order then result may be changed.
2. keywordarguments:
Eg:
1. def wish(name,msg):
2. print("Hello",name,msg)
3. wish(name="Venkat",msg="Good Morning")
4. wish(msg="Good Morning",name="Venkat")
5.
6. Output
7. Hello Venkat Good Morning
8. Hello Venkat Good Morning
Here the order of arguments is not important but number of arguments must be matched.
Note:
We can use both positional and keyword arguments simultaneously. But first we have to
take positional arguments and then keyword arguments,otherwise we will get
syntaxerror.
def wish(name,msg):
print("Hello",name,msg)
wish("Venkat","GoodMorning") ==>valid
wish("Venkat",msg="GoodMorning") ==>valid
wish(name="Venkat","GoodMorning") ==>invalid
SyntaxError: positional argument follows keywordargument
3. DefaultArguments:
Eg:
1) def wish(name="Guest"):
2) print("Hello",name,"GoodMorning")
3)
4) wish("Venkat")
5) wish()
6)
7) Output
8) Hello Venkat Good Morning
9) Hello Guest Good Morning
[Type here]
If we are not passing any name then only default value will be considered.
***Note:
4. Variable lengtharguments:
def f1(*n):
We can call this function by passing any number of arguments including zero number.
Internally all these values represented in the form of tuple.
Eg:
1) def sum(*n):
2) total=0
3) for n1 inn:
4) total=total+n1
5) print("TheSum=",total)
6)
7) sum()
8) sum(10)
9) sum(10,20)
10) sum(10,20,30,40)
11)
12) Output
13) The Sum= 0
14) The Sum= 10
15) The Sum= 30
16) The Sum= 100
Note:
We can mix variable length arguments with positional arguments.
[Type here]
Eg:
1) def f1(n1,*s):
2) print(n1)
3) for s1 in
4) print(s1)
s:5)
6) f1(10)
7) f1(10,20,30,40)
8) f1(10,"A",30,"B")
9)
10) Output
11)10
12) 10
13)20
14) 30
15)40
16) 10
17)A
18) 30
19)B
Note:After variable length argument,if we are taking any other arguments then we
should provide values as keyword arguments.
Eg:
1) def f1(*s,n1):
2) for s1 ins:
3) print(s1)
4) print(n1)
5)
6) f1("A","B",n1=10)
7) Output
8) A
9) B
10) 10
f1("A","B",10)==>Invalid
TypeError: f1() missing 1 required keyword-only argument: 'n1'
def f1(**n):
[Type here]
We can call this function by passing any number of keyword arguments. Internally these
keyword arguments will be stored inside a dictionary.
Eg:
1) def display(**kwargs):
2) for k,v inkwargs.items():
3) print(k,"=",v)
4) display(n1=10,n2=20,n3=30)
5) display(rno=100,name="Venkat",marks=70,subject="Java")
6)
7) Output
8) n1 = 10
9) n2 = 20
10) n3 = 30
11) rno = 100
12) name = Venkat
13) marks = 70
14) subject = Java
Case Study:
def f(arg1,arg2,arg3=4,arg4=8):
print(arg1,arg2,arg3,arg4)
1.f(3,2) ==> 3 2 48
2. f(10,20,30,40) ===>10 20 30 40
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'
[Type here]
Library Function
Types of Variables
Python supports 2 types of variables.
1. GlobalVariables
2. LocalVariables
1. Global Variables
The variables which are declared outside of function are called global variables.
These variables can be accessed in all functions of that module.
Eg:
2. LocalVariables:
The variables which are declared inside a function are called local variables.
Local variables are available only for the function in which we declared it.i.e from outside
of function we cannot access.
Eg:
1) def f1():
2) a=10
3) print(a) #valid
4)
5) def f2():
6) print(a) #invalid
7)
8) f1()
9) f2()
10)
11) NameError: name 'a' is not defined
global keyword:
We can use global keyword for the following 2 purposes:
Eg 1:
1) a=10
2) def f1():
3) a=777
4) print(a)
5)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()
11)
12) Output
13) 777
14) 10
[Type here]
Eg2:
1) a=10
2) def f1():
3) globala
4) a=777
5) print(a)
6)
7) def f2():
8) print(a)
9)
10) f1()
11)f2()
12)
13)
14) 777
Output15)77
Eg3:7
1) def f1():
2) a=10
3) print(a)
4)
5) def f2():
6) print(a)
7)
8) f1()
9) f2()
10)
11) NameError: name 'a' is not defined
Eg4:
1) def f1():
2) global a
3) a=10
4) print(a)
5)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()
11)
12) Output
13) 10
14) 10
[Type here]
Note:If global variable and local variable having the same name then we can access
global variable inside a function as follows
1) a=10 #globalvariable
2) def f1():
3) a=777 #localvariable
4) print(a)
5)
6) f1()
print(globals()['a'])
8)
7)
10) 777
9) Output
11) 10
Recursive Functions
A function that calls itself is known as Recursive Function.
Eg:
factorial(3)=3*factorial(2)
=3*2*factorial(1)
=3*2*1*factorial(0)
=3*2*1*1
=6
factorial(n)= n*factorial(n-1)
Eg:
1) deffactorial(n):
2) ifn==0:
3) result=1
4) else:
5) result=n*factorial(n-1)
6) returnresult
7) print("Factorial of 4 is :",factorial(4))
8) print("Factorial of 5 is :",factorial(5))
9)
10) Output
[Type here]
11) Factorial of 4 is : 24
12) Factorial of 5 is : 120
Anonymous Functions:
Sometimes we can declare a function without any name,such type of nameless functions
are called anonymous functions or lambda functions.
The main purpose of anonymous function is just for instant use(i.e for one time usage)
Normal Function:
We can define by using def keyword.
def squareIt(n):
return n*n
lambda Function:
We can define by using lambda keyword
lambda n:n*n
Note:By using Lambda Functions we can write very concise code so that readability of
the program will be improved.
1) s=lambda n:n*n
2) print("The Square of 4 is :",s(4))
3) print("The Square of 5 is :",s(5))
4)
5) Output
6) The Square of 4 is : 16
7) The Square of 5 is : 25
1) s=lambda a,b:a+b
2) print("The Sum of 10,20 is:",s(10,20))
[Type here]
Note:
Lambda Function internally returns expression value and we are not required to write
return statement explicitly.
We can use lambda functions very commonly with filter(),map() and reduce() functions,b'z
these functions expect function as argument.
filter() function:
We can use filter() function to filter values from the given sequence based on some
condition.
filter(function,sequence)
Q. Program to filter only even numbers from the list by using filter()
function?
5) returnFalse
6) l=[0,5,10,15,20,25,30]
7) l1=list(filter(isEven,l))
8) print(l1) #[0,10,20,30]
map() function:
For every element present in the given sequence,apply some functionality and generate
new element with the required modification. For this requirement we should go for
map() function.
Eg: For every element present in the list perform double and generate new list of doubles.
Syntax:
map(function,sequence)
The function can be applied on each element of sequence and generates new sequence.
Eg:Without lambda
1) l=[1,2,3,4,5]
2) def doubleIt(x):
3) return2*x
4) l1=list(map(doubleIt,l))
5) print(l1) #[2, 4, 6, 8, 10]
with lambda
1) l=[1,2,3,4,5]
2) l1=list(map(lambda x:2*x,l))
3) print(l1) #[2, 4, 6, 8,10]
-------------------------------------------------------------
[Type here]
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.
1. l1=[1,2,3,4]
2. l2=[2,3,4,5]
3. l3=list(map(lambdax,y:x*y,l1,l2))
4. print(l3) #[2, 6, 12,20]
reduce() function:
reduce() function reduces sequence of elements into a single element by applying the
specified function.
reduce(function,sequence)
reduce() function present in functools module and hence we should write import
statement.
Eg:
Eg:
1) result=reduce(lambda x,y:x*y,l)
2) print(result) #12000000
Eg:
Note:
In Python every thing is treated asobject.
Even functions also internally treated as objectsonly.
Eg:
1) def f1():
2) print("Hello")
3) print(f1)
4) print(id(f1))
Output
<function f1 at 0x00419618>
4298264
Function Aliasing:
For the existing function we can give another name, which is nothing but function aliasing.
Eg:
1) def wish(name):
2) print("GoodMorning:",name)
3)
4) greeting=wish
5) print(id(wish))
6) print(id(greeting))
7)
8) greeting('Venkat')
9) wish('Venkat')
Output
4429336
4429336
Good Morning:
Venkat Good
Morning: Venkat
Note:In the above example only one function is available but we can call that function by using
either wish name or greeting name.
If we delete one name still we can access that function by using alias name
Eg:
1) def wish(name):
2) print("GoodMorning:",name)
[Type here]
3)
4) greeting=wish
5)
6) greeting('Venkat')
7) wish('Venkat')
8)
9) del wish
10) #wish('Venkat') ==>NameError: name 'wish' is not defined
11) greeting('Pavan')
Output
Good Morning:
Venkat Good
Morning: Venkat
Good Morning: Pavan
Nested Functions:
We can declare a function inside another function, such type of functions are called Nested
functions.
Eg:
1) def outer():
2) print("outer function started")
3) def inner():
4) print("inner function execution")
5) print("outer function calling inner function")
6) inner()
7) outer()
8) #inner() ==>NameError: name 'inner' is notdefined
Output
outer function started
outer function calling inner function
inner function execution
In the above example inner() function is local to outer() function and hence it is not possible to call
directly from outside of outer() function.
Eg:
1) def outer():
2) print("outer function started")
3) def inner():
4) print("inner function execution")
[Type here]
Output
outer function started
outer function returning inner function
inner functionexecution
inner function execution
inner functionexecution
In the first case for the outer() function we are providing another name f1(functionaliasing).
Butinthesecondcasewecallingouter()function,whichreturnsinnerfunction.Forthatinner
function() we are providing another namef1
Eg:filter(function,sequence)
map(function,sequence)
reduce(function,sequence)
[Type here]
Function Decorators:
Decorator is a function which can take a function as argument and extend its functionality
and returns modified function with extended functionality.
The main objective of decorator functions is we can extend the functionality of existing
functions without modifies that function.
1) defwish(name):
2) print("Hello",name,"GoodMorning")
This function can always print same output for any name
But we want to modify this function to provide different message if name is Sunny.
We can do this without touching wish() function by using decorator.
Eg:
1) def decor(func):
2) definner(name):
3) if name=="Sunny":
4) print("Hello Sunny Bad Morning")
5) else:
6) func(name)
7) returninner
8)
9) @decor
10) def wish(name):
11) print("Hello",name,"GoodMorning")
12)
13)wish("Venkat")
14) wish("Ravi")
15)wish("Sunny")
16)
[Type here]
17) Output
18) Hello Venkat Good Morning
19) Hello Ravi Good Morning
20) Hello Sunny Bad Morning
In the above program whenever we call wish() function automatically decor function will
be executed.
1) def decor(func):
2) definner(name):
3) if name=="Sunny":
4) print("Hello Sunny Bad Morning")
5) else:
6) func(name)
7) returninner
8)
9)
10) def wish(name):
11) print("Hello",name,"GoodMorning")
12)
13) decorfunction=decor(wish)
14)
15) wish("Venkat") #decorator wont be executed
16) wish("Sunny") #decorator wont be executed
17)
18) decorfunction("Venkat")#decorator will be executed
19) decorfunction("Sunny")#decorator will be executed
20)
21) Output
22) Hello Venkat Good Morning
23) Hello Sunny Good Morning
24) Hello Venkat Good Morning
25) Hello Sunny Bad Morning
Eg 2:
1) def smart_division(func):
2) def inner(a,b):
3) print("We are dividing",a,"with",b)
4) if b==0:
5) print("OOPS...cannot divide")
6) return
7) else:
8) return func(a,b)
[Type here]
9) return inner
10)
11) @smart_division
12) def division(a,b):
13) return a/b
14)
15) print(division(20,2))
16) print(division(20,0))
17)
18) without decorator we will get Error.In this case output is:
19)
20) 10.0
21) Traceback (most recent call last):
22) File "test.py", line 16, in <module>
23) print(division(20,0))
24) File "test.py", line 13, in division
25) return a/b
26) ZeroDivisionError: division by zero
with decorator we won't get any error. In this case output is:
Decorator Chaining
We can define multiple decorators for the same function and all these decorators will
form Decorator Chaining.
Eg:
@decor1
@decor
def num():
For num() function we are applying 2 decorator functions. First inner decorator will work
and then outer decorator.
Eg:
1) def decor1(func):
2) definner():
3) x=func()
4) returnx*x
[Type here]
5) return inner
6)
7) def decor(func):
8) definner():
9) x=func()
10) return2*x
11) return inner
12)
13) @decor1
14) @decor
15) def num():
16) return10
17)
18) print(num())
D:\venkatclasses>py
decaratordemo1.py Second
Decor(decor1) Execution
First Decor(decor) Function Execution
Hello Venkat Good Morning
[Type here]
Generators
Generator is a function which is responsible to generate a sequence of values.
We can write generator functions just like ordinary functions, but it uses yield keyword to
return values.
yield
Eg1:
1) def mygen():
2) yield'A'
3) yield'B'
4) yield'C'
5)
6) g=mygen()
7) print(type(g))
8)
9) print(next(g))
10) print(next(g))
11) print(next(g))
12) print(next(g))
13)
14) Output
15) <class 'generator'>
16) A
17) B
18) C
19) Traceback (most recent call last):
20) File "test.py", line 12, in <module>
21) print(next(g))
22) StopIteration
Eg2:
1) def countdown(num):
2) print("Start Countdown")
3) while(num>0):
4) yield num
5) num=num-1
6)
7) values=countdown(5)
8) for x in values:
[Type here]
9) print(x)
10)
11) Output
12) Start Countdown
13)5
14) 4
15)3
16) 2
17)1
1) def firstn(num):
2) n=1
3) whilen<=num:
4) yieldn
5) n=n+1
6)
7) values=firstn(5)
8) for x in values:
9) print(x)
10)
11) Output
12) 1
13) 2
14) 3
15) 4
16) 5
Eg: 0,1,1,2,3,5,8,13,21,...
1) def fib():
2) a,b=0,1
3) whileTrue:
4) yield a
5) a,b=b,a+b
6) for f in fib():
7) iff>100:
8) break
9) print(f)
[Type here]
10)
11) Output
12) 0
13) 1
14) 1
15) 2
16) 3
17) 5
18) 8
19) 13
20) 21
21) 34
22) 55
23) 89
24) }
25) yieldperson
26)
27) '''''t1 = time.clock()
28) people = people_list(10000000)
29) t2 = time.clock()'''
30)
31) t1 = time.clock()
32) people = people_generator(10000000)
33) t2 = time.clock()
34)
35) print('Took {}'.format(t2-t1))
Note:In the above program observe the differnce wrt execution time by using list and generators
We will get MemoryError in this case because all these values are required to store in the memory.
Generators:
g=(x*x for x in range(10000000000000000))
print(next(g))
Output: 0
We won't get any MemoryError because the values won't be stored at the beginning
[Type here]
Modules
A group of functions, variables and classes saved to a file, which is nothing but module.
Eg: venkatmath.py
1) x=888
2)
3) def add(a,b):
4) print("TheSum:",a+b)
5)
6) def product(a,b):
7) print("TheProduct:",a*b)
If we want to use members of module in our program then we should import that module.
import modulename
test.py:
1) import venkatmath
2) print(venkatmath.x)
3) venkatmath.add(10,20)
4) venkatmath.product(10,20)
5)
6) Output
7) 888
8) The Sum: 30
9) The Product: 200
[Type here]
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.
test.py:
1) import venkatmath as m
2) print(m.x)
3) m.add(10,20)
4) m.product(10,20)
Eg:
from venkatmath import
x,add print(x)
add(10,20)
product(10,20)==> NameError: name 'product' is not defined
test.py:
member aliasing:
from venkatmath import x as y,add as
sum print(y)
sum(10,20)
Once we defined as alias name,we should use alias name only and we should not use
original name
Eg:
from venkatmath import x as y
print(x)==>NameError: name 'x' is not defined
Reloading a Module:
By default module will be loaded only once eventhough we are importing multiple
multiple times.
1) import time
2) from imp import reload
3) import module1
4) time.sleep(30)
5) reload(module1)
6) time.sleep(30)
7) reload(module1)
8) print("This is test file")
Note: In the above program, everytime updated version of module1 will be available to
our program
[Type here]
module1.py:
test.py
1) importmodule1
2) import module1
3) importmodule1
4) import module1
5) print("This is test module")
6)
7) Output
8) This is from module1
9) This is test module
In the above program test module will be loaded only once eventhough we are importing
multiple times.
The problem in this approach is after loading a module if it is updated outside then
updated version of module1 is not available to our program.
We can solve this problem by reloading module explicitly based on our requirement.
We can reload by using reload() function of imp module.
import imp
imp.reload(module1)
test.py:
1) import module1
2) import module1
3) from imp import reload
4) reload(module1)
5) reload(module1)
6) reload(module1)
7) print("This is test module")
In the above program module1 will be loaded 4 times in that 1 time by default and 3 times
explicitly. In this case output is
1) This is frommodule1
2) This is from module1
3) This is frommodule1
4) This is from module1
5) This is test module
[Type here]
The main advantage of explicit module reloading is we can ensure that updated version is
always available to our program.
Python provides inbuilt function dir() to list out all members of current module or a
specified module.
Eg 1: test.py
1) x=10
2) y=20
3) def f1():
4) print("Hello")
5) print(dir()) # To print all members of current module
6)
7) Output
8) ['annotations', 'builtins', 'cached', 'doc', 'file', 'loader', 'nam
e', 'package', 'spec', 'f1', 'x', 'y']
venkatmath.py:
1) x=888
2)
3) def add(a,b):
4) print("TheSum:",a+b)
5)
6) def product(a,b):
7) print("TheProduct:",a*b)
test.py:
1) import venkatmath
2) print(dir(venkatmath))
3)
4) Output
5) ['builtins', 'cached', 'doc', 'file', 'loader', 'name',
6) ' package ', ' spec ', 'add', 'product', 'x']
Note: For every module at the time of execution Python interpreter will add some special
properties automatically for internal use.
[Type here]
Based on our requirement we can access these properties also in our program.
Eg: 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 )
9)
10) Output
11) <module 'builtins' (built-in)>
12) None
13) None
test.py
TheSpecialvariable name :
For every Python program , a special variablenamewill be added internally. This
variable stores information regarding whether the program is executed asan
individual program or as amodule.
If the program executed as an individual program then the value of this variable is
main
If the program executed as a module from some other program then the value of this
variable is the name of module where it is defined.
Hence by usingthis name variable we can identify whether the program executed
directly or as amodule.
[Type here]
Demo program:
module1.py:
1) def f1():
2) if name ==' main':
3) print("The code executed as aprogram")
4) else:
5) print("The code executed as a module from some otherprogram")
6) f1()
test.py:
1) import module1
2) module1.f1()
3)
4) D:\Python_classes>py module1.py
5) The code executed as a program
6)
7) D:\Python_classes>py test.py
8) The code executed as a module from some other program
9) The code executed as a module from some other program
1. sqrt(x)
2. ceil(x)
3. floor(x)
4. fabs(x)
5.log(x)
6. sin(x)
7. tan(x)
....
Eg:
7)
8) Output
9) 2.0
10) 11
11) 10
12) 10.6
13) 10.6
Note:
We can find help for any module by using help() function
Eg:
import math
help(math)
1. random()function:
This function always generate some float value between 0 and 1 ( not inclusive)
0<x<1
Eg:
2. randint()function:
Eg:
3. uniform():
Eg:
4. randrange([start],stop,[step])
Eg1:
Eg2:
Eg 3:
5. choice()function:
Eg:
OutputB
unny
pinny
Bunny
Sunny
Bunny
pinny
pinny
Vinny
Bunny
Sunny
[Type here]
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.
init.py
File 1
File 1 File 1
init.py init.py
Loan
[Type here]
init.py
File 1
File 1 File 1
init.py init.py
Loan
Eg1:
D:\Python_classes>
|-test.py
|-pack1
|-module1.py
|-init.py
init.py:
empty file
module1.py:
def f1():
print("Hello this is from module1 present in pack1")
test.py (version-1):
import pack1.module1
pack1.module1.f1()
[Type here]
test.py (version-2):
Eg 2:
D:\Python_classes>
|-test.py
|-com
|-module1.py
|-init.py
|-venkatsoft
|-module2.py
|-init.py
init.py:
empty file
module1.py:
def f1():
print("Hello this is from module1 present in com")
module2.py:
deff2():
print("Hello this is from module2 present incom.venkatsoft")
test.py:
5.
6. Output
7. D:\Python_classes>pytest.py
8. Hello this is from module1 present incom
9. Hello this is from module2 present incom.venkatsoft
Library
File Handling
As the part of programming requirement, we have to store our data permanently for
future purpose. For this requirement we should go for files.
Files are very common permanent storage areas to store our data.
Types of Files:
There are 2 types of files
1. TextFiles:
2. BinaryFiles:
Usually we can use binary files to store binary data like images,video files, audio files etc...
Opening a File:
Before performing any operation (like read or write) on the file,first we have to open that
file.For this we should use Python's inbuilt function open()
But at the time of open, we have to specify mode,which represents the purpose of
opening file.
f = open(filename, mode)
1. ropenanexistingfileforreadoperation.Thefilepointerispositionedatthe
beginning of the file.If the specified file does not exist then we will get
FileNotFoundError.This is defaultmode.
[Type here]
2. w open an existing file for write operation. If the file already contains some data
thenitwillbeoverridden.Ifthespecifiedfileisnotalreadyavaialblethenthismodewill create
thatfile.
3. a open an existing file for append operation. It won't override existing data.If the
specified file is not already avaialble then this mode will create a newfile.
6. a+ To append and read data from the file.It wont override existingdata.
7. x To open a file in exclusive creation mode for write operation. If the filealready
exists then we will getFileExistsError.
Note: All the above modes are applicable for text files. If the above modes suffixed with
'b' then these represents for binary files.
Eg: rb,wb,ab,r+b,w+b,a+b,xb
f = open("abc.txt","w")
Closing a File:
After completing our operations on the file,it is highly recommended to close the file.
For this we have to use close() function.
f.c lose()
Eg:
1) f=open("abc.txt",'w')
2) print("File Name: ",f.name)
3) print("File Mode: ",f.mode)
4) print("Is File Readable: ",f.readable())
5) print("Is File Writable: ",f.writable())
6) print("Is File Closed : ",f.closed)
7) f.close()
8) print("Is File Closed : ",f.closed)
9)
10)
11) Output
12) D:\Python_classes>py test.py
13) File Name: abc.txt
14) File Mode: w
15) Is File Readable: False
16) Is File Writable: True
17) Is File Closed : False
18) Is File Closed : True
write(str)
writelines(list of lines)
Eg:
1) f=open("abcd.txt",'w')
2) f.write("Venkat\n")
3) f.write("Software\n")
4) f.write("Solutions\n")
5) print("Data written to the file successfully")
6) f.close()
abcd.txt:
Venkat
Software
Solutions
Note: In the above program, data present in the file will be overridden everytime if we
run the program. Instead of overriding if we want append operation then we should open
the file as follows.
f = open("abcd.txt","a")
[Type here]
Eg 2:
1) f=open("abcd.txt",'w')
2) list=["sunny\n","bunny\n","vinny\n","chinny"]
3) f.writelines(list)
4) print("List of lines written to the file successfully")
5) f.close()
abcd.txt:
sunny
bunny
vinny
chinny
Note: while writing data by using write() methods, compulsory we have to provide line
seperator(\n),otherwise total data should be written to a single line.
1) f=open("abc.txt",'r')
2) data=f.read()
3) print(data)
4) f.close()
5)
6) Output
7) sunny
8) bunny
9) chinny
10) vinny
1) f=open("abc.txt",'r')
2) data=f.read(10)
3) print(data)
4) f.close()
5)
[Type here]
6) Output
7) Sunny
8) Bunn
1) f=open("abc.txt",'r')
2) line1=f.readline()
3) print(line1,end='')
4) line2=f.readline()
5) print(line2,end='')
6) line3=f.readline()
7) print(line3,end='')
8) f.close()
9)
10) Output
11) sunny
12) bunny
13) chinny
1) f=open("abc.txt",'r')
2) lines=f.readlines()
3) for line in lines:
4) print(line,end='')
5) f.close()
6)
7) Output
8) sunny
9) bunny
10) chinny
11) vinny
Eg 5:
1) f=open("abc.txt","r")
2) print(f.read(3))
3) print(f.readline())
4) print(f.read(4))
5) print("Remaining data")
6) print(f.read())
7)
8) Output
9) sun
10) ny
11)
12) bunn
13) Remaining data
[Type here]
14) y
15) chinny
16) vinny
1) with open("abc.txt","w") as f:
2) f.write("Venkat\n")
3) f.write("Software\n")
4) f.write("Solutions\n")
5) print("Is File Closed:",f.closed)
6) print("Is File Closed: ",f.closed)
7)
8) Output
9) Is File Closed: False
10) Is File Closed: True
tell():
==>We can use tell() method to return current position of the cursor(file pointer) from
beginning of the file. [ can you plese telll current cursor position]
The position(index) of first character in files is zero just like string index.
Eg:
1) f=open("abc.txt","r")
2) print(f.tell())
3) print(f.read(2))
4) print(f.tell())
5) print(f.read(3))
6) print(f.tell())
abc.txt:
sunny
bunny
chinny
vinny
[Type here]
Output:
0
su
2
nny
5
seek():
f.seek(offset, fromwhere)
Eg:
1) import os,sys
2) fname=input("Enter File Name: ")
3) if os.path.isfile(fname):
4) print("Fileexists:",fname)
5) f=open(fname,"r")
6) else:
7) print("File does not exist:",fname)
8) sys.exit(0)
9) print("The content of file is:")
10) data=f.read()
11) print(data)
12)
13) Output
14) D:\Python_classes>py test.py
15) Enter File Name: venkat.txt
16) File does not exist: venkat.txt
17)
18) D:\Python_classes>py test.py
19) Enter File Name: abc.txt
20) File exists: abc.txt
21) The content of file is:
22) All Students are GEMS!!!
23) All Students areGEMS!!!
24) All Students are GEMS!!!
25) All Students areGEMS!!!
26) All Students are GEMS!!!
27) All Students areGEMS!!!
Note:
sys.exit(0) ===>To exit system without executing rest of the program.
argument represents status code . 0 means normal termination and it is the default value.
[Type here]
1) import os,sys
2) fname=input("Enter File Name:")
3) ifos.path.isfile(fname):
4) print("Fileexists:",fname)
5) f=open(fname,"r")
6) else:
7) print("File does not exist:",fname)
8) sys.exit(0)
9) lcount=wcount=ccount=0
10) for line inf:
11) lcount=lcount+1
12) ccount=ccount+len(line)
13) words=line.split()
14) wcount=wcount+len(words)
15) print("The number of Lines:",lcount)
16) print("The number of Words:",wcount)
17) print("The number of Characters:",ccount)
18)
19) Output
20) D:\Python_classes>pytest.py
21) Enter File Name:venkat.txt
22) File does not exist:
venkat.txt 23)
24) D:\Python_classes>pytest.py
25) Enter File Name:abc.txt
26) File exists:abc.txt
27) The number of Lines:6
28) The number of Words:24
29) The number of Characters: 149
abc.txt: