Core Python Material PDF
Core Python Material PDF
FUNDAMENTALS
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
1 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Introduction
Python is a general purpose high level programming language.
Python was developed by Guido Van Rossam in 1989 while working at National
Research Institute at Netherlands.
But officially Python was made available to public in 1991. The official Date of Birth for
Python is : Feb 20th 1991.
Java:
C:
1) #include<stdio.h>
2) void main()
3) {
4) print("Hello world");
5) }
Python:
print("Hello World")
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
Features of Python:
4) Platform Independent:
Once we write a Python program,it can run on any platform without rewriting once
again.
Internally PVM is responsible to convert into machine understandable form.
5) Portability:
Python programs are portable. ie we can migrate from one platform to another
platform very easily. Python programs will provide same results on any paltform.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
4 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
6) Dynamically Typed:
In Python we are not required to declare type for variables. Whenever we are
assigning the value, based on value, type will be allocated automatically.Hence Python
is considered as dynamically typed language.
But Java, C etc are Statically Typed Languages b'z we have to provide type at the
beginning only.
This dynamic typing nature will provide more flexibility to the programmer.
8) Interpreted:
We are not required to compile Python programs explcitly. Internally Python
interpreter will take care that compilation.
If compilation fails interpreter raised syntax errors. Once compilation success then
PVM (Python Virtual Machine) is responsible to execute.
9) Extensible:
We can use other language programs in Python.
The main advantages of this approach are:
We can use already existing legacy non-Python code
We can improve performance of the application
10) Embedded:
We can use Python programs in any other language programs.
i.e we can embedd Python programs anywhere.
Limitations of Python:
1) Performance wise not up to the mark because it is interpreted language.
2) Not using for mobile Applications.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
5 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Flavors of Python:
1) CPython:
It is the standard flavor of Python. It can be used to work with C lanugage Applications.
2) Jython OR JPython:
It is for Java Applications. It can run on JVM
3) IronPython:
It is for C#.Net platform
4) PyPy:
The main advantage of PyPy is performance will be improved because JIT compiler is
available inside PVM.
5) RubyPython
For Ruby Platforms
6) AnacondaPython
It is specially designed for handling large volume of data processing.
Python Versions:
Python 1.0V introduced in Jan 1994
Python 2.0V introduced in October 2000
Python 3.0V introduced in December 2008
Current versions
Python 3.6.1 Python 2.7.13
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
6 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
IDENTIFIERS
A Name in Python Program is called Identifier.
It can be Class Name OR Function Name OR Module Name OR Variable Name.
a = 10
By mistake if we are using any other symbol like $ then we will get syntax error.
cash = 10 √
ca$h =20
123total
total123 √
3. Identifiers are case sensitive. Of course Python language is case sensitive language.
total=10
TOTAL=999
print(total) #10
print(TOTAL) #999
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
7 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Identifier:
1) Alphabet Symbols (Either Upper case OR Lower case)
6) There is no length limit for Python identifiers. But not recommended to use too
lengthy identifiers.
Note:
4) Eg: __add__
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
8 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
RESERVED WORDS
In Python some words are reserved to represent some meaning or functionality.
Such types of words are called reserved words.
Note:
2. Except the following 3 reserved words, all contain only lower case alphabet symbols.
True
False
None
Eg: a= true
a=True √
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
9 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
DATA TYPES
Data Type represents 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.
1) Int
2) Float
3) Complex
4) Bool
5) Str
6) Bytes
7) Bytearray
8) Range
9) List
10) Tuple
11) Set
12) Frozenset
13) Dict
14) None
10
a = 10 a
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
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
10 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
3) print()
to print the value
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) Decimal form
2) Binary form
3) Octal form
4) Hexa decimal form
Eg: a = 0B1111
a = 0B123
a = b111
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
11 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
III) Octal Form (Base-8):
The allowed digits are : 0 to 7
Literal value should be prefixed with 0o or 0O.
Eg: a = 0o123
a = 0o786
Eg: a = 0XFACE
a = 0XBeef
a = 0XBeer
Note: Being a programmer we can specify literal values in decimal, binary, octal and hexa
decimal forms. But PVM will always provide values only in decimal form.
a=10
b=0o10
c=0X10
d=0B10
print(a)10
print(b)8
print(c)16
print(d)2
Base Conversions
Python provide the following in-built functions for base conversions
1) bin():
We can use bin() to convert from any base to binary
1) >>> bin(15)
2) '0b1111'
3) >>> bin(0o11)
4) '0b1001'
5) >>> bin(0X10)
6) '0b10000'
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
12 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
2) oct():
We can use oct() to convert from any base to octal
1) >>> oct(10)
2) '0o12'
3) >>> oct(0B1111)
4) '0o17'
5) >>> oct(0X123)
6) '0o443'
3) hex():
We can use hex() to convert from any base to hexa decimal
1) >>> hex(100)
2) '0x64'
3) >>> hex(0B111111)
4) '0x3f'
5) >>> hex(0o12345)
6) '0x14e5'
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.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
13 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) >>> f=0B11.01
2) File "<stdin>", line 1
3) f=0B11.01
4) ^
5) SyntaxError: invalid syntax
6)
7) >>> f=0o123.456
8) SyntaxError: invalid syntax
9)
10) >>> f=0X123.456
11) SyntaxError: invalid syntax
j2 = -1
a + bj
j=
Real Part Imaginary Part
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: invalid syntax
1) >>> a=10+1.5j
2) >>> b=20+2.5j
3) >>> c=a+b
4) >>> print(c)
5) (30+4j)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
14 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
6) >>> type(c)
7) <class 'complex'>
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.
b = True
type(b) bool
Eg:
a = 10
b = 20
c = a<b
print(c) True
True+True 2
True-False 1
s1='durga'
s1="durga"
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
15 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
By using single quotes or double quotes we cannot represent multi line string
literals.
s1="durga
soft"
For this requirement we should go for triple single quotes(''') or triple double
quotes(""")
s1='''durga
soft'''
s1="""durga
soft"""
We can also use triple quotes to use single quote or double quote in our String.
''' This is " character'''
' This i " Character '
Slicing of Strings:
1) slice means a piece
2) [ ] operator is called slice operator, which can be used to retrieve parts of String.
3) In Python Strings follows zero based index.
4) The index can be either +ve or -ve.
5) +ve index means forward direction from Left to Right
6) -ve index means backward direction from Right to Left
-5 -4 -3 -2 -1
d u r g a
0 1 2 3 4
1) >>> s="durga"
2) >>> s[0]
3) 'd'
4) >>> s[1]
5) 'u'
6) >>> s[-1]
7) 'a'
8) >>> s[40]
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
16 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) >>> s[1:40]
2) 'urga'
3) >>> s[1:]
4) 'urga'
5) >>> s[:4]
6) 'durg'
7) >>> s[:]
8) 'durga'
9) >>>
10)
11) >>> s*3
12) 'durgadurgadurga'
13)
14) >>> len(s)
15) 5
Note:
1) In Python the following data types are considered as Fundamental Data types
int
float
complex
bool
str
2) In Python, we can represent char values also by using str type and explicitly char type
is not available.
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 type only.
4) In Python we can present char Value also by using str Type and explicitly char Type is
not available.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
17 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
TYPE CASTING
֍ We can convert one type value to another type. This conversion is called Typecasting
or Type coersion.
֍ The following are various inbuilt functions for type casting.
1) int()
2) float()
3) complex()
4) bool()
5) str()
֍ int():
We can use this function to convert values from other types to int
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:
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
18 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
֍ 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 complex type.
2) Whenever we are trying to convert str type to float type compulsary str should be
either integral or floating point literal and should be specified only in base-10.
֍ complex():
We can use complex() function to convert other types to complex type.
Form-1: complex(x)
We can use this function to convert x into complex number with real part x and imaginary
part 0.
Eg:
1) complex(10)==>10+0j
2) complex(10.5)===>10.5+0j
3) complex(True)==>1+0j
4) complex(False)==>0j
5) complex("10")==>10+0j
6) complex("10.5")==>10.5+0j
7) complex("ten")
8) ValueError: complex() arg is a malformed string
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
19 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Form-2: complex(x,y)
We can use this method to convert x and y into complex number such that x will be real
part and y will be imaginary part.
֍ bool():
We can use this function to convert other type values to bool type.
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
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
20 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
֍ str():
We can use this method to convert other type values to str type.
1) >>> str(10)
2) '10'
3) >>> str(10.5)
4) '10.5'
5) >>> str(10+5j)
6) '(10+5j)'
7) >>> str(True)
8) 'True'
֍ In Python if a new object is required, then PVM won’t create object immediately. First
it will check is any object available with the required content or not. If available then
existing object will be reused. If it is not available then only a new object will be
created. The advantage of this approach is memory utilization and performance will be
improved.
֍ But the problem in this approach is, several references pointing to the same object, by
using one reference if we are allowed to change the content in the existing object then
the remaining references will be effected. To prevent this immutability concept is
required. According to this once creates an object we are not allowed to change
content. If we are trying to change with those changes a new object will be created.
1) >>> a=10
2) >>> b=10
3) >>> a is b
4) True
5) >>> id(a)
6) 1572353952
7) >>> id(b)
8) 1572353952
9) >>>
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
21 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
>>> a=10 >>> a=10+5j >>> a=True >>> a='durga'
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.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
22 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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
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)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
23 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
1) list=[10,10.5,'durga',True,10]
2) print(list) # [10,10.5,'durga',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
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("durga")
3) >>> list
4) [10, 20, 30, 'durga']
5) >>> list.remove(20)
6) >>> list
7) [10, 30, 'durga']
8) >>> list2=list*2
9) >>> list2
10) [10, 30, 'durga', 10, 30, 'durga']
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
24 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
9) Tuple Data Type:
tuple data type is exactly same as list data type except that it is immutable.i.e we
cannot chage values.
Tuple elements can be represented within parenthesis.
Eg:
1) 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("durga")
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 to 9
Eg:
r = range(10,20)
for i in r : print(i) 10 to 19
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
25 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Form-3: range(10, 20, 2)
2 means increment value
Eg:
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.
Eg:
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]
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
26 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
1) s={100,0,10,200,10,'durga'}
2) s # {0, 100, 'durga', 200, 10}
3) s[0] TypeError: 'set' object does not support indexing
֍ set is growable in nature, based on our requirement we can increase or decrease the
size.
1) >>> s.add(60)
2) >>> s
3) {0, 100, 'durga', 200, 10, 60}
4) >>> s.remove(100)
5) >>> s
6) {0, 'durga', 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'
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
27 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
13) dict Data Type:
֍ If we want to represent a group of values as key-value pairs then we should go for
dict data type.
֍ Eg: d = {101:'durga',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:'durga',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 binary information
like images, video files etc
2) In Python2 long data type is available. But in Python3 it is not available and we can
represent long values also by using int type only.
3) In Python there is no char data type. Hence we can represent char values also by using
str type.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
28 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Summary of Datatypes in Python 3
Datatype Description Is Immutable? Example
Int We can use to Immutable >>> a=10
represent the >>> type(a)
whole/integral <class 'int'>
numbers
Float We can use to Immutable >>> b=10.5
represent the >>> type(b)
decimal/floating <class 'float'>
point numbers
Complex We can use to Immutable >>> c=10+5j
represent the >>> type(c)
complex numbers <class 'complex'>
>>> c.real
10.0
>>> c.imag
5.0
Bool We can use to Immutable >>> flag=True
represent the logical >>> flag=False
values (Only allowed >>> type(flag)
values are True and <class 'bool'>
False)
Str To represent Immutable >>> s='durga'
sequence of >>> type(s)
Characters <class 'str'>
>>> s="durga"
>>> s='''Durga Software
Solutions... Ameerpet'''
>>> type(s)
<class 'str'>
bytes To represent a Immutable >>> list=[1,2,3,4]
sequence of byte >>> b=bytes(list)
values from 0-255 >>> type(b)
<class 'bytes'>
bytearray To represent a Mutable >>> list=[10,20,30]
sequence of byte >>> ba=bytearray(list)
values from 0-255 >>> type(ba)
<class 'bytearray'>
range To represent a range Immutable >>> r=range(10)
of values >>> r1=range(0,10)
>>> r2=range(0,10,2)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
29 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
list To represent an Mutable >>> l=[10,11,12,13,14,15]
ordered collection of >>> type(l)
objects <class 'list'>
tuple To represent an Immutable >>> t=(1,2,3,4,5)
ordered collections of >>> type(t)
objects <class 'tuple'>
set To represent an Mutable >>> s={1,2,3,4,5,6}
unordered collection >>> type(s)
of unique objects <class 'set'>
frozenset To represent an Immutable >>> s={11,2,3,'Durga',100,'Ramu'}
unordered collection >>> fs=frozenset(s)
of unique objects >>> type(fs)
<class 'frozenset'>
dict To represent a group Mutable >>>
of key value pairs d = {101:'durga', 102:'ramu',
103:'hari'}
>>> type(d)
<class 'dict'>
Eg:
def m1():
a=10
print(m1())
None
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
30 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Escape Characters:
In String literals we can use esacpe characters to associate a special meaning.
1) >>> s="durga\nsoftware"
2) >>> print(s)
3) durga
4) software
5) >>> s="durga\tsoftware"
6) >>> print(s)
7) durga software
8) >>> s="This is " symbol"
9) File "<stdin>", line 1
10) s="This is " symbol"
11) ^
12) SyntaxError: invalid syntax
13) >>> s="This is \" symbol"
14) >>> print(s)
15) This is " symbol
1) \n New Line
2) \t Horizontal Tab
3) \r Carriage Return
4) \b Back Space
5) \f Form Feed
6) \v Vertical Tab
7) \' Single Quote
8) \" Double Quote
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
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
31 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
OPERATORS
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
32 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Operator is a symbol that performs certain operations.
Python provides the following set of operators
1) Arithmetic Operators
2) Relational Operators OR Comparison Operators
3) Logical operators
4) Bitwise oeprators
5) Assignment operators
6) Special operators
1) Arithmetic Operators:
1) + Addition
2) – Subtraction
3) * Multiplication
4) / Division Operator
5) % 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)
Output:
Python test.py OR py test.py
a+b = 12
a-b= 8
a*b= 20
a/b= 5.0
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
33 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
a//b= 5
a%b= 0
a**b= 100
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:
֍ We can use +,* operators for str type also.
֍ If we want to use + operator for str type then compulsory both arguments should be
str type only otherwise we will get error.
1) >>> "durga"+10
2) TypeError: must be str, not int
3) >>> "durga"+"10"
4) 'durga10'
֍ If we use * operator for str type then compulsory one argument should be int and
other argument should be str type.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
34 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
֍ 2*"durga"
"durga"*2
2.5*"durga" TypeError: can't multiply sequence by non-int of type 'float'
"durga"*"durga" TypeError: can't multiply sequence by non-int of type 'str'
10/0
10.0/0
.....
Eg 2:
1) a="durga"
2) b="durga"
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 True
10) a < b is False
11) a <= b is True
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
35 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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>'durga')
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 than b")
5) else:
6) print("a is not greater than b")
1) 10<20 True
2) 10<20<30 True
3) 10<20<30<40 True
4) 10<20<30<40>50 False
1) >>> 10==20
2) False
3) >>> 10!= 20
4) True
5) >>> 10==True
6) False
7) >>> False==False
8) True
9) >>> "durga"=="durga"
10) True
11) >>> 10=="durga"
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
36 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
12) False
Note: Chaining concept is applicable for equality operators. If atleast one comparison
returns False then the result is False. Otherwise the result is True.
1) >>> 10==20==30==40
2) False
3) >>> 10==10==10==10
4) True
x and y:
If x is evaluates to false return x otherwise return y
Eg:
10 and 20
0 and 20
x or y:
If x evaluates to True then result is x otherwise result is y
10 or 20 10
0 or 20 20
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
37 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
not x:
If x is evalutates to False then result is True otherwise False
not 10 False
not 0 True
Eg:
5) Bitwise Operators:
֍ We can apply these operators bitwise.
֍ These operators are applicable only for int and boolean types.
֍ By mistake if we are trying to apply for any other type then we will get Error.
֍ print(4&5) Valid
֍ print(10.5 & 5.6)
TypeError: unsupported operand type(s) for &: 'float' and 'float'
֍ print(4&5) 4
֍ print(4|5) 5
֍ print(4^5) 1
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
38 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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
Eg: print(~5) -6
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.
6) 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
print(10>>2) 2
0 0 0 0 1 0 1 0
0 0 0 0 0 0 1 0
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
39 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
We can apply bitwise operators for boolean types also
7) Assignment Operators:
֍ We can use assignment operator to assign value to the variable.
Eg: x = 10
֍ We can combine asignment operator with some other operator to form compound
assignment operator.
Eg: x += 10 x = x+10
The following is the list of all possible compound assignment operators in Python.
+=
-=
*=
/=
%=
//=
**=
&=
|=
^=
>>=
<<=
Eg:
1) x=10
2) x+=20
3) print(x) 30
Eg:
1) x=10
2) x&=5
3) print(x) 0
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
40 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
8) Ternary Operator OR Conditional 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
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
41 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
Output:
D:\python_classes>py test.py
Enter First Number:10
Enter Second Number:10
Both numbers are equal
D:\python_classes>py test.py
Enter First Number:10
Enter Second Number:20
First Number is Less than Second Number
D:\python_classes>py test.py
Enter First Number:20
Enter Second Number:10
First Number Greater than Second Number
9) Special Operators:
Python defines the following 2 special operators
1) Identity Operators
2) Membership operators
1) Identity Operators
We can use identity operators for address comparison.
There are 2 identity operators are available
1) is
2) is not
Eg:
1) a=10
2) b=10
3) print(a is b) True
4) x=True
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
42 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5) y=True
6) print( x is y) True
Eg:
1) a="durga"
2) b="durga"
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
Note: We can use is operator for address comparison where as == operator for content
comparison.
2) Membership Operators:
We can use Membership operators to check whether the given object present in the
given collection. (It may be String, List, Set, Tuple OR Dict)
In Returns True if the given object present in the specified Collection
not in Retruns True if the given object not present in the specified Collection
Eg:
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
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
43 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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
1) () Parenthesis
2) ** Exponential Operator
3) ~, - Bitwise Complement Operator, Unary Minus Operator
4) *, /, %, // Multiplication, Division, Modulo, Floor Division
5) +, - Addition, Subtraction
6) <<, >> Left and Right Shift
7) & Bitwise And
8) ^ Bitwise X-OR
9) | Bitwise OR
10) >, >=, <, <=, ==, != Relational OR Comparison Operators
11) =, +=, -=, *=... Assignment Operators
12) is , is not Identity Operators
13) in , not in Membership operators
14) not Logical not
15) and Logical and
16) or Logical or
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) 3/2*4+3+(10/5)**3-2
10) 3/2*4+3+2.0**3-2
11) 3/2*4+3+8.0-2
12) 1.5*4+3+8.0-2
13) 6.0+3+8.0-2
14) 15.0
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
44 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Mathematical Functions (math Module)
֍ A Module is collection of functions, variables and classes etc.
֍ math is a module that contains several functions to perform mathematical operations.
֍ If we want to use any module in Python, first we have to import that module.
import math
֍ Once we import a module then we can call any function of that module.
1) import math
2) print(math.sqrt(16))
3) print(math.pi)
Output
4.0
3.141592653589793
1) import math as m
2) print(m.sqrt(16))
3) print(m.pi)
֍ If we import a member explicitly then it is not required to use module name while
accessing.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
45 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Important Functions of math Module:
1) ceil(x)
2) floor(x)
3) pow(x,y)
4) factorial(x)
5) trunc(x)
6) gcd(x,y)
7) sin(x)
8) cos(x)
9) tan(x)
10) ....
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
46 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
INPUT AND OUTPUT STATEMENTS
Reading Dynamic Input from the Keyboard:
In Python 2 the following 2 functions are available to read dynamic input from the
keyboard.
1) raw_input()
2) input()
1) raw_input():
This function always reads the data from the keyboard in the form of String Format.
We have to convert that string type to our required type by using the corresponding
type casting methods.
2) input():
input() function can be used to read data directly in our required format.We are not
required to perform type casting.
x = input("Enter Value)
type(x)
10 int
"durga" str
10.5 float
True bool
***Note:
But in Python 3 we have only input() method and raw_input() method is not available.
Python3 input() function behaviour exactly same as raw_input() method of Python2.
i.e every input value is treated as str type only.
raw_input() function of Python 2 is renamed as input() function in Python 3.
Q) Write a program to read 2 numbers from the keyboard and print sum
-----------------------------------------------------------
D:\Python_classes>py test.py
Enter Employee No:100
Enter Employee Name:Sunny
Enter Employee Salary:1000
Enter Employee Address:Mumbai
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
48 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Employee Married ?[True|False]:True
Please Confirm Information
Employee No : 100
Employee Name : Sunny
Employee Salary : 1000.0
Employee Address : Mumbai
Employee Married ? : True
D:\Python_classes>py test.py
Enter 2 numbers :10 20
Product is : 200
Note: split() function can take space as seperator by default .But we can pass
anything as seperator.
D:\Python_classes>py test.py
Enter 3 float numbers :10.5,20.6,20.1
The Sum is : 51.2
eval():
eval Function take a String and evaluate the Result.
Eg: x = eval(“10+20+30”)
print(x)
Output: 60
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
49 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
eval() can evaluate the Input to list, tuple, set, etc based the provided Input.
Eg: Write a Program to accept list from the keynboard on the display
1) l = eval(input(“Enter List”))
2) print (type(l))
3) print(l)
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
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
50 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
D:\Python_classes>py test.py 10 20 30
The Number of Command Line Arguments: 4
The List of Command Line Arguments: [‘test.py’, ‘10’,’20’,’30’]
Command Line Arguments one by one:
test.py
10
20
30
---------------------------
1) from sys import argv
2) sum=0
3) args=argv[1:]
4) for x in args :
5) n=int(x)
6) sum=sum+n
7) print("The Sum:",sum)
D:\Python_classes>py test.py 10 20 30 40
The Sum: 100
Note 1: 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)
Note 2: 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.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
51 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
D:\Python_classes>py test.py 10 20
1020
30
Note 3: If we are trying to access command line arguments with out of range index then
we will get Error.
D:\Python_classes>py test.py 10 20
IndexError: list index out of range
Note: In Python there is argparse module to parse command line arguments and display
some help messages whenever end user enters wrong input.
input()
raw_input()
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")
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
52 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note:
֍ If both arguments are String type then + operator acts as concatenation operator.
֍ If one argument is string type and second is any other type like int then we will get
Error.
֍ If both arguments are number type then + operator acts as arithmetic addition
operator.
Note:
1) print("Hello"+"World")
2) print("Hello","World")
HelloWorld
Hello World
1) a,b,c=10,20,30
2) print("The Values are :",a,b,c)
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=':')
D:\Python_classes>py test.py
10,20,30
10:20:30
1) print("Hello")
2) print("Durga")
3) print("Soft")
Output:
Hello
Durga
Soft
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
53 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
If we want output in the same line with space
1) print("Hello",end=' ')
2) print("Durga",end=' ')
3) print("Soft")
Note: The default value for end attribute is \n, which is nothing but new line character.
We can pass any object (like list, tuple, set etc) as argument to the print() statement.
1) l=[10,20,30,40]
2) t=(10,20,30,40)
3) print(l)
4) print(t)
We can use print() statement with String and any number of arguments.
1) s = "Durga"
2) a = 48
3) s1 ="Java"
4) s2 ="Python"
5) print("Hello",s,"Your Age is",a)
6) print("You are teaching",s1,"and",s2)
Output:
Hello Durga Your Age is 48
You are teaching java and Python
1) %i int
2) %d int
3) %f float
4) %s String type
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
54 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg 1:
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))
Output
a value is 10
b value is 20 and c value is 30
Eg 2:
1) s="Durga"
2) list=[10,20,30,40]
3) print("Hello %s ...The List of Items are %s" %(s,list))
Output: Hello Durga ...The List of Items are [10, 20, 30, 40]
Eg:
1) name = "Durga"
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))
Output
Hello Durga your salary is 10000 and Your Friend Sunny is waiting
Hello Durga your salary is 10000 and Your Friend Sunny is waiting
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
55 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
FLOW
CONTROL
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
56 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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. Conditional Statements
1) if
if condition : statement
OR
if condition :
statement-1
statement-2
statement-3
Eg:
1) name=input("Enter Name:")
2) if name=="durga" :
3) print("Hello Durga Good Morning")
4) print("How are you!!!")
D:\Python_classes>py test.py
Enter Name:durga
Hello Durga Good Morning
How are you!!!
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
57 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
D:\Python_classes>py test.py
Enter Name: Ravi
How are you!!!
2) if-else:
if condition:
Action-1
else:
Action-2
if condition is true then Action-1 will be executed otherwise Action-2 will be executed.
1) name=input("Enter Name:")
2) if name=="durga" :
3) print("Hello Durga Good Morning")
4) else:
5) print("Hello Guest Good Moring")
6) print("How are you!!!")
D:\Python_classes>py test.py
Enter Name:durga
Hello Durga Good Morning
How are you!!!
D:\Python_classes>py test.py
Enter Name:Ravi
Hello Guest Good Moring
How are you!!!
3) if-elif-else:
if condition1:
Action-1
elif condition2:
Action-2
elif condition3:
Action-3
elif condition4:
Action-4
...
else:
Default Action
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
58 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) brand=input("Enter Your Favourite Brand:")
2) if brand=="RC" :
3) print("It is childrens brand")
4) elif brand=="KF":
5) print("It is not that much kick")
6) elif brand=="FO":
7) print("Buy one get Free One")
8) else :
9) print("Other Brands are not recommended")
D:\Python_classes>py test.py
Enter Your Favourite Brand:RC
It is childrens brand
D:\Python_classes>py test.py
Enter Your Favourite Brand:KF
It is not that much kick
D:\Python_classes>py test.py
Enter Your Favourite Brand: KALYANI
Other Brands are not recommended
Note:
1) else part is always optional. Hence the following are various possible syntaxes.
1) If
2) if – else
3) if-elif-else
4) if-elif
2) There is no switch statement in Python
D:\Python_classes>py test.py
Enter First Number:10
Enter Second Number:20
Biggest Number is: 20
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
59 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q) Write a Program to find Biggest of given 3 Numbers from the
Commad Prompt?
1) n1=int(input("Enter First Number:"))
2) n2=int(input("Enter Second Number:"))
3) n3=int(input("Enter Third Number:"))
4) if n1>n2 and n1>n3:
5) print("Biggest Number is:",n1)
6) elif n2>n3:
7) print("Biggest Number is:",n2)
8) else :
9) print("Biggest Number is:",n3)
D:\Python_classes>py test.py
Enter First Number:10
Enter Second Number:20
Enter Third Number:30
Biggest Number is: 30
D:\Python_classes>py test.py
Enter First Number:10
Enter Second Number:30
Enter Third Number:20
Biggest Number is: 30
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
60 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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) elif n==1:
8) print("ONE")
9) elif n==2:
10) print("TWO")
11) elif n==3:
12) print("THREE")
13) elif n==4:
14) print("FOUR")
15) elif n==5:
16) print("FIVE")
17) elif n==6:
18) print("SIX")
19) elif n==7:
20) print("SEVEN")
21) elif n==8:
22) print("EIGHT")
23) elif n==9:
24) print("NINE")
25) else:
26) print("PLEASE ENTER A DIGIT FROM 0 TO 9")
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
61 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
II. Iterative Statements
֍ If we want to execute a group of statements multiple times then we should go for
Iterative statements.
֍ Python supports 2 types of iterative statements.
1) for loop
2) while loop
1) for loop:
If we want to execute some action for every element present in some sequence
(it may be string or collection) then we should go for for loop.
1) s="Sunny Leone"
2) for x in s :
3) print(x)
Output
S
u
n
n
y
L
e
o
n
e
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
62 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
D:\Python_classes>py test.py
Enter some String: Sunny Leone
The character present at 0 index is : S
The character present at 1 index is : u
The character present at 2 index is : n
The character present at 3 index is : n
The character present at 4 index is : y
The character present at 5 index is :
The character present at 6 index is : L
The character present at 7 index is : e
The character present at 8 index is : o
The character present at 9 index is : n
The character present at 10 index is : e
1) for x in range(10) :
2) print("Hello")
1) for x in range(11) :
2) print(x)
1) for x in range(21) :
2) if (x%2!=0):
3) print(x)
1) for x in range(10,0,-1) :
2) print(x)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
63 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
D:\Python_classes>py test.py
Enter List:[10,20,30,40]
The Sum= 100
D:\Python_classes>py test.py
Enter List:[45,67]
The Sum= 112
2) while loop:
If we want to execute a group of statements iteratively until some condition false,then
we should go for while loop.
1) x = 1
2) while x <= 10:
3) print(x)
4) x = x+1
1) n=int(input("Enter number:"))
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)
Eg: Write a program to prompt user to enter some name until entering Durga
1) name=""
2) while name!="durga":
3) name=input("Enter Name:")
4) print("Thanks for confirmation")
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
64 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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.
1) for i in range(4):
2) for j in range(4):
3) print("i=",i," j=",j)
Output
D:\Python_classes>py test.py
i= 0 j= 0
i= 0 j= 1
i= 0 j= 2
i= 0 j= 3
i= 1 j= 0
i= 1 j= 1
i= 1 j= 2
i= 1 j= 3
i= 2 j= 0
i= 2 j= 1
i= 2 j= 2
i= 2 j= 3
i= 3 j= 0
i= 3 j= 1
i= 3 j= 2
i= 3 j= 3
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
65 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q) Write a Program to display *'s in Pyramid Style
(Also known as Equivalent Triangle)
*
** 1) n = int(input("Enter number of rows:"))
*** 2) for i in range(1,n+1):
**** 3) print(" " * (n-i),end="")
***** 4) print("* "*i)
******
*******
1) for i in range(10):
2) if i==7:
3) print("processing is enough..plz break")
4) break
5) print(i)
D:\Python_classes>py test.py
0
1
2
3
4
5
6
processing is enough..plz break
Eg:
1) cart=[10,20,600,60,70]
2) for item in cart:
3) if item>500:
4) print("To place this order insurence must be required")
5) break
6) print(item)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
66 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
D:\Python_classes>py test.py
10
20
To place this order insurence must be required
2) continue:
We can use continue statement to skip current iteration and continue next iteration.
1) for i in range(10):
2) if i%2==0:
3) continue
4) print(i)
D:\Python_classes>py test.py
1
3
5
7
9
Eg 2:
1) cart=[10,20,500,700,50,60]
2) for item in cart:
3) if item>=500:
4) print("We cannot process this item :",item)
5) continue
6) print(item)
D:\Python_classes>py test.py
10
20
We cannot process this item : 500
We cannot process this item : 700
50
60
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
67 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg 3:
1) numbers=[10,20,0,5,0,30]
2) for n in numbers:
3) if n==0:
4) print("Hey how we can divide with zero..just skipping")
5) continue
6) print("100/{} = {}".format(n,100/n))
Output
100/10 = 10.0
100/20 = 5.0
Hey how we can divide with zero..just skipping
100/5 = 20.0
Hey how we can divide with zero..just skipping
100/30 = 3.3333333333333335
1) cart=[10,20,30,40,50]
2) for item in cart:
3) if item>=500:
4) print("We cannot process this order")
5) break
6) print(item)
7) else:
8) print("Congrats ...all items processed successfully")
Output
10
20
30
40
50
Congrats ...all items processed successfully
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
68 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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")
Output
D:\Python_classes>py test.py
10
20
We cannot process this order
Q)When else part will be executed wrt loops? If loop executed without break
3) pass statement:
pass is a keyword in Python.
In our programming syntactically if block is required which won't do anything then we
can define that empty block with pass keyword.
pass
|- It is an empty statement
|- It is null statement
|- It won't do anything
Eg: if True:
SyntaxError: unexpected EOF while parsing
if True: pass valid
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
69 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
def m1():
SyntaxError: unexpected EOF while parsing
1) for i in range(100):
2) if i%9==0:
3) print(i)
4) else:pass
D:\Python_classes>py test.py
0
9
18
27
36
45
54
63
72
81
90
99
del Statement:
del is a keyword in Python.
After using a variable, it is highly recommended to delete that variable if it is no longer
required,so that the corresponding object is eligible for Garbage Collection.
We can delete variable by using del keyword.
1) x = 10
2) print(x)
3) del x
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
70 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
After deleting a variable we cannot access that variable otherwise we will get NameError.
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.
1) s = "durga"
2) print(s)
3) del s valid
4) del s[0] TypeError: 'str' object doesn't support item deletion
1) s = "durga"
2) del s
3) print(s) NameError: name 's' is not defined.
But in the case of None assignment the variable won't be removed but the corresponding
object is eligible for Garbage Collection (re bind operation). Hence after assigning with
None value, we can access that variable.
1) s = "durga"
2) s = None
3) print(s) None
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
71 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
STRING
DATA TYPE
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
72 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
The most commonly used object in any project and in any programming language is String
only. Hence we should aware complete information about String data type.
What is String?
Any sequence of characters within either single quotes or double quotes is considered as a
String.
Syntax:
s = 'durga'
s = "durga"
Note: In most of other languges like C, C++, Java, a single character with in single quotes
is treated as char data type value. But in Python we are not having char data type.Hence it
is treated as String only.
Eg:
>>> ch = 'a'
>>> type(ch)
<class 'str'>
Eg:
>>> s = '''durga
software
solutions'''
We can also use triple quotes to use single quotes or double quotes as symbol inside
String literal.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
73 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
How to Access Characters of a String?
We can access characters of a string by using the following ways.
1) By using index
2) By using slice operator
1) >>> s='durga'
2) >>> s[0]
3) 'd'
4) >>> s[4]
5) 'a'
6) >>> s[-1]
7) 'a'
8) >>> s[10]
9) 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:
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
74 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
2) Accessing Characters by using Slice Operator:
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.
***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.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
75 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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("durga"+"soft") durgasoft
print("durga"*2) durgadurga
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
76 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note:
1) To use + operator for Strings, compulsory both arguments should be str type.
2) To use * operator for Strings, compulsory one argument should be str and other
argument should be int.
Alternative ways:
1) s = "Learning Python is very easy !!!"
2) print("Forward direction")
3) for i in s:
4) print(i,end=' ')
5) print("Forward direction")
6) for i in s[::]:
7) print(i,end=' ')
8)
9) print("Backward direction")
10) for i in s[::-1]:
11) print(i,end=' ')
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
77 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Checking Membership:
We can check whether the character or string is the member of another string or not by
using in and not in operators
s = 'durga'
print('d' in s) True
print('z' in s) False
Output:
D:\python_classes>py test.py
Enter main string:durgasoftwaresolutions
Enter sub string:durga
durga is found in main string
D:\python_classes>py test.py
Enter main string:durgasoftwaresolutions
Enter sub string:python
python is not found in main string
Comparison of Strings:
We can use comparison operators (<, <=, >, >=) and equality operators (==, !=) for
strings.
Comparison will be performed based on alphabetical order.
Output:
D:\python_classes>py test.py
Enter first string:durga
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
78 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Enter Second string:durga
Both strings are equal
D:\python_classes>py test.py
Enter first string:durga
Enter Second string:ravi
First String is less than Second String
D:\python_classes>py test.py
Enter first string:durga
Enter Second string:anil
First String is greater than Second String
Finding Substrings:
We can use the following 4 methods
Note: By default find() method can search total string. We can also specify the
boundaries to search.
s.find(substring,bEgin,end)
It will always search from bEgin index to end-1 index.
1) s="durgaravipavanshiva"
2) print(s.find('a'))#4
3) print(s.find('a',7,15))#10
4) print(s.find('z',7,15))#-1
index():
index() method is exactly same as find() method except that if the specified substring is
not available then we will get ValueError.
Output:
D:\python_classes>py test.py
Enter main string:learning python is very easy
Enter sub string:python
substring found
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
80 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
D:\python_classes>py test.py
Enter main string:learning python is very easy
Enter sub string:java
substring not found
Output:
D:\python_classes>py test.py
Enter main string:abbababababacdefg
Enter sub string:a
Found at position 0
Found at position 3
Found at position 5
Found at position 7
Found at position 9
Found at position 11
D:\python_classes>py test.py
Enter main string:abbababababacdefg
Enter sub string:bb
Found at position 1
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
81 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) s="abcabcabcabcadda"
2) print(s.count('a'))
3) print(s.count('ab'))
4) print(s.count('a',3,7))
Output:
6
4
2
Eg 1:
s = "Learning Python is very difficult"
s1 = s.replace("difficult","easy")
print(s1)
Output: bbbbbbbbbbbbbb
Eg:
s = "abab"
s1 = s.replace("a","b")
print(s,"is available at :",id(s))
print(s1,"is available at :",id(s1))
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
82 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output:
abab is available at : 4568672
bbbb is available at : 4568704
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.
Output:
durga
software
solutions
1) s="22-02-2018"
2) l=s.split('-')
3) for x in l:
4) print(x)
Output:
22
02
2018
Joining of Strings:
We can join a Group of Strings (List OR Tuple) wrt the given Seperator.
s = seperator.join(group of strings)
Eg 1:
t = ('sunny', 'bunny', 'chinny')
s = '-'.join(t)
print(s)
Output: sunny-bunny-chinny
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
83 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg 2:
l = ['hyderabad', 'singapore', 'london', 'dubai']
s = ':'.join(l)
print(s)
Output: hyderabad:singapore:london:dubai
Output:
LEARNING PYTHON IS VERY EASY
learning python is very easy
LEARNING pYTHON IS VERY eASY
Learning Python Is Very Easy
Learning python is very easy
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
84 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output:
True
False
True
Eg:
1) print('Durga786'.isalnum()) True
2) print('durga786'.isalpha()) False
3) print('durga'.isalpha()) True
4) print('durga'.isdigit()) False
5) print('786786'.isdigit()) True
6) print('abc'.islower()) True
7) print('Abc'.islower()) False
8) print('abc123'.islower()) True
9) print('ABC'.isupper()) True
10) print('Learning python is Easy'.istitle()) False
11) print('Learning Python Is Easy'.istitle()) True
12) print(' '.isspace()) True
Demo Program:
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
85 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
13) print("It is space character")
14) else:
15) print("Non Space Special Character")
D:\python_classes>py test.py
Enter any character:7
Alpha Numeric Character
it is a digit
D:\python_classes>py test.py
Enter any character:a
Alpha Numeric Character
Alphabet character
Lower case alphabet character
D:\python_classes>py test.py
Enter any character:$
Non Space Special Character
D:\python_classes>py test.py
Enter any character:A
Alpha Numeric Character
Alphabet character
Upper case alphabet character
1) name = 'durga'
2) salary = 10000
3) age = 48
4) print("{} 's salary is {} and his age is {}".format(name,salary,age))
5) print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
6) print("{x} 's salary is {y} and his age is {z}".format(z=age,y=salary,x=name))
Output:
durga 's salary is 10000 and his age is 48
durga 's salary is 10000 and his age is 48
durga 's salary is 10000 and his age is 48
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
86 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Important Programs regarding String Concept
1st Way:
1) s = input("Enter Some String:")
2) print(s[::-1])
2nd Way:
1) s = input("Enter Some String:")
2) print(''.join(reversed(s)))
3rd Way:
1) s = input("Enter Some String:")
2) i=len(s)-1
3) target=''
4) while i>=0:
5) target=target+s[i]
6) i=i-1
7) print(target)
2nd Way:
1) s=input("Enter Some String:")
2) i=0
3) print("Characters at Even Position:")
4) while i< len(s):
5) print(s[i],end=',')
6) i=i+2
7) print()
8) print("Characters at Odd Position:")
9) i=1
10) while i< len(s):
11) print(s[i],end=',')
12) i=i+2
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
88 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q5) Program to Merge Characters of 2 Strings into a Single
String by taking Characters alternatively
Input: s1 = "ravi"
s2 = "reja"
Output: rtaevjia
Output:
Enter First String:durga
Enter Second String:ravisoft
druarvgiasoft
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
89 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q7) Write a Program for the following Requirement
Input: a4b3c2
Output: aaaabbbcc
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
90 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q10) Write a Program to find the Number of Occurrences of
each Character present in the given String?
Input: ABCABCABBCDE
Output: A-3,B-4,C-3,D-1,E-1
Output:
D:\durgaclasses>py test.py
Enter Some String:one two three four five six seven
Original String: one two three four five six seven
output String: one owt three ruof five xis seven
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
91 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Formatting the Strings:
֍ We can format the strings with variable values by using replacement operator {} and
format() method.
֍ The main objective of format() method to format string into meaningful output form.
1) name = 'durga'
2) salary = 10000
3) age = 48
4) print("{} 's salary is {} and his age is {}".format(name,salary,age))
5) print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
6) print("{x} 's salary is {y} and his age is {z}".format(z=age,y=salary,x=name))
Output:
durga 's salary is 10000 and his age is 48
durga 's salary is 10000 and his age is 48
durga 's salary is 10000 and his age is 48
d Decimal IntEger
f Fixed point number(float).The default precision is 6
b Binary format
o Octal Format
x Hexa Decimal Format (Lower case)
X Hexa Decimal Format (Upper case)
Eg-1:
Output:
The intEger number is: 123
The intEger number is: 123
The intEger number is: 123
The intEger number is: 00123
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
92 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg-2:
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}
֍ Total positions should be minimum 8.
֍ After decimal point exactly 3 digits are allowed.If it is less then 0s will be placed in the
last positions
֍ If total number is < 8 positions then 0 will be placed in MSBs
֍ If total number is >8 positions then all intEgral digits will be considered.
֍ The extra digits we can take only 0
1) print("Binary Form:{0:b}".format(153))
2) print("Octal Form:{0:o}".format(153))
3) print("Hexa decimal Form:{0:x}".format(154))
4) 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.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
93 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note:
1) {:5d} It takes an intEger argument and assigns a minimum width of 5.
2) {: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
3) {:05d} The blank places can be filled with 0. In this place only 0 allowed.
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))
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
94 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output:
12
12
12000
12
00012
12
-12
12.235
- 12.235
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("durgasoftware"))
2) print("{:5.3}".format("durgasoftware"))
3) print("{:>5.3}".format("durgasoftware"))
4) print("{:^5.3}".format("durgasoftware"))
5) print("{:*^5.3}".format("durgasoftware"))
Output:
dur
dur
dur
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
95 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
dur
*dur*
1) person={'age':48,'name':'durga'}
2) print("{p[name]}'s age is: {p[age]}".format(p=person))
Output:
durga's age is: 48
Note: p is alias name of dictionary
person dictionary we are passing as keyword argument
1) person={'age':48,'name':'durga'}
2) print("{name}'s age is: {age}".format(**person))
1) class Person:
2) age=48
3) name="durga"
4) print("{p.name}'s age is :{p.age}".format(p=Person()))
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('durga',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))
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
96 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
4) print(string.format('cat',fill='*',align='<',width=6))
5) print(string.format('cat',fill='*',align='>',width=6))
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))
1) complexNumber=1+2j
2) print("Real Part:{0.real} and Imaginary Part:{0.imag}".format(complexNumber))
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
97 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
LIST
DATA STRUCTURE
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
98 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
֍ If we want to represent a group of individual objects as a single entity where insertion
order preserved and duplicates are allowed, then we should go for List.
֍ insertion order preserved.
֍ duplicate objects are allowed.
֍ heterogeneous objects are allowed.
֍ List is dynamic because based on our requirement we can increase the size and
decrease the size.
֍ In List the elements will be placed within square brackets and with comma seperator.
֍ We can differentiate duplicate elements by using index and we can preserve insertion
order by using index. Hence index will play very important role.
֍ Python supports both positive and negative indexes. +ve index means from left to
right where as negative index means right to left.
[10,"A","B",20, 30, 10]
-6 -5 -4 -3 -2 -1
10 A B 20 30 10
0 1 2 3 4 5
֍ List objects are mutable.i.e we can change the content.
1) list=[]
2) print(list)
3) print(type(list))
4)
5) []
6) <class 'list'>
2) If we know elements already then we can create list as follows list = [10, 20, 30, 40]
1) list=eval(input("Enter List:"))
2) print(list)
3) print(type(list))
D:\Python_classes>py test.py
Enter List:[10,20,30,40]
[10, 20, 30, 40]
<class 'list'>
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
99 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
4) With list() Function:
1) l=list(range(0,10,2))
2) print(l)
3) print(type(l))
D:\Python_classes>py test.py
[0, 2, 4, 6, 8]
<class 'list'>
Eg:
1) s="durga"
2) l=list(s)
3) print(l)
D:\Python_classes>py test.py
['d', 'u', 'r', 'g', 'a']
D:\Python_classes>py test.py
['Learning', 'Python', 'is', 'very', 'very', 'easy', '!!!']
<class 'list'>
Note: Sometimes we can take list inside another list, such type of lists are called nested
lists.
[10, 20, [30, 40]]
1) By using Index:
֍ List follows zero based index. ie index of first element is zero.
֍ List supports both +ve and -ve indexes.
֍ +ve index meant for Left to Right
֍ -ve index meant for Right to Left
֍ list = [10, 20, 30, 40]
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
100 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
-4 -3 -2 -1
list 10 20 30 40
0 1 2 3
֍ print(list[0]) 10
֍ print(list[-1]) 40
֍ print(list[10]) IndexError: list index out of range
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])
Output
D:\Python_classes>py test.py
[3, 5, 7]
[5, 7, 9]
[4, 5, 6, 7]
[9, 7, 5]
[5, 6, 7, 8, 9, 10]
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
101 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
List vs Mutability:
Once we creates a List object, we can modify its content. Hence List objects are mutable.
1) n=[10,20,30,40]
2) print(n)
3) n[1]=777
4) print(n)
D:\Python_classes>py test.py
[10, 20, 30, 40]
[10, 777, 30, 40]
D:\Python_classes>py test.py
0
1
2
3
4
5
6
7
8
9
10
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
102 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
D:\Python_classes>py test.py
0
1
2
3
4
5
6
7
8
9
10
D:\Python_classes>py test.py
0
2
4
6
8
10
D:\Python_classes>py test.py
A is available at positive index: 0 and at negative index: -3
B is available at positive index: 1 and at negative index: -2
C is available at positive index: 2 and at negative index: -1
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
103 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Important Functions of List:
I. To get Information about List:
1) len():
Returns the number of elements present in the list
Eg: n = [10, 20, 30, 40]
print(len(n) 4
2) count():
It returns the number of occurrences of specified item in the list
1) 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))
D:\Python_classes>py test.py
1
4
2
0
3) index():
Returns the index of first occurrence of the specified item.
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 in list
Note: If the specified element not present in the list then we will get ValueError.Hence
before index() method we have to check whether item present in the list or not by using in
operator.
print( 4 in n) False
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
104 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
II. Manipulating Elements of List:
1) append() Function:
We can use append() function to add item at the end of the list.
1) list=[]
2) list.append("A")
3) list.append("B")
4) list.append("C")
5) print(list)
D:\Python_classes>py test.py
['A', 'B', 'C']
Eg: To add all elements to list upto 100 which are divisible by 10
1) list=[]
2) for i in range(101):
3) if i%10==0:
4) list.append(i)
5) print(list)
D:\Python_classes>py test.py
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
2) insert() Function:
To insert item at specified index position
1) n=[1,2,3,4,5]
2) n.insert(1,888)
3) print(n)
D:\Python_classes>py test.py
[1, 888, 2, 3, 4, 5]
1) n=[1,2,3,4,5]
2) n.insert(10,777)
3) n.insert(-10,999)
4) print(n)
D:\Python_classes>py test.py
[999, 1, 2, 3, 4, 5, 777]
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
105 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note: If the specified index is greater than max index then element will be inserted at last
position. If the specified index is smaller than min index then element will be inserted at
first position.
3) extend() Function:
To add all items of one list to another list
l1.extend(l2)
all items present in l2 will be added to l1
1) order1=["Chicken","Mutton","Fish"]
2) order2=["RC","KF","FO"]
3) order1.extend(order2)
4) print(order1)
D:\Python_classes>py test.py
['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']
1) order = ["Chicken","Mutton","Fish"]
2) order.extend("Mushroom")
3) print(order)
D:\Python_classes>py test.py
['Chicken', 'Mutton', 'Fish', 'M', 'u', 's', 'h', 'r', 'o', 'o', 'm']
4) remove() Function:
We can use this function to remove specified item from the list.If the item present
multiple times then only first occurrence will be removed.
1) n=[10,20,10,30]
2) n.remove(10)
3) print(n)
D:\Python_classes>py test.py
[20, 10, 30]
If the specified item not present in list then we will get ValueError
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
106 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) n=[10,20,10,30]
2) n.remove(40)
3) print(n)
Note: Hence before using remove() method first we have to check specified element
present in the list or not by using in operator.
5) pop() Function:
It removes and returns the last element of the list.
This is only function which manipulates list and returns some element.
1) n=[10,20,30,40]
2) print(n.pop())
3) print(n.pop())
4) print(n)
D:\Python_classes>py test.py
40
30
[10, 20]
1) n = []
2) print(n.pop()) IndexError: pop from empty list
Note:
1) pop() is the only function which manipulates the list and returns some value
2) In general we can use append() and pop() functions to implement stack datastructure
by using list,which follows LIFO(Last In First Out) order.
In general we can use pop() function to remove last element of the list. But we can use to
remove elements based on index.
1) n = [10,20,30,40,50,60]
2) print(n.pop()) 60
3) print(n.pop(1)) 20
4) print(n.pop(10)) IndexError: pop index out of range
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
107 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Differences between remove() and pop()
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():
We can use to reverse() order of elements of list.
1) n=[10,20,30,40]
2) n.reverse()
3) print(n)
D:\Python_classes>py test.py
[40, 30, 20, 10]
2) sort():
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']
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
108 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note: To use sort() function, compulsory list should contain only homogeneous elements.
Otherwise we will get TypeError
1) n=[20,10,"A","B"]
2) n.sort()
3) print(n)
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()
3) print(n)# [10,20,'A','B']
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]
1) x=[10,20,30,40]
2) y=x 10 20 30 40
x
3) print(id(x)) y
4) print(id(y))
The problem in this approach is by using one reference variable if we are changing
content, then those changes will be reflected to the other reference variable.
1) x = [10,20,30,40]
10 20 30 40
2) y = x
x 777
3) y[1] = 777
y
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
109 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
4) print(x) [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
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
110 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Using Mathematical Operators for List Objects:
We can use + and * operators for List objects.
Note: To use + operator compulsory both arguments should be list objects, otherwise we
will get TypeError.
Eg:
c = a+40 TypeError: can only concatenate list (not "int") to list.
c = a+[40] Valid
Note: Whenever we are using comparison operators (==, !=) for List objects then the
following should be considered
1) The Number of Elements
2) The Order of Elements
3) The Content of Elements (Case Sensitive)
Note: When ever we are using relatational Operators (<, <=, >, >=) between List Objects,
only 1ST Element comparison will be performed.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
111 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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:
Membership Operators:
We can check whether element is a member of the list or not by using memebership
operators.
1) in Operator
2) not in Operator
1) n=[10,20,30,40]
2) print (10 in n)
3) print (10 not in n)
4) print (50 in n)
5) print (50 not in n)
Output
True
False
False
True
clear() Function:
We can use clear() function to remove all elements of List.
1) n=[10,20,30,40]
2) print(n)
3) n.clear()
4) print(n)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
112 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output
D:\Python_classes>py test.py
[10, 20, 30, 40]
[]
Nested Lists:
Sometimes we can take one list inside another list. Such type of lists are called nested
lists.
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])
Output
D:\Python_classes>py test.py
[10, 20, [30, 40]]
10
[30, 40]
30
40
Note: We can access nested list elements by using index just like accessing multi
dimensional array elements.
1) n=[[10,20,30],[40,50,60],[70,80,90]]
2) print(n)
3) print("Elements by Row wise:")
4) for r in n:
5) print(r)
6) print("Elements by Matrix style:")
7) for i in range(len(n)):
8) for j in range(len(n[i])):
9) print(n[i][j],end=' ')
10) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
113 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output
D:\Python_classes>py test.py
[[10, 20, 30], [40, 50, 60], [70, 80, 90]]
List Comprehensions:
It is very easy and compact way of creating list objects from any iterable objects
(Like List, Tuple, Dictionary, Range etc) based on some condition.
D:\Python_classes>py test.py
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[2, 4, 8, 16, 32]
[4, 16, 36, 64, 100]
1) words=["Balaiah","Nag","Venkatesh","Chiranjeevi"]
2) l=[w[0] for w in words]
3) print(l)
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
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
114 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
7) num4=[i for i in num1 if i in num2]
8) print(num4) [30, 40]
Eg:
Output
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
[['THE', 3], ['QUICK', 5], ['BROWN', 5], ['FOX', 3], ['JUMPS', 5], ['OVER', 4],
['THE', 3], ['LAZY', 4], ['DOG', 3]]
D:\Python_classes>py test.py
Enter the word to search for vowels: durgasoftwaresolutions
['u', 'a', 'o', 'e', 'i']
The number of different vowels present in durgasoftwaresolutions is 5
List out all Functions of List and write a Program to use these Functions
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
115 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
TUPLE
DATA STRUCTURE
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
116 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) Tuple is exactly same as List except that it is immutable. i.e once we creates Tuple
object, we cannot perform any changes in that object.
2) Hence Tuple is Read only version of List.
3) If our data is fixed and never changes then we should go for Tuple.
4) Insertion Order is preserved
5) Duplicates are allowed
6) Heterogeneous objects are allowed.
7) We can preserve insertion order and we can differentiate duplicate objects by using
index. Hence index will play very important role in Tuple also.
8) Tuple support both +ve and -ve index. +ve index means forward direction (from left to
right) and -ve index means backward direction (from right to left)
9) We can represent Tuple elements within Parenthesis and with comma seperator.
10) Parenethesis are optional but recommended to use.
1) t=10,20,30,40
2) print(t)
3) print(type(t))
4)
5) Output
6) (10, 20, 30, 40)
7)
8) <class 'tuple'>
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.
1) t=(10)
2) print(t)
3) print(type(t))
4)
5) Output
6) 10
7) <class 'int'>
Eg:
1) t=(10,)
2) print(t)
3) print(type(t))
4)
5) Output
6) (10,)
7) <class 'tuple'>
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
117 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q) Which of the following are valid Tuples?
1) t = ()
2) t = 10, 20, 30, 40
3) t = 10
4) t = 10,
5) t = (10)
6) t = (10,)
7) t = (10, 20, 30, 40)
Tuple Creation:
1) t = ()
Creation of Empty Tuple
2) t = (10,)
t = 10,
Creation of Single valued Tuple, Parenthesis are Optional, should ends with Comma
3) t = 10, 20, 30
t = (10, 20, 30)
Creation of multi values Tuples & Parenthesis are Optional.
1) By using Index:
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 of range
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
118 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
2) By using Slice Operator:
1) t=(10,20,30,40,50,60)
2) print(t[2:5])
3) print(t[2:100])
4) print(t[::2])
Output
(30, 40, 50)
(30, 40, 50, 60)
(10, 30, 50)
Tuple vs Immutability:
Once we creates tuple, we cannot change its content.
Hence tuple objects are immutable.
Eg:
t = (10, 20, 30, 40)
t[1] = 70 TypeError: 'tuple' object does not support item assignment
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
119 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Important Functions of Tuple:
1) len()
To return number of elements present in the tuple.
Eg: t = (10,20,30,40)
print(len(t)) 4
2) count()
To return number of occurrences of given element in the tuple
3) index()
Returns index of first occurrence of the given element.
If the specified element is not available then we will get ValueError.
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)
Output
[10, 20, 30, 40]
(40, 10, 30, 20)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
120 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5) min() And max() Functions:
These functions return min and max values according to default natural sorting order.
1) t = (40,10,30,20)
2) print(min(t)) 10
3) print(max(t)) 40
6) cmp():
֍ It compares the elements of both tuples.
֍ If both tuples are equal then returns 0
֍ If the first tuple is less than second tuple then it returns -1
֍ If the first tuple is greater than second tuple then it returns +1
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.
Tuple unpacking is the reverse process of Tuple packing.
We can unpack a Tuple and assign its values to different variables.
1) t=(10,20,30,40)
2) a,b,c,d=t
3) print("a=",a,"b=",b,"c=",c,"d=",d)
Output: a= 10 b= 20 c= 30 d= 40
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
121 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note: At the time of tuple unpacking the number of variables and number of values
should be same, otherwise we will get ValueError.
Eg:
t = (10,20,30,40)
a, b, c = t ValueError: too many values to unpack (expected 3)
Tuple Comprehension:
Tuple Comprehension is not supported by Python.
t = ( x**2 for x in range(1,6))
Here we are not getting tuple object and we are getting generator object.
D:\Python_classes>py test.py
<class 'generator'>
1
4
9
16
25
D:\Python_classes>py test.py
Enter Tuple of Numbers:(10,20,30,40)
The Sum= 100
The Average= 25.0
D:\Python_classes>py test.py
Enter Tuple of Numbers: (100,200,300)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
122 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
The Sum= 600
The Average= 200.0
List Tuple
1) List is a Group of Comma separeated 1) Tuple is a Group of Comma separeated
Values within Square Brackets and Values within Parenthesis and
Square Brackets are mandatory. Parenthesis 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
changes in that Object. change 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.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
123 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
SET
DATA STRUCTURE
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
124 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
If we want to represent a group of unique values as a single entity then we should go
for set.
Duplicates are not allowed.
Insertion order is not preserved.But we can sort the elements.
Indexing and slicing not allowed for the set.
Heterogeneous elements are allowed.
Set objects are mutable i.e once we creates set object we can perform any changes in
that object based on our requirement.
We can represent set elements within curly braces and with comma seperation
We can apply mathematical operations like union, intersection, difference etc on set
objects.
Output
{40, 10, 20, 30}
<class 'set'>
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}
Note:
֍ While creating empty set we have to take special care.
֍ Compulsory we should use set() function.
֍ s = {} It is treated as dictionary but not empty set.
1) s={}
2) print(s)
3) print(type(s))
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
125 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output
{}
<class 'dict'>
Eg:
1) s=set()
2) print(s)
3) print(type(s))
Output
set()
<class 'set'>
1) s={10,20,30}
2) s.add(40);
3) print(s) #{40, 10, 20, 30}
2) update(x,y,z):
To add multiple items to the set.
Arguments are not individual elements and these are Iterable objects like List, Range
etc.
All elements present in the given Iterable objects will be added to the set.
1) s={10,20,30}
2) l=[40,50,60,10]
3) s.update(l,range(5))
4) print(s)
3) copy():
Returns copy of the set.
It is cloned object.
1) s = {10,20,30}
2) s1 = s.copy()
3) print(s1)
4) pop():
It removes and returns some random element from the set.
1) s={40,10,30,20}
2) print(s)
3) print(s.pop())
4) print(s)
Output
{40, 10, 20, 30}
40
{10, 20, 30}
5) remove(x):
It removes specified element from the set.
If the specified element not present in the Set then we will get KeyError.
6) discard(x):
1) It removes the specified element from the set.
2) If the specified element not present in the set then we won't get any error.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
127 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
3) print {(s) 20, 30}
4) s.discard(50)
5) print {(s) 20, 30}
7) clear():
To remove all elements from the Set.
1) s={10,20,30}
2) print(s)
3) s.clear()
4) print(s)
Output
{10, 20, 30}
set()
2) intersection():
x.intersection(y) OR x&y.
Returns common elements present in both x and y.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
128 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
3) difference():
x.difference(y) OR x-y.
Returns the elements present in x but not in y.
4) symmetric_difference():
x.symmetric_difference(y) OR x^y.
Returns elements present in either x OR y but not in both.
Output
{'u', 'g', 'r', 'd', 'a'}
True
False
Set Comprehension:
Set comprehension is possible.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
129 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Set Objects won't support indexing and slicing:
1) s = {10,20,30,40}
2) print(s[0]) TypeError: 'set' object does not support indexing
3) print(s[1:3]) TypeError: 'set' object is not subscriptable
D:\Python_classes>py test.py
Enter word to search for vowels: durga
The different vowel present in durga are {'u', 'a'}
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
130 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
DICTIONARY
DATA STRUCTURE
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
131 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
֍ We can use List, Tuple and Set to represent a group of individual objects as a single
entity.
֍ If we want to represent a group of objects as key-value pairs then we should go for
Dictionary.
Eg:
rollno ---- name
phone number -- address
ipaddress --- domain name
Note: In C++ and Java Dictionaries are known as "Map" where as in Perl and Ruby it is
known as "Hash"
1) d[100]="durga"
2) d[200]="ravi"
3) d[300]="shiva"
4) print(d) {100: 'durga', 200: 'ravi', 300: 'shiva'}
1) d = {100:'durga',200:'ravi', 300:'shiva'}
2) print(d[100]) #durga
3) print(d[300]) #shiva
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
132 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
print(d[400]) KeyError: 400
We can prevent this by checking whether key is already available or not by using
has_key() function or by using in operator.
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])
D:\Python_classes>py test.py
Enter number of students: 3
Enter Student Name: durga
Enter % of Marks of Student: 60%
Enter Student Name: ravi
Enter % of Marks of Student: 70%
Enter Student Name: shiva
Enter % of Marks of Student: 80%
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
133 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
How to Update Dictionaries?
֍ d[key] = value
֍ If the key is not available then a new entry will be added to the dictionary with the
specified key-value pair
֍ If the key is already available then old value will be replaced with new value.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) d[400]="pavan"
4) print(d)
5) d[100]="sunny"
6) print(d)
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
{100: 'sunny', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) del d[100]
4) print(d)
5) del d[400]
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{200: 'ravi', 300: 'shiva'}
KeyError: 400
2) d.clear()
To remove all entries from the dictionary.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) d.clear()
4) print(d)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
134 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
{}
3) del d
To delete total dictionary.Now we cannot access d.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) del d
4) print(d)
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
NameError: name 'd' is not defined
2) len()
Returns the number of items in the dictionary.
3) clear():
To remove all elements from the dictionary.
4) get():
To get the value associated with the key
d.get(key)
If the key is available then returns the corresponding value otherwise returns None.It
wont raise any error.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
135 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
d.get(key,defaultvalue)
If the key is available then returns the corresponding value otherwise returns default
value.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d[100]) durga
3) print(d[400]) KeyError:400
4) print(d.get(100)) durga
5) print(d.get(400)) None
6) print(d.get(100,"Guest")) durga
7) print(d.get(400,"Guest")) Guest
5) pop():
d.pop(key)
It removes the entry associated with the specified key and returns the
corresponding value.
If the specified key is not available then we will get KeyError.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.pop(100))
3) print(d)
4) print(d.pop(400))
Output
durga
{200: 'ravi', 300: 'shiva'}
KeyError: 400
6) popitem():
It removes an arbitrary item(key-value) from the dictionaty and returns it.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d)
3) print(d.popitem())
4) print(d)
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
(300, 'shiva')
{100: 'durga', 200: 'ravi'}
If the dictionary is empty then we will get KeyError
d={}
print(d.popitem()) ==>KeyError: 'popitem(): dictionary is empty'
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
136 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
7) keys():
It returns all keys associated eith dictionary.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.keys())
3) for k in d.keys():
4) print(k)
Output
dict_keys([100, 200, 300])
100
200
300
8) values():
It returns all values associated with the dictionary.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.values())
3) for v in d.values():
4) print(v)
Output
dict_values(['durga', 'ravi', 'shiva'])
durga
ravi
shiva
9) items():
It returns list of tuples representing key-value pairs.
[(k,v),(k,v),(k,v)]
1) d={100:"durga",200:"ravi",300:"shiva"}
2) for k,v in d.items():
3) print(k,"--",v)
Output
100 -- durga
200 -- ravi
300 -- shiva
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
137 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
10) copy():
To create exactly duplicate dictionary (cloned copy)
d1 = d.copy();
11) setdefault():
d.setdefault(k,v)
If the key is already available then this function returns the corresponding value.
If the key is not available then the specified key-value will be added as new item to
the dictionary.
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.setdefault(400,"pavan"))
3) print(d)
4) print(d.setdefault(100,"sachin"))
5) print(d)
Output
pavan
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
durga
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
12) update():
d.update(x)
All items present in the dictionary x will be added to dictionary d
Output
D:\Python_classes>py test.py
Enter dictionary:{'A':100,'B':200,'C':300}
Sum= 600
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
138 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q) Write a Program to find Number of Occurrences of each Letter
present in the given String?
1) word=input("Enter any word: ")
2) d={}
3) for x in word:
4) d[x]=d.get(x,0)+1
5) for k,v in d.items():
6) print(k,"occurred ",v," times")
Output
D:\Python_classes>py test.py
Enter any word: mississippi
m occurred 1 times
i occurred 4 times
s occurred 4 times
p occurred 2 times
Output
D:\Python_classes>py test.py
Enter any word: doganimaldoganimal
a occurred 4 times
i occurred 2 times
o occurred 2 times
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
139 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q) Write a Program to accept Student Name and Marks from the
Keyboard and creates a Dictionary. Also display Student Marks
by taking Student Name as Input?
1) n=int(input("Enter the number of students: "))
2) d={}
3) for i in range(n):
4) name=input("Enter Student Name: ")
5) marks=input("Enter Student Marks: ")
6) d[name]=marks
7) while True:
8) name=input("Enter Student Name to get Marks: ")
9) marks=d.get(name,-1)
10) if marks== -1:
11) print("Student Not Found")
12) else:
13) print("The Marks of",name,"are",marks)
14) option=input("Do you want to find another student marks[Yes|No]")
15) if option=="No":
16) break
17) print("Thanks for using our application")
Output
D:\Python_classes>py test.py
Enter the number of students: 5
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
140 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Do you want to find another student marks[Yes|No]Yes
Dictionary Comprehension:
Comprehension concept applicable for dictionaries also.
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
141 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
FUNCTIONS
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
142 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
֍ If a group of statements is repeatedly required then it is not recommended to write
these statements everytime seperately.We have to define these statements as a single
unit and we can call that unit any number of times based on our requirement without
rewriting. This unit is nothing but function.
1) Built in Functions:
The functions which are coming along with Python software automatically, are called
built in functions or pre defined functions.
Eg: id()
type()
input()
eval()
etc..
test.py
1) def wish():
2) print("Hello Good Morning")
3) wish()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
143 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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("Durga")
4) wish("Ravi")
D:\Python_classes>py test.py
Hello Durga Good Morning
Hello Ravi Good Morning
Eg: Write a function to take number as input and print its square value
1) def squareIt(number):
2) print("The Square of",number,"is", number*number)
3) squareIt(4)
4) squareIt(5)
D:\Python_classes>py test.py
The Square of 4 is 16
The Square of 5 is 25
Return Statement:
Function can take input values as parameters and executes business logic, and returns
output to the caller with return statement.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
144 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
D:\Python_classes>py test.py
The sum is 30
The sum is 300
If we are not writing return statement then default return value is None.
1) def f1():
2) print("Hello")
3) f1()
4) print(f1())
Output
Hello
Hello
None
Output
D:\Python_classes>py test.py
10 is Even Number
15 is Odd Number
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
145 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output
D:\Python_classes>py test.py
The Factorial of 1 is : 1
The Factorial of 2 is : 2
The Factorial of 3 is : 6
The Factorial of 4 is : 24
Eg 1:
1) def sum_sub(a,b):
2) sum=a+b
3) sub=a-b
4) return sum,sub
5) x,y=sum_sub(100,50)
6) print("The Sum is :",x)
7) print("The Subtraction is :",y)
Output
The Sum is : 150
The Subtraction is : 50
Eg 2:
1) def calc(a,b):
2) sum=a+b
3) sub=a-b
4) mul=a*b
5) div=a/b
6) return sum,sub,mul,div
7) t=calc(100,50)
8) print("The Results are")
9) for i in t:
10) print(i)
Output
The Results are
150
50
5000
2.0
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
146 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Types of Arguments
def f1(a,b):
------
------
------
f1(10,20)
1) Positional Arguments:
These are the arguments passed to function in correct positional order.
def sub(a, b):
print(a-b)
sub(100, 200)
sub(200, 100)
2) Keyword Arguments:
We can pass argument values by keyword i.e by parameter name.
1) def wish(name,msg):
2) print("Hello",name,msg)
3) wish(name="Durga",msg="Good Morning")
4) wish(msg="Good Morning",name="Durga")
Output
Hello Durga Good Morning
Hello Durga Good Morning
Here the order of arguments is not important but number of arguments must be matched.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
147 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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.
1) def wish(name,msg):
2) print("Hello",name,msg)
3) wish("Durga","GoodMorning") Valid
4) wish("Durga",msg="GoodMorning") Valid
5) wish(name="Durga","GoodMorning") Invalid
6) SyntaxError: positional argument follows keyword argument
3) Default Arguments:
Sometimes we can provide default values for our positional arguments.
1) def wish(name="Guest"):
2) print("Hello",name,"Good Morning")
3) wish("Durga")
4) wish()
Output
Hello Durga Good Morning
Hello Guest Good Morning
If we are not passing any name then only default value will be considered.
***Note:
After default arguments we should not take non default arguments.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
148 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) def sum(*n):
2) total=0
3) for n1 in n:
4) total=total+n1
5) print("The Sum=",total)
6)
7) sum()
8) sum(10)
9) sum(10,20)
10) sum(10,20,30,40)
Output
The Sum= 0
The Sum= 10
The Sum= 30
The Sum= 100
1) def f1(n1,*s):
2) print(n1)
3) for s1 in s:
4) print(s1)
5)
6) f1(10)
7) f1(10,20,30,40)
8) f1(10,"A",30,"B")
Output
10
10
20
30
40
10
A
30
B
Note: After variable length argument,if we are taking any other arguments then we
should provide values as keyword arguments.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
149 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) def f1(*s,n1):
2) for s1 in s:
3) print(s1)
4) print(n1)
5)
6) f1("A","B",n1=10)
Output
A
B
10
f1("A","B",10) Invalid
TypeError: f1() missing 1 required keyword-only argument: 'n1'
1) def display(**kwargs):
2) for k,v in kwargs.items():
3) print(k,"=",v)
4) display(n1=10,n2=20,n3=30)
5) display(rno=100,name="Durga",marks=70,subject="Java")
Output
n1 = 10
n2 = 20
n3 = 30
rno = 100
name = Durga
marks = 70
subject = Java
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
150 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Case Study:
def f(arg1,arg2,arg3=4,arg4=8):
print(arg1,arg2,arg3,arg4)
1) f(3,2) 3 2 4 8
2) f(10,20,30,40) 10 20 30 40
3) f(25,50,arg4=100) 25 50 4 100
4) f(arg4=2,arg1=3,arg2=4) 3 4 4 2
5) f() Invalid
TypeError: f() missing 2 required positional arguments: 'arg1' and 'arg2'
Library Function
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
151 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Types of Variables
Python supports 2 types of variables.
1) Global Variables
2) Local Variables
1) Global Variables
The variables which are declared outside of function are called global variables.
These variables can be accessed in all functions of that module.
Output
10
10
2) Local Variables:
The variables which are declared inside a function are called local variables.
Local variables are available only for the function in which we declared it.i.e from
outside of function we cannot access.
1) def f1():
2) a=10
3) print(a) # valid
4)
5) def f2():
6) print(a) #invalid
7)
8) f1()
9) f2()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
152 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
global Keyword:
We can use global keyword for the following 2 purposes:
1) To declare global variable inside function
2) To make global variable available to the function so that we can perform required
modifications
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)
Output
777
10
1) a=10
2) def f1():
3) global a
4) a=777
5) print(a)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()
Output
777
777
1) def f1():
2) a=10
3) print(a)
4)
5) def f2():
6) print(a)
7)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
153 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
8) f1()
9) f2()
1) def f1():
2) global a
3) a=10
4) print(a)
5)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()
Output
10
10
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 Global Variable
2) def f1():
3) a=777 Local Variable
4) print(a)
5) print(globals()['a'])
6) f1()
Output
777
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)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
154 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
The main advantages of recursive functions are:
1) We can reduce length of the code and improves readability.
2) We can solve complex problems very easily.
Output
Factorial of 4 is : 24
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.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
155 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q) Write a Program to create a Lambda Function to find Square of
given Number?
1) s=lambda n:n*n
2) print("The Square of 4 is :",s(4))
3) print("The Square of 5 is :",s(5))
Output
The Square of 4 is : 16
The Square of 5 is : 25
Output
The Sum of 10,20 is: 30
The Sum of 100,200 is: 300
Output
The Biggest of 10,20 is: 20
The Biggest of 100,200 is: 200
Note: Lambda Function internally returns expression value and we are not required to
write return statement explicitly.
Note: Sometimes we can pass function as argument to another function. In such cases
lambda functions are best choice.
We can use lambda functions very commonly with filter(), map() and reduce() functions,
because these functions expect function as argument.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
156 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
filter() Function:
We can use filter() function to filter values from the given sequence based on some
condition.
filter(function,sequence)
Where Function Argument is responsible to perform conditional check Sequence can be
List OR Tuple OR String.
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.
The function can be applied on each element of sequence and generates new
sequence.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
157 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Without Lambda
1) l=[1,2,3,4,5]
2) def doubleIt(x):
3) return 2*x
4) l1=list(map(doubleIt,l))
5) print(l1) #[2, 4, 6, 8, 10]
With Lambda
1) l=[1,2,3,4,5]
2) l1=list(map(lambda x:2*x,l))
3) print(l1) #[2, 4, 6, 8, 10]
-------------------------------------------------------------
Eg 2: To find square of given numbers
1) l=[1,2,3,4,5]
2) l1=list(map(lambda x:x*x,l))
3) print(l1) #[1, 4, 9, 16, 25]
We can apply map() function on multiple lists also.But make sure all list should have same
length.
1) l1=[1,2,3,4]
2) l2=[2,3,4,5]
3) l3=list(map(lambda x,y:x*y,l1,l2))
4) print(l3) #[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.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
158 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
1) result=reduce(lambda x,y:x*y,l)
2) print(result) #12000000
Eg:
Everything is an Object:
In Python every thing is treated as object.
Even functions also internally treated as objects only.
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.
1) def wish(name):
2) print("Good Morning:",name)
3)
4) greeting=wish
5) print(id(wish))
6) print(id(greeting))
7)
8) greeting('Durga')
9) wish('Durga')
Output:
4429336
4429336
Good Morning: Durga
Good Morning: Durga
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
159 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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.
1) def wish(name):
2) print("Good Morning:",name)
3)
4) greeting=wish
5)
6) greeting('Durga')
7) wish('Durga')
8)
9) del wish
10) #wish('Durga') NameError: name 'wish' is not defined
11) greeting('Pavan')
Output:
Good Morning: Durga
Good Morning: Durga
Good Morning: Pavan
Nested Functions:
We can declare a function inside another function,such type of functions are called Nested
functions.
1) def outer():
2) print("outer function started")
3) def inner():
4) print("inner function execution")
5) print("outer function calling inner function")
6) inner()
7) outer()
8) #inner() NameError: name 'inner' is not defined
Output:
outer function started
outer function calling inner function
inner function execution
In the above example inner() function is local to outer() function and hence it is not
possible to call directly from outside of outer() function.
Output:
outer function started
outer function returning inner function
inner function execution
inner function execution
inner function execution
In the first case for the outer() function we are providing another name f1
(function aliasing).
But in the second case we calling outer() function,which returns inner function.For
that inner function() we are providing another name f1
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
161 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
MODULES
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
162 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
A group of functions, variables and classes saved to a file, which is nothing but
module.
Every Python file (.py) acts as a module.
durgamath.py
1) x = 888
2)
3) def add(a,b):
4) print("The Sum:",a+b)
5)
6) def product(a,b):
7) print("The Product:",a*b)
test.py:
1) import durgamath
2) print(durgamath.x)
3) durgamath.add(10,20)
4) durgamath.product(10,20)
Output
888
The Sum: 30
The Product: 200
Note: Whenever we are using a module in our program, for that module compiled file
will be generated and stored in the hard disk permanently.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
163 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Renaming a Module at the time of import
(Module Aliasing):
Eg: import durgamath as m
Here durgamath is original module name and m is alias name.
We can access members by using alias name m
test.py:
1) import durgamath as m
2) print(m.x)
3) m.add(10,20)
4) m.product(10,20)
test.py:
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
164 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Member Aliasing:
1) from durgamath import x as y,add as sum
2) print(y)
3) sum(10,20)
Once we defined as alias name,we should use alias name only and we should not use
original name
Reloading a Module:
By default module will be loaded only once eventhough we are importing multiple
multiple times.
module1.py:
print("This is from module1")
test.py
1) import module1
2) import module1
3) import module1
4) import module1
5) print("This is test module")
Output
This is from module1
This is test module
In the above program test module will be loaded only once eventhough we are
importing multiple times.
The problem in this approach is after loading a module if it is updated outside then
updated version of module1 is not available to our program.
We can solve this problem by reloading module explicitly based on our requirement.
We can reload by using reload() function of imp module.
1) import imp
2) imp.reload(module1)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
165 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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
The main advantage of explicit module reloading is we can ensure that updated version is
always available to our program.
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
Output
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__nam
e__', '__package__', '__spec__', 'f1', 'x', 'y']
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
166 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg 2: To display members of particular module
durgamath.py:
1) x=888
2)
3) def add(a,b):
4) print("The Sum:",a+b)
5)
6) def product(a,b):
7) print("The Product:",a*b)
test.py:
1) import durgamath
2) print(dir(durgamath))
Output
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'add', 'product', 'x']
Note: For every module at the time of execution Python interpreter will add some special
properties automatically for internal use.
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__)
Output
<module 'builtins' (built-in)>
None
None
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
167 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
test.py
If the program executed as an individual program then the value of this variable is
__main__
If the program executed as a module from some other program then the value of this
variable is the name of module where it is defined.
Hence by using this __name__ variable we can identify whether the program executed
directly or as a module.
Demo program:
module1.py:
1) def f1():
2) if __name__=='__main__':
3) print("The code executed as a program")
4) else:
5) print("The code executed as a module from some other program")
6) f1()
test.py:
1) import module1
2) module1.f1()
D:\Python_classes>py module1.py
The code executed as a program
D:\Python_classes>py test.py
The code executed as a module from some other program
The code executed as a module from some other program
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
168 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Working with math Module:
Python provides inbuilt module math.
This module defines several functions which can be used for mathematical operations.
The main important functions are
1) sqrt(x)
2) ceil(x)
3) floor(x)
4) fabs(x)
5) log(x)
6) sin(x)
7) tan(x)
8) ....
Output
2.0
11
10
10.6
10.6
Note: We can find help for any module by using help() function
Eg:
import math
help(math)
1) random() Function:
This function always generate some float value between 0 and 1 ( not inclusive)
0<x<1
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
169 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) from random import *
2) for i in range(10):
3) print(random())
Output
0.4572685609302056
0.6584325233197768
0.15444034016553587
0.18351427005232201
0.1330257265904884
0.9291139798071045
0.6586741197891783
0.8901649834019002
0.25540891083913053
0.7290504335962871
2) randint() Function:
To generate random integer beween two given numbers(inclusive)
Output
51
44
39
70
49
74
52
10
40
8
3) uniform() Function:
It returns random float values between 2 given numbers (not inclusive)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
170 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output
9.787695398230332
6.81102218793548
8.068672144377329
8.567976357239834
6.363511674803802
2.176137584071641
4.822867939432386
6.0801725149678445
7.508457735544763
1.9982221862917555
Output: 9
4
0
2
9
4
8
9
5
9
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
171 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output: 2
2
8
10
3
5
9
1
6
3
Output: 1
3
9
5
7
1
1
1
7
3
5) choice() Function:
It won’t return random number.
It will return a random object from the given list or tuple.
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
173 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
֍ It is an encapsulation mechanism to group related modules into a single unit.
֍ package is nothing but folder or directory which represents collection of Python
modules.
֍ Any folder or directory contains __init__.py file,is considered as a Python package.This
file can be empty.
֍ A package can contains sub packages also.
__init__.py
File 1
File 1 File 1
__init__.py __init__.py
Loan
__init__.py
File 1
File 1 File 1
__init__.py __init__.py
Loan
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
174 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg 1:
D:\Python_classes>
|-test.py
|-pack1
|-module1.py
|-__init__.py
__init__.py:
empty file
module1.py:
def f1():
print("Hello this is from module1 present in pack1")
test.py (version-1):
import pack1.module1
pack1.module1.f1()
test.py (version-2):
from pack1.module1 import f1
f1()
Eg 2:
D:\Python_classes>
|-test.py
|-com
|-module1.py
|-__init__.py
|-durgasoft
|-module2.py
|-__init__.py
__init__.py:
empty file
module1.py:
def f1():
print("Hello this is from module1 present in com")
module2.py:
def f2():
print("Hello this is from module2 present in com.durgasoft")
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
175 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
test.py
Output
D:\Python_classes>py test.py
Hello this is from module1 present in com
Hello this is from module2 present in com.durgasoft
Note: Summary diagram of library, packages, modules which contains functions, classes
and variables.
Library
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
176 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
100
PATTERN
PROGRAMS
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
177 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-1:
**********
********** 1) n=int(input("Enter the number of rows: "))
********** 2) for i in range(1,n+1):
********** 3) print("* "*n)
**********
**********
**********
**********
**********
**********
Pattern-2:
1111111111
2222222222 1) n=int(input("Enter the number of rows: "))
3333333333 2) for i in range(1,n+1):
4444444444 3) for j in range(1,n+1):
5555555555 4) print(i,end=" ")
6666666666 5) print()
7777777777
8888888888
9999999999
10 10 10 10 10 10 10 10 10 10
Pattern-3:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 1) n=int(input("Enter the number of rows: "))
1 2 3 4 5 6 7 8 9 10 2) for i in range(1,n+1):
1 2 3 4 5 6 7 8 9 10 3) for j in range(1,n+1):
1 2 3 4 5 6 7 8 9 10 4) print(j,end=" ")
1 2 3 4 5 6 7 8 9 10 5) print()
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
178 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-4:
AAAAAAAAAA
BBBBBBBBBB
CCCCCCCCCC 1) n=int(input("Enter the number of rows: "))
DDDDDDDDDD 2) for i in range(1,n+1):
EEEEEEEEEE 3) for j in range(1,n+1):
FFFFFFFFFF 4) print(chr(64+i),end=" ")
GGGGGGGGGG 5) print()
HHHHHHHHHH
IIIIIIIIII
JJJJJJJJJJ
Pattern-5:
ABCDEFGHIJ
ABCDEFGHIJ
ABCDEFGHIJ
ABCDEFGHIJ 1) n=int(input("Enter the number of rows: "))
ABCDEFGHIJ 2) for i in range(1,n+1):
ABCDEFGHIJ 3) for j in range(1,n+1):
ABCDEFGHIJ 4) print(chr(64+j),end=" ")
ABCDEFGHIJ 5) print()
ABCDEFGHIJ
ABCDEFGHIJ
Pattern-6:
10 10 10 10 10 10 10 10 10 10
9999999999
8888888888 1) n=int(input("Enter the number of rows: "))
7777777777 2) for i in range(1,n+1):
6666666666 3) for j in range(1,n+1):
5555555555 4) print(n+1-i,end=" ")
4444444444 5) print()
3333333333
2222222222
1111111111
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
179 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-7:
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1 1) n=int(input("Enter the number of rows: "))
10 9 8 7 6 5 4 3 2 1 2) for i in range(1,n+1):
10 9 8 7 6 5 4 3 2 1 3) for j in range(1,n+1):
10 9 8 7 6 5 4 3 2 1 4) print(n+1-j,end=" ")
10 9 8 7 6 5 4 3 2 1 5) print()
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
Pattern-8:
JJJJJJJJJJ
IIIIIIIIII
HHHHHHHHHH 1) n=int(input("Enter the number of rows: "))
GGGGGGGGGG 2) for i in range(1,n+1):
FFFFFFFFFF 3) for j in range(1,n+1):
EEEEEEEEEE 4) print(chr(65+n-i),end=" ")
DDDDDDDDDD 5) print()
CCCCCCCCCC
BBBBBBBBBB
AAAAAAAAAA
Pattern-9:
JIHGFEDCBA
JIHGFEDCBA
JIHGFEDCBA 1) n=int(input("Enter the number of rows: "))
JIHGFEDCBA 2) for i in range(1,n+1):
JIHGFEDCBA 3) for j in range(1,n+1):
JIHGFEDCBA 4) print(chr(65+n-j),end=" ")
JIHGFEDCBA 5) print()
JIHGFEDCBA
JIHGFEDCBA
JIHGFEDCBA
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
180 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-10: Code - 1
1) n=int(input("Enter the number of rows:"))
* 2) for i in range(1,n+1):
** 3) for j in range(1,i+1):
*** 4) print("*",end=" ")
**** 5) print()
*****
****** Code - 2
******* 1) n=int(input("Enter the number of rows:"))
******** 2) for i in range(1,n+1):
********* 3) print("* "*i)
**********
Pattern-11:
1
1) n=int(input("Enter the number of rows: "))
22
2) for i in range(1,n+1):
333
3) for j in range(1,i+1):
4444
4) print(i,end=" ")
55555
5) print()
666666
7777777
88888888
999999999
10 10 10 10 10 10 10 10 10 10
Pattern-12:
1
12
123
1234 1) n=int(input("Enter the number of rows: "))
12345 2) for i in range(1,n+1):
123456 3) for j in range(1,i+1):
1234567 4) print(j,end=" ")
12345678 5) print()
123456789
1 2 3 4 5 6 7 8 9 10
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
181 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-13:
A
BB
CCC 1) n=int(input("Enter the number of rows: "))
DDDD 2) for i in range(1,n+1):
EEEEE 3) for j in range(1,i+1):
FFFFFF 4) print(chr(64+i),end=" ")
GGGGGGG 5) print()
HHHHHHHH
IIIIIIIII
JJJJJJJJJJ
Pattern-14:
A
AB
ABC
1) n=int(input("Enter the number of rows: "))
ABCD
2) for i in range(1,n+1):
ABCDE
3) for j in range(1,i+1):
ABCDEF
4) print(chr(64+j),end=" ")
ABCDEFG
5) print()
ABCDEFGH
ABCDEFGHI
ABCDEFGHIJ
1) Squares
2) Right Angled Triangle
3) Reverse of Right Angled Triangle
Pattern-15:
**********
*********
********
1) n=int(input("Enter the number of rows: "))
*******
2) for i in range(1,n+1):
******
3) for j in range(1,n+2-i):
*****
4) print("*",end=" ")
****
5) print()
***
**
*
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
182 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-16:
1111111111
222222222
33333333 1) n=int(input("Enter the number of rows: "))
4444444 2) for i in range(1,n+1):
555555 3) for j in range(1,n+2-i):
66666 4) print(i,end=" ")
7777 5) print()
888
99
10
Pattern-17:
1 2 3 4 5 6 7 8 9 10
123456789
12345678 1) n=int(input("Enter the number of rows: "))
1234567 2) for i in range(1,n+1):
123456 3) for j in range(1,n+2-i):
12345 4) print(j,end=" ")
1234 5) print()
123
12
1
Pattern-18:
AAAAAAAAAA
BBBBBBBBB
CCCCCCCC
DDDDDDD 1) n=int(input("Enter the number of rows: "))
EEEEEE 2) for i in range(1,n+1):
FFFFF 3) for j in range(1,n+2-i):
GGGG 4) print(chr(64+i),end=" ")
HHH 5) print()
II
J
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
183 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-19:
ABCDEFGHIJ
ABCDEFGHI
ABCDEFGH 1) n=int(input("Enter the number of rows: "))
ABCDEFG 2) for i in range(1,n+1):
ABCDEF 3) for j in range(1,n+2-i):
ABCDE 4) print(chr(64+j),end=" ")
ABCD 5) print()
ABC
AB
A
Pattern-20:
10 10 10 10 10 10 10 10 10 10
999999999
88888888
1) n=int(input("Enter the number of rows: "))
7777777
2) for i in range(1,n+1):
666666
3) for j in range(1,n+2-i):
55555
4) print(n+1-i,end=" ")
4444
5) print()
333
22
1
Pattern-21:
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2
10 9 8 7 6 5 4 3
10 9 8 7 6 5 4 1) n=int(input("Enter the number of rows: "))
10 9 8 7 6 5 2) for i in range(1,n+1):
10 9 8 7 6 3) for j in range(1,n+2-i):
10 9 8 7 4) print(n+1-j,end=" ")
10 9 8 5) print()
10 9
10
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
184 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-22:
JJJJJJJJJJ
IIIIIIIII
HHHHHHHH 1) n=int(input("Enter the number of rows: "))
GGGGGGG 2) for i in range(1,n+1):
FFFFFF 3) for j in range(1,n+2-i):
EEEEE 4) print(chr(65+n-i),end=" ")
DDDD 5) print()
CCC
BB
A
Pattern-23:
JIHGFEDCBA
JIHGFEDCB
JIHGFEDC
JIHGFED 1) n=int(input("Enter the number of rows: "))
JIHGFE 2) for i in range(1,n+1):
JIHGF 3) for j in range(1,n+2-i):
JIHG 4) print(chr(65+n-j),end=" ")
JIH 5) print()
JI
J
Pattern-24:
*
**
***
****
***** 1) n=int(input("Enter the number of rows: "))
****** 2) for i in range(1,n+1):
******* 3) print(" "*(n-i),"*"*i,end=" ")
******** 4) print()
*********
**********
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
185 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-25:
*
**
*** 1) n=int(input("Enter the number of rows: "))
**** 2) for i in range(1,n+1):
***** 3) print(" "*(n-i),end="")
****** 4) for j in range(1,i+1):
******* 5) print("*",end=" ")
6) print()
********
*********
**********
Pattern-26:
1
22
333
7777777
88888888
999999999
10 10 10 10 10 10 10 10 10 10
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
186 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-27:
1
12 1) n=int(input("Enter the number of rows: "))
123 2) for i in range(1,n+1):
1234 3) print(" "*(n-i),end="")
12345 4) for j in range(1,i+1):
123456 5) print(j,end=" ")
1234567 6) print()
12345678
123456789
1 2 3 4 5 6 7 8 9 10
Pattern-28:
A
BB
CCC
1) n=int(input("Enter the number of rows: "))
DDDD 2) for i in range(1,n+1):
3) print(" "*(n-i),(chr(64+i)+" ")*i)
EEEEE 4) print()
FFFFFF
GGGGGGG
HHHHHHHH
Pattern-29:
A
AB
ABC
1) n=int(input("Enter the number of rows: "))
ABCD
2) for i in range(1,n+1):
ABCDE
3) print(" "*(n-i),end="")
ABCDEF
4) for j in range(1,i+1):
ABCDEFG
5) print(chr(64+j),end=" ")
ABCDEFGH
6) print()
ABCDEFGHI
ABCDEFGHIJ
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
187 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-30:
*****
**** 1) n=int(input("Enter the number of rows: "))
*** 2) for i in range(1,n+1):
** 3) print(" "*(i-1),"* "*(n+1-i))
*
Pattern-31:
55555
4444 1) n=int(input("Enter the number of rows: "))
333 2) for i in range(1,n+1):
22 3) print(" "*(i-1),(str(n+1-i)+" ")*(n+1-i))
1
Pattern-32:
12345 1) n=int(input("Enter the number of rows: "))
1234 2) for i in range(1,n+1):
123 3) print(" "*(i-1),end="")
12 4) for j in range(1,n+2-i):
1 5) print(j,end=" ")
6) print()
Pattern-33:
EEEEE
DDDD 1) n=int(input("Enter the number of rows: "))
CCC 2) for i in range(1,n+1):
BB 3) print(" "*(i-1),(str(chr(65+n-i))+" ")*(n+1-i))
A
Pattern-34:
ABCDE 1) n=int(input("Enter the number of rows: "))
ABCD 2) for i in range(1,n+1):
ABC 3) print(" "*(i-1),end="")
AB 4) for j in range(65,66+n-i):
A 5) print(chr(j),end=" ")
6) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
188 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-35:
* 1) n=int(input("Enter the number of rows: "))
*** 2) for i in range(1,n+1):
***** 3) print(" "*(n-i),"* "*(2*i-1))
*******
*********
Pattern-36:
1
222 1) n=int(input("Enter the number of rows: "))
33333 2) for i in range(1,n+1):
4444444 3) print(" "*(n-i),(str(i)+" ")*(2*i-1))
555555555
Pattern-37:
A
BBB 1) n=int(input("Enter the number of rows: "))
CCCCC 2) for i in range(1,n+1):
DDDDDDD 3) print(" "*(n-i),(str(chr(64+i)+" "))*(2*i-1))
EEEEEEEEE
Pattern-38:
A 1) n=int(input("Enter the number of rows: "))
CCC 2) for i in range(1,n+1):
EEEEE 3) print(" "*(n-i),(str(chr(64+2*i-1)+" "))*(2*i-1))
GGGGGGG
IIIIIIIII
Pattern-39:
1) n=int(input("Enter the number of rows: "))
1
2) for i in range(1,n+1):
123
3) print(" "*(n-i),end="")
12345
4) for j in range(1,2*i):
1234567
5) print(j,end=" ")
123456789
6) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
189 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-40:
1) n=int(input("Enter the number of rows: "))
1 2) for i in range(1,n+1):
321 3) print(" "*(n-i),end="")
54321 4) for j in range(2*i-1,0,-1):
7654321 5) print(j,end=" ")
987654321 6) print()
Pattern-41:
1) n=int(input("Enter the number of rows: "))
A 2) for i in range(1,n+1):
ABC 3) print(" "*(n-i),end="")
ABCDE 4) for j in range(65,65+2*i-1):
ABCDEFG 5) print(chr(j),end=" ")
ABCDEFGHI 6) print()
Pattern-42:
1) n=int(input("Enter the number of rows: "))
A 2) for i in range(1,n+1):
CBA 3) print(" "*(n-i),end="")
EDCBA 4) for j in range(65+2*i-2,64,-1):
GFEDCBA 5) print(chr(j),end=" ")
IHGFEDCBA 6) print()
Pattern-43:
1) n=int(input("Enter the number of rows: "))
0 2) for i in range(1,n+1):
101 3) print(" "*(n-i),end="")
21012 4) for j in range(1,i):
3210123 5) print(i-j,end=" ")
432101234 6) for k in range(0,i):
7) print(k,end=" ")
8) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
190 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-44: 1) n=int(input("Enter the number of rows: "))
2) for i in range(1,n+1):
A
3) print(" "*(n-i),end="")
BAB
4) for j in range(1,i):
CBABC
5) print(chr(i-j+65),end=" ")
DCBABCD
6) for k in range(0,i):
EDCBABCDE
7) print(chr(k+65),end=" ")
8) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
191 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-48: 1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
********* 3) print(" "*(i-1),end="")
******* 4) for j in range(1,num+2-i):
***** 5) print("*",end=" ")
*** 6) for k in range(1,num+1-i):
* 7) print("*",end=" ")
8) print()
Pattern-51:
1) num=int(input("Enter a number:"))
1234567 2) for i in range(1,num+1):
12345 3) print(" "*(i-1),end="")
123 4) for j in range(1,num+2-i):
1 5) print(j,end=" ")
6) for k in range(2,num+2-i):
7) print(num+k-i,end=" ")
8) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
192 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-52: 1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
EEEEEEEEE 3) print(" "*(i-1),end="")
DDDDDDD 4) for j in range(1,num+2-i):
CCCCC 5) print(chr(65+num-i),end=" ")
BBB 6) for k in range(2,num+2-i):
A 7) print(chr(65+num-i),end=" ")
8) print()
1) num=int(input("Enter a number:"))
Pattern-54: 2) for i in range(1,num+1):
3) print(" "*(i-1),end="")
ABCDEFG 4) for j in range(1,num+2-i):
ABCDE 5) print(chr(64+j),end=" ")
ABC 6) for k in range(2,num+2-i):
A 7) print(chr(68+k-i),end=" ")
8) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
193 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-56:
1) num=int(input("Enter a number:"))
* 2) for i in range(1,num+1):
** 3) print(" "*(num-i),end="")
*** 4) for j in range(1,i+1):
**** 5) print("*",end=" ")
***** 6) print()
**** 7) for k in range(1,num):
*** 8) print(" "*k,end="")
** 9) for l in range(1,num+1-k):
* 10) print("*",end=" ")
11) print()
1) num=int(input("Enter a number:"))
Pattern-57: 2) for i in range(1,num+1):
3) print(" "*(num-i),end="")
4 4) for j in range(1,i+1):
43 5) print(num-j,end=" ")
432 6) print()
4321 7) for k in range(1,num):
43210 8) print(" "*k,end="")
4321 9) for l in range(1,num+1-k):
432 10) print(num-l,end=" ")
43 11) print()
4
1) num=int(input("Enter a number:"))
Pattern-58: 2) for i in range(1,num+1):
3) print(" "*(num-i),end="")
4) for j in range(0,i):
3
5) print(num+j-i,end=" ")
23
6) print()
123
7) for k in range(1,num):
0123
8) print(" "*k,end="")
123
9) for l in range(1,num+1-k):
23
10) print(l+k-1,end=" ")
3
11) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
194 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-59: 1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
E 3) print(" "*(num-i),end="")
DE 4) for j in range(0,i):
CDE 5) print(chr(65+num+j-i),end=" ")
BCDE 6) print()
ABCDE 7) for k in range(1,num):
BCDE 8) print(" "*k,end="")
CDE 9) for l in range(0,num-k):
DE 10) print(chr(65+k+l),end=" ")
E 11) print()
Pattern-60:
1) num=int(input("Enter a number:"))
*
2) for i in range(1,num+1):
**
3) for j in range(1,i+1):
***
4) print("*",end=" ")
****
5) print()
*****
6) for a in range(1,num+1):
****
7) for k in range(1,num+1-a):
***
8) print("*",end=" ")
**
9) print()
*
Pattern-61:
4 1) num=int(input("Enter a number:"))
43 2) for i in range(1,num+1):
432 3) for j in range(1,i+1):
4321 4) print(num-j,end=" ")
43210 5) print()
4321 6) for a in range(1,num+1):
432 7) for k in range(1,num+1-a):
43 8) print(num-k,end=" ")
4 9) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
195 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-62:
4 1) num=int(input("Enter a number:"))
34 2) for i in range(1,num+1):
234 3) for j in range(1,i+1):
1234 4) print(num-i+j-1,end=" ")
01234 5) print()
1234 6) for a in range(1,num+1):
234 7) for k in range(0,num-a):
34 8) print(k+a,end=" ")
4 9) print()
Pattern-63:
E 1) num=int(input("Enter a number:"))
DD 2) for i in range(1,num+1):
CCC 3) for j in range(1,i+1):
BBBB 4) print(chr(65+num-i),end=" ")
AAAAA 5) print()
BBBB 6) for a in range(1,num+1):
CCC 7) for k in range(0,num-a):
DD 8) print(chr(65+a),end=" ")
E 9) print()
Pattern-64:
E 1) for i in range(1,num+1):
ED 2) for j in range(1,i+1):
EDC 3) print(chr(65+num-j),end=" ")
EDCB 4) print()
EDCBA 5) for a in range(1,num+1):
EDCB 6) for k in range(num-a,0,-1):
EDC 7) print(chr(64+k+a),end=" ")
ED 8) print()
E 9) num=int(input("Enter a number:"))
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
196 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-65:
E 1) num=int(input("Enter a number:"))
DE 2) for i in range(1,num+1):
CDE 3) for j in range(1,i+1):
BCDE 4) print(chr(64+num-i+j),end=" ")
ABCDE 5) print()
BCDE 6) for a in range(1,num+1):
CDE 7) for k in range(1,num-a+1):
DE 8) print(chr(64+k+a),end=" ")
E 9) print()
Pattern-66:
1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
*
3) print(" "*(num-i),end="")
**
4) for j in range(1,i+1):
***
5) print("*",end=" ")
****
6) print()
*****
Pattern-67:
1) num=int(input("Enter a number:"))
1 2) for i in range(1,num+1):
22 3) print(" "*(num-i),end="")
333 4) for j in range(1,i+1):
4444 5) print(i,end=" ")
55555 6) print()
Pattern-68:
1 1) num=int(input("Enter a number:"))
12 2) for i in range(1,num+1):
123 3) print(" "*(num-i),end="")
1234 4) for j in range(1,1+i):
12345 5) print(j,end=" ")
6) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
197 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-69:
1) num=int(input("Enter a number:"))
A 2) for i in range(1,num+1):
BB 3) print(" "*(num-i),end="")
CCC 4) for j in range(1,1+i):
DDDD 5) print(chr(64+i),end=" ")
EEEEE 6) print()
Pattern-71:
1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
*****
3) print(" "*(i-1),end="")
****
4) for j in range(1,num+2-i):
***
5) print("*",end=" ")
**
6) print()
*
Pattern-72:
1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
55555
3) print(" "*(i-1),end="")
4444
4) for j in range(1,num+2-i):
333
5) print(num-i+1,end=" ")
22
6) print()
1
Pattern-73:
1) num=int(input("Enter a number:"))
54321 2) for i in range(1,num+1):
4321 3) print(" "*(i-1),end="")
321 4) for j in range(1,num+2-i):
21 5) print(num+2-i-j,end=" ")
1 6) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
198 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-74: 1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
EEEEE 3) print(" "*(i-1),end="")
DDDD 4) for j in range(1,num+2-i):
CCC 5) print(chr(65+num-i),end=" ")
BB 6) print()
A
Pattern-75:
1) num=int(input("Enter a number:"))
EDCBA 2) for i in range(1,num+1):
DCBA 3) print(" "*(i-1),end="")
CBA 4) for j in range(1,num+2-i):
BA 5) print(chr(65+num+1-i-j),end=" ")
A 6) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
199 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-78: 1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
1
3) print(" "*(num-i),end="")
22
4) for j in range(1,i+1):
333
5) print(i,end=" ")
4444
6) print()
55555
7) for p in range(1,num):
4444
8) print(" "*p,end="")
333
9) for q in range(1,num+1-p):
22
10) print(num-p,end=" ")
1
11) print()
1) num=int(input("Enter a number:"))
Pattern-79: 2) for i in range(1,num+1):
3) print(" "*(num-i),end="")
4) for j in range(1,i+1):
1
5) print(j,end=" ")
12
6) print()
123
7) for p in range(1,num):
1234
8) print(" "*p,end="")
12345
9) for q in range(1,num+1-p):
2345
10) print(q+p,end=" ")
345
11) print()
45
5
1) num=int(input("Enter a number:"))
Pattern-80: 2) for i in range(1,num+1):
3) print(" "*(num-i),end="")
1 4) for j in range(1,i+1):
12 5) print(j,end=" ")
123 6) print()
1234 7) for p in range(1,num):
12345 8) print(" "*p,end="")
1234 9) for q in range(1,num+1-p):
123 10) print(q,end=" ")
12 11) print()
1
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
200 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-81: 1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
A 3) print(" "*(num-i),end="")
BB 4) for j in range(1,i+1):
CCC 5) print(chr(64+i),end=" ")
DDDD 6) print()
EEEEE 7) for p in range(1,num):
DDDD 8) print(" "*p,end="")
CCC 9) for q in range(1,num+1-p):
BB 10) print(chr(64+num-p),end=" ")
A 11) print()
1) n=int(input("Enter a number:"))
2) for i in range(1,n+1):
Pattern-83: 3) print(" "*(n-i),end="")
4) for j in range(1,i+1):
5) print(n-i+j,end=" ")
5
6) for k in range(2,i+1):
454
7) print(n+1-k,end=" ")
34543
8) print()
2345432
9) for i in range(1,n+1):
123454321
10) print(" "*i,end="")
2345432
11) for j in range(1+i,n+1):
34543
12) print(j,end=" ")
454
13) for k in range(2,n+1-i):
5
14) print(n+1-k,end=" ")
15) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
201 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-84: 1) while True:
2) n=int(input("Enter a number:"))
5 3) for i in range(1,n+1):
545 4) print(" "*(n-i),end="")
54345 5) for j in range(1,i+1):
5432345 6) print(n+1-j,end=" ")
543212345 7) for k in range(2,i+1):
5432345 8) print(n-i+k,end=" ")
54345 9) print()
545 10) for i in range(1,n+1):
5 11) print(" "*i,end="")
12) for j in range(1,n+1-i):
13) print(n+1-j,end=" ")
14) for k in range(2,n+1-i):
15) print(i+k,end=" ")
16) print()
1) num=int(input("Enter a number:"))
Pattern-85: 2) for i in range(1,num+1):
3) print(" "*(num-i),end="")
4) for j in range(i,i+1):
* 5) print("*",end=" ")
** 6) if i>=2:
* * 7) print(" "*(2*i-4),end="")
* * 8) for k in range(i,i+1):
* * 9) print("*",end=" ")
10) print()
1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
Pattern-86: 3) print(" "*(num-i),end="")
4) for j in range(i,i+1):
5) print(i,end=" ")
1
6) if i>=2:
22
7) print(" "*(2*i-4),end="")
3 3
8) for k in range(i,i+1):
4 4
9) print(i,end=" ")
5 5
10) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
202 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-87: 1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
5 3) print(" "*(num-i),end="")
44 4) for j in range(i,i+1):
3 3 5) print(num+1-i,end=" ")
2 2 6) if i>=2:
1 1 7) print(" "*(2*i-4),end="")
8) for k in range(i,i+1):
9) print(num+1-i,end=" ")
10) print()
1) num=int(input("Enter a number:"))
Pattern-88: 2) for i in range(1,num+1):
3) print(" "*(num-i),end="")
4) for j in range(i,i+1):
E
5) print(chr(64+num+1-i),end=" ")
DD
6) if i>=2:
C C
7) print(" "*(2*i-4),end="")
B B
8) for k in range(i,i+1):
A A
9) print(chr(64+num+1-i),end=" ")
10) print()
1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
Pattern-89:
3) print(" "*(num-i),end="")
4) for j in range(i,i+1):
5) print(chr(64+i),end=" ")
A 6) if i>=2:
BB 7) print(" "*(2*i-4),end="")
C C 8) for k in range(i,i+1):
D D 9) print(chr(64+i),end=" ")
E E 10) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
203 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-90: 1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
3) print(" "*(i-1),end="")
* *
4) for j in range(i,i+1):
* *
5) print("*",end=" ")
* *
6) if i<=4:
**
7) print(" "*(2*num-2*i-2),end="")
*
8) for k in range(i,i+1):
9) print("*",end=" ")
10) print()
1) num=int(input("Enter a number:"))
Pattern-91:
2) for i in range(1,num+1):
3) print(" "*(i-1),end="")
4) for j in range(i,i+1):
1 1 5) print(i,end=" ")
2 2 6) if i<num:
3 3 7) print(" "*(2*num-2*i-2),end="")
44 8) for k in range(i,i+1):
5 9) print(i,end=" ")
10) print()
1) num=int(input("Enter a number:"))
Pattern-92: 2) for i in range(1,num+1):
3) print(" "*(i-1),end="")
4) for j in range(i,i+1):
5 5 5) print(num-i+1,end=" ")
4 4 6) if i<=4:
3 3 7) print(" "*(2*num-2*i-2),end="")
22 8) for k in range(i,i+1):
1 9) print(num-i+1,end=" ")
10) print()
1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
Pattern-93: 3) print(" "*(i-1),end="")
4) for j in range(i,i+1):
5) print(chr(64+num-i+1),end=" ")
E E
6) if i<=4:
D D
7) print(" "*(2*num-2*i-2),end="")
C C 8) for k in range(i,i+1):
BB 9) print(chr(64+num-i+1),end=" ")
A 10) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
204 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-94: 1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
A A 3) print(" "*(i-1),end="")
B B 4) for j in range(i,i+1):
C C 5) print(chr(64+i),end=" ")
DD 6) if i<=4:
E 7) print(" "*(2*num-2*i-2),end="")
8) for k in range(i,i+1):
9) print(chr(64+i),end=" ")
10) print()
Pattern-95:
1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
*****
3) print(" "*(i-1),end="")
*****
4) for j in range(1,num+1):
*****
5) print("*",end=" ")
*****
6) print()
*****
1) num=int(input("Enter a number:"))
Pattern-96:
2) for i in range(1,num+1):
3) print(" "*(num-i),end="")
4) for j in range(1,i+1):
* * 5) print("*",end=" ")
** ** 6) print(" "*(num-i),end="")
*** *** 7) for k in range(1,i+1):
**** **** 8) print("*",end=" ")
********** 9) print()
Pattern-97:
1) n=int(input("Enter a number:"))
1 2) for i in range(1,n+1):
01 3) for j in range(1,i+1):
101 4) if (i%2!=0 and j%2!=0 )or(i%2==0 and j%2==0):
0101 5) print("1",end=" ")
10101 6) else:
010101 7) print("0",end=" ")
1010101 8) print()
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
205 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-98:
*
** 1) num=int(input("Enter a number:"))
*** 2) for i in range(1,num+1):
**** 3) print(" "*(2*num-i+3),end="")
*** 4) for j in range(1,i+1):
**** 5) print("*",end=" ")
***** 6) print()
****** 7) for i in range(1,num+3):
******* 8) print(" "*(2*num-i+1),end="")
******** 9) for j in range(-1,i+1):
**** 10) print("*",end=" ")
***** 11) print()
****** 12) for i in range(1,num+5):
******* 13) print(" "*(2*num-i),end="")
******** 14) for j in range(-2,i+1):
********* 15) print("*",end=" ")
********** 16) print()
*********** 17) for i in range(1,num+3):
*** 18) print(" "*((2*num)),end="")
*** 19) print("* "*3)
***
***
***
***
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
206 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-100:
**
** 1) n=int(input("Enter a number"))
**** 2) for i in range(1,2*n+1):
**** 3) if i%2==0:
****** 4) print("*"*i,end=" ")
****** 5) else:
******** 6) print("*"*(i+1),end=" ")
******** 7) print()
**********
**********
Pattern-101:
1) n=int(input("Enter a number:"))
2) for a in range(1,n+1,2):
3) for i in range(1,n+1):
4) print(" "*(2*n-i-a),end="")
5) for j in range(1,i+a):
6) print("*",end=" ")
7) print()
8) for b in range(1,n+1):
9) print(" "*(n-2),end="")
10) print("* "*3)
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
207 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
*
**
***
****
*****
******
*******
********
***
****
*****
******
*******
********
*********
**********
*****
******
*******
********
*********
**********
***********
************
*******
********
*********
**********
***********
************
*************
**************
***
***
***
***
***
***
***
***
D D
U U
R R
nd
G DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, G
208 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
A A
DURGA DURGA DURGA DURGA DURGA DURGA DURGA DURGA DURGA DURGA DURGA DURGA DURGA