0% found this document useful (0 votes)
3 views104 pages

core python

Python basic tutorials

Uploaded by

sharath.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views104 pages

core python

Python basic tutorials

Uploaded by

sharath.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

Introduction

 Python is a general purpose high level programming language.

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

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

 Python is recommended as first programming language for beginners.

Eg1: To print Helloworld

Java:

LANGUAGE
1) public class HelloWorld
2) {
3) p s v main(String[] args)
4) {
5) SOP("Hello world");

FUNDAMENTALS
6) }
7) }

C:

1) #include<stdio.h>
2) void main()
3) {
4) print("Hello world");
5) }

Python:
print("Hello World")

Eg2: To print the sum of 2 numbers

Java:

1) public class Add


2) {
3) public static void main(String[] args)
4) {
5) int a,b;
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
2  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
6) a =10; 5) For developing games
7) b=20; 6) For Data Analysis Applications
8) System.out.println("The Sum:"+(a+b)); 7) For Machine Learning
9) } 8) For developing Artificial Intelligence Applications
10) } 9) For IoT
...
C: Note:
 Internally Google and Youtube use Python coding.
1) #include <stdio.h>  NASA and Nework Stock Exchange Applications developed by Python.
2)  Top Software companies like Google, Microsoft, IBM, Yahoo using Python.
3) void main()
4) {
5) int a,b; Features of Python:
6) a =10;
7) b=20;
8) printf("The Sum:%d",(a+b)); 1) Simple and easy to learn:
9) }  Python is a simple programming language. When we read Python program,we can feel
like reading english statements.
Python:  The syntaxes are very simple and only 30+ kerywords are available.
 When compared with other languages, we can write programs with very less number
1) a=10 of lines. Hence more readability and simplicity.
2) b=20  We can reduce development and cost of the project.
3) print("The Sum:",(a+b))

The name Python was selected from the TV Show 2) Freeware and Open Source:
"The Complete Monty Python's Circus", which was broadcasted in BBC from 1969 to 1974.  We can use Python software without any licence and it is freeware.
 Its source code is open,so that we can we can customize based on our requirement.
Guido developed Python language by taking almost all programming features from  Eg: Jython is customized version of Python to work with Java Applications.
different languages
3) High Level Programming language:
1. Functional Programming Features from C  Python is high level programming language and hence it is programmer friendly
2. Object Oriented Programming Features from C++ language.
3. Scripting Language Features from Perl and Shell Script  Being a programmer we are not required to concentrate low level activities like
4. Modular Programming Features from Modula-3 memory management and security etc.

Most of syntax in Python Derived from C and ABC languages.


4) Platform Independent:
 Once we write a Python program,it can run on any platform without rewriting once
Where we can use Python: again.
 Internally PVM is responsible to convert into machine understandable form.
We can use everywhere. The most common important application areas are
5) Portability:
1) For developing Desktop Applications Python programs are portable. ie we can migrate from one platform to another
2) For developing web Applications platform very easily. Python programs will provide same results on any paltform.
3) For developing database Applications
4) For Network Programming
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
3  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
4  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
6) Dynamically Typed: Flavors of Python:
 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. 1) CPython:
 But Java, C etc are Statically Typed Languages b'z we have to provide type at the It is the standard flavor of Python. It can be used to work with C lanugage Applications.
beginning only.
 This dynamic typing nature will provide more flexibility to the programmer. 2) Jython OR JPython:
It is for Java Applications. It can run on JVM
7) Both Procedure Oriented and Object Oriented:
Python language supports both Procedure oriented (like C, pascal etc) and object 3) IronPython:
oriented (like C++, Java) features. Hence we can get benefits of both like security and It is for C#.Net platform
reusability etc
4) PyPy:
8) Interpreted: The main advantage of PyPy is performance will be improved because JIT compiler is
 We are not required to compile Python programs explcitly. Internally Python available inside PVM.
interpreter will take care that compilation.
 If compilation fails interpreter raised syntax errors. Once compilation success then 5) RubyPython
PVM (Python Virtual Machine) is responsible to execute.
For Ruby Platforms

9) Extensible: 6) AnacondaPython
 We can use other language programs in Python.
It is specially designed for handling large volume of data processing.
 The main advantages of this approach are:
 We can use already existing legacy non-Python code
 We can improve performance of the application Python Versions:
10) Embedded:  Python 1.0V introduced in Jan 1994
We can use Python programs in any other language programs.  Python 2.0V introduced in October 2000
i.e we can embedd Python programs anywhere.  Python 3.0V introduced in December 2008

11) Extensive Library: Note: Python 3 won't provide backward compatibility to Python2 i.e there is no
 Python has a rich inbuilt library. guarantee that Python2 programs will run in Python3.
 Being a programmer we can use this library directly and we are not responsible to
implement the functionality. Etc. Current versions
Limitations of Python: Python 3.6.1 Python 2.7.13
1) Performance wise not up to the mark because it is interpreted language.
2) Not using for mobile Applications.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
6  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
IDENTIFIERS
Identifier:
1) Alphabet Symbols (Either Upper case OR Lower case)

 A Name in Python Program is called Identifier. 2) If Identifier is start with Underscore (_) then it indicates it is private.
 It can be Class Name OR Function Name OR Module Name OR Variable Name.
3) Identifier should not start with Digits.
 a = 10
4) Identifiers are case sensitive.

Rules to define Identifiers in Python: 5) We cannot use reserved words as identifiers


Eg: def = 10 
1. The only allowed characters in Python are
6) There is no length limit for Python identifiers. But not recommended to use too
 alphabet symbols(either lower case or upper case) lengthy identifiers.
 digits(0 to 9)
 underscore symbol(_) 7) Dollor ($) Symbol is not allowed in Python.

By mistake if we are using any other symbol like $ then we will get syntax error.
Q) Which of the following are valid Python identifiers?
 cash = 10 √
 ca$h =20  1) 123total 
2) total123 √
2. Identifier should not starts with digit 3) java2share √
4) ca$h 
 123total  5) _abc_abc_ √
 total123 √ 6) def 
7) if 
3. Identifiers are case sensitive. Of course Python language is case sensitive language.
Note:
 total=10
 TOTAL=999 1) If identifier starts with _ symbol then it indicates that it is private
 print(total) #10 2) If identifier starts with __(Two Under Score Symbols) indicating that strongly private
 print(TOTAL) #999 identifier.
3) If the identifier starts and ends with two underscore symbols then the identifier is
language defined special name, which is also known as magic methods.

4) Eg: __add__

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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.
DATA TYPES
Such types of words are called reserved words.  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,
There are 33 reserved words available in Python. the type will be assigned automatically.Hence Python is dynamically Typed Language.

 True, False, None Python contains the following inbuilt data types
 and, or ,not,is
 if, elif, else 1) Int
 while, for, break, continue, return, in, yield 2) Float
 try, except, finally, raise, assert 3) Complex
 import, from, as, class, def, pass, global, nonlocal, lambda, del, with 4) Bool
5) Str
Note: 6) Bytes
7) Bytearray
1. All Reserved words in Python contain only alphabet symbols. 8) Range
9) List
2. Except the following 3 reserved words, all contain only lower case alphabet symbols. 10) Tuple
11) Set
 True 12) Frozenset
 False 13) Dict
14) None
 None

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

Note: Python contains several inbuilt functions

1) type()
to check the type of variable

2) id()
to get address of object

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
10  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
3) print() III) Octal Form (Base-8):
to print the value
 The allowed digits are : 0 to 7
In Python everything is an Object.  Literal value should be prefixed with 0o or 0O.

1) int Data Type:  Eg: a = 0o123


a = 0o786
We can use int data type to represent whole numbers (integral values)
Eg: a = 10 IV) Hexa Decimal Form (Base-16):
type(a) #int
 The allowed digits are: 0 to 9, a-f (both lower and upper cases are allowed)
Note:  Literal value should be prefixed with 0x or 0X
 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  Eg: a = 0XFACE
using int type only. a = 0XBeef
a = 0XBeer
We can represent int values in the following ways
Note: Being a programmer we can specify literal values in decimal, binary, octal and hexa
1) Decimal form decimal forms. But PVM will always provide values only in decimal form.
2) Binary form
3) Octal form  a=10
4) Hexa decimal form  b=0o10
 c=0X10
 d=0B10
I) Decimal Form (Base-10):  print(a)10
 print(b)8
 It is the default number system in Python  print(c)16
 The allowed digits are: 0 to 9  print(d)2
 Eg: a =10

Base Conversions
II) Binary Form (Base-2):
Python provide the following in-built functions for base conversions
 The allowed digits are : 0 & 1
 Literal value should be prefixed with 0b or 0B
1) bin():
 Eg: a = 0B1111 We can use bin() to convert from any base to binary
a = 0B123
1) >>> bin(15)
a = b111
2) '0b1111'
3) >>> bin(0o11)
4) '0b1001'
5) >>> bin(0X10)
6) '0b10000'

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
12  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) >>> f=0B11.01
2) oct(): 2) File "<stdin>", line 1
We can use oct() to convert from any base to octal 3) f=0B11.01
4) ^
1) >>> oct(10) 5) SyntaxError: invalid syntax
2) '0o12' 6)
3) >>> oct(0B1111) 7) >>> f=0o123.456
4) '0o17' 8) SyntaxError: invalid syntax
5) >>> oct(0X123) 9)
6) '0o443' 10) >>> f=0X123.456
11) SyntaxError: invalid syntax
3) hex():
We can use hex() to convert from any base to hexa decimal
3) Complex Data Type:
1) >>> hex(100)
2) '0x64'  A complex number is of the form
3) >>> hex(0B111111)
4) '0x3f' a + bj j2 = -1
5) >>> hex(0o12345) j=
6) '0x14e5' Real Part Imaginary Part

2) Float Data Type:  ‘a’ and ‘b’ contain Intergers OR Floating Point Values.

 We can use float data type to represent floating point values (decimal values) Eg: 3 + 5j
Eg: f = 1.234 10 + 5.5j
type(f) float 0.5 + 0.1j

 We can also represent floating point values by using exponential form  In the real part if we use int value then we can specify that either by decimal, octal,
(Scientific Notation) binary or hexa decimal form.
Eg: f = 1.2e3  instead of 'e' we can use 'E'  But imaginary part should be specified only by using decimal form.
print(f) 1200.0
1) >>> a=0B11+5j
 The main advantage of exponential form is we can represent big values in less 2) >>> a
memory. 3) (3+5j)
4) >>> a=3+0B11j
5) SyntaxError: invalid syntax
***Note:
We can represent int values in decimal, binary, octal and hexa decimal forms. But we
 Even we can perform operations on complex type values.
can represent float values only by using decimal form.
1) >>> a=10+1.5j
2) >>> b=20+2.5j
3) >>> c=a+b
4) >>> print(c)
5) (30+4j)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
14  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
6) >>> type(c)  By using single quotes or double quotes we cannot represent multi line string
7) <class 'complex'> literals.

Note: Complex data type has some inbuilt attributes to retrieve the real part and  s1="durga
imaginary part soft"

c = 10.5+3.6j  For this requirement we should go for triple single quotes(''') or triple double
quotes(""")
c.real  10.5
c.imag  3.6  s1='''durga
soft'''
We can use complex type generally in scientific Applications and electrical engineering
Applications.  s1="""durga
soft"""

4) bool Data Type:  We can also use triple quotes to use single quote or double quote in our String.
 ''' This is " character'''
 We can use this data type to represent boolean values. ' This i " Character '
 The only allowed values for this data type are:
 True and False  We can embed one string in another string
 '''This "Python class very helpful" for java students'''
 Internally Python represents True as 1 and False as 0

b = True
Slicing of Strings:
type(b) bool
1) slice means a piece
2) [ ] operator is called slice operator, which can be used to retrieve parts of String.
Eg:
3) In Python Strings follows zero based index.
a = 10
4) The index can be either +ve or -ve.
b = 20
5) +ve index means forward direction from Left to Right
c = a<b
6) -ve index means backward direction from Right to Left
print(c)  True
-5 -4 -3 -2 -1
d u r g a
True+True  2 0 1 2 3 4
True-False  1 1) >>> s="durga"
2) >>> s[0]
5) str Data Type: 3)
4)
'd'
>>> s[1]
5) 'u'
 str represents String data type. 6) >>> s[-1]
 A String is a sequence of characters enclosed within single quotes or double 7) 'a'
quotes. 8) >>> s[40]
 s1='durga' IndexError: string index out of range
 s1="durga"
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
16  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
TYPE CASTING
1) >>> s[1:40]
2) 'urga'
3) >>> s[1:]
4) 'urga'
5) >>> s[:4]
6) 'durg' ֍ We can convert one type value to another type. This conversion is called Typecasting
7) >>> s[:] or Type coersion.
8) 'durga' ֍ The following are various inbuilt functions for type casting.
9) >>>
10) 1) int()
11) >>> s*3 2) float()
12) 'durgadurgadurga' 3) complex()
13) 4) bool()
14) >>> len(s) 5) str()
15) 5

Note:
֍ int():
We can use this function to convert values from other types to int
1) In Python the following data types are considered as Fundamental Data types
1) >>> int(123.987)
2) 123
 int
3) >>> int(10+5j)
 float
4) TypeError: can't convert complex to int
 complex
5) >>> int(True)
 bool
6) 1
 str 7) >>> int(False)
8) 0
2) In Python, we can represent char values also by using str type and explicitly char type 9) >>> int("10")
is not available. 10) 10
11) >>> int("10.5")
1) >>> c='a'
12) ValueError: invalid literal for int() with base 10: '10.5'
2) >>> type(c)
13) >>> int("ten")
3) <class 'str'>
14) ValueError: invalid literal for int() with base 10: 'ten'
15) >>> int("0B1111")
3) long Data Type is available in Python2 but not in Python3. In Python3 long values also
16) ValueError: invalid literal for int() with base 10: '0B1111'
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
Note:
not available.
1) We can convert from any type to int except complex type.
2) If we want to convert str type to int type, compulsary str should contain only integral
value and should be specified in base-10.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
18  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Form-2: complex(x,y)
֍ float():
We can use float() function to convert other type values to float type. We can use this method to convert x and y into complex number such that x will be real
part and y will be imaginary part.
1) >>> float(10)
2) 10.0 Eg: complex(10, -2)  10-2j
3) >>> float(10+5j) complex(True, False)  1+0j
4) TypeError: can't convert complex to float
5) >>> float(True)
6) 1.0 ֍ bool():
7) >>> float(False) We can use this function to convert other type values to bool type.
8) 0.0
9) >>> float("10") 1) bool(0)  False
10) 10.0 2) bool(1)  True
11) >>> float("10.5") 3) bool(10)  True
12) 10.5 4) bool(10.5)  True
13) >>> float("ten") 5) bool(0.178)  True
14) ValueError: could not convert string to float: 'ten' 6) bool(0.0)  False
15) >>> float("0B1111") 7) bool(10-2j)  True
16) ValueError: could not convert string to float: '0B1111' 8) bool(0+1.5j)  True
9) bool(0+0j)  False
Note: 10) bool("True")  True
1) We can convert any type value to float type except complex type. 11) bool("False")  True
2) Whenever we are trying to convert str type to float type compulsary str should be 12) bool("")  False
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 nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
20  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
֍ str(): >>> a=10 >>> a=10+5j >>> a=True >>> a='durga'
We can use this method to convert other type values to str type.
>>> b=10 >>> b=10+5j >>> b=True >>> b='durga'
1) >>> str(10)
2) '10' >>> id(a) >>> a is b >>> a is b >>> a is b
3) >>> str(10.5)
4) '10.5' 1572353952 False True True
5) >>> str(10+5j)
6) '(10+5j)' >>> id(b) >>> id(a) >>> id(a) >>> id(a)
7) >>> str(True)
8) 'True' 1572353952 15980256 1572172624 16378848

Fundamental Data Types vs Immutability: >>> a is b >>> id(b) >>> id(b) >>> id(b)

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

֍ In Python if a new object is required, then PVM won’t create object immediately. First 6) bytes Data Type:
it will check is any object available with the required content or not. If available then bytes data type represens a group of byte numbers just like an array.
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 1) x = [10,20,30,40]
improved. 2) b = bytes(x)
3) type(b)  bytes
֍ But the problem in this approach is, several references pointing to the same object, by 4) print(b[0])  10
using one reference if we are allowed to change the content in the existing object then 5) print(b[-1])  40
the remaining references will be effected. To prevent this immutability concept is 6) >>> for i in b : print(i)
required. According to this once creates an object we are not allowed to change 7)
content. If we are trying to change with those changes a new object will be created. 8) 10
9) 20
10) 30
1) >>> a=10
11) 40
2) >>> b=10
3) >>> a is b
4) True
Conclusion 1:
The only allowed values for byte data type are 0 to 256. By mistake if we are trying to
5) >>> id(a)
provide any other values then we will get value error.
6) 1572353952
7) >>> id(b)
8) 1572353952 Conclusion 2:
9) >>> Once we creates bytes data type value, we cannot change its values,otherwise we will get
TypeError.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
22  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg: Eg:
1) >>> x=[10,20,30,40] 1) list=[10,10.5,'durga',True,10]
2) >>> b=bytes(x) 2) print(list) # [10,10.5,'durga',True,10]
3) >>> b[0]=100
4) TypeError: 'bytes' object does not support item assignment Eg:

7) bytearray Data Type: 1) list=[10,20,30,40]


2) >>> list[0]
bytearray is exactly same as bytes data type except that its elements can be
3) 10
modified.
4) >>> list[-1]
5) 40
Eg 1:
6) >>> list[1:3]
7) [20, 30]
1) x=[10,20,30,40]
8) >>> list[0]=100
2) b = bytearray(x)
9) >>> for i in list:print(i)
3) for i in b : print(i)
10) ...
4) 10
11) 100
5) 20
12) 20
6) 30
13) 30
7) 40
14) 40
8) b[0]=100
9) for i in b: print(i)
list is growable in nature. i.e based on our requirement we can increase or decrease the
10) 100
size.
11) 20
12) 30 1) >>> list=[10,20,30]
13) 40
2) >>> list.append("durga")
3) >>> list
Eg 2:
4) [10, 20, 30, 'durga']
5) >>> list.remove(20)
1) >>> x =[10,256]
6) >>> list
2) >>> b = bytearray(x)
7) [10, 30, 'durga']
3) ValueError: byte must be in range(0, 256)
8) >>> list2=list*2
9) >>> list2
8) List Data Type: 10) [10, 30, 'durga', 10, 30, 'durga']
If we want to represent a group of values as a single entity where insertion order
required to preserve and duplicates are allowed then we should go for list data Note: An ordered, mutable, heterogenous collection of eleemnts is nothing but list,
type. where duplicates also allowed.

1) Insertion Order is preserved


2) Heterogeneous Objects are allowed
3) Duplicates are allowed
4) Growable in nature
5) Values should be enclosed within square brackets.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
24  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Form-3: range(10, 20, 2)
9) Tuple Data Type: 2 means increment value
 tuple data type is exactly same as list data type except that it is immutable.i.e we
cannot chage values.
Eg:
 Tuple elements can be represented within parenthesis. r = range(10,20,2)
for i in r : print(i)  10,12,14,16,18
Eg:
We can access elements present in the range Data Type by using index.
1) t=(10,20,30,40)
2) type(t)
3) <class 'tuple'>
Eg:
4) t[0]=100 r = range(10,20)
5) TypeError: 'tuple' object does not support item assignment r[0]  10
6) >>> t.append("durga") r[15]  IndexError: range object index out of range
7) AttributeError: 'tuple' object has no attribute 'append'
8) >>> t.remove(10) We cannot modify the values of range data type
9) AttributeError: 'tuple' object has no attribute 'remove'
Eg:
Note: tuple is the read only version of list r[0] = 100
TypeError: 'range' object does not support item assignment

10) Range Data Type: We can create a list of values with range data type
 range Data Type represents a sequence of numbers.
 The elements present in range Data type are not modifiable. i.e range Data type is Eg:
immutable.
1) >>> l = list(range(10))
Form-1: range(10) 2) >>> l
generate numbers from 0 to 9 3) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Eg: 11) set Data Type:


r = range(10)
for i in r : print(i)  0 to 9 ֍ If we want to represent a group of values without duplicates where order is not
important then we should go for set Data Type.
Form-2: range(10, 20)
generate numbers from 10 to 19 1) Insertion order is not preserved
2) Duplicates are not allowed
Eg: 3) Heterogeneous objects are allowed
r = range(10,20) 4) Index concept is not applicable
for i in r : print(i) 10 to 19 5) It is mutable collection
6) Growable in nature

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
26  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
13) dict Data Type:
1) s={100,0,10,200,10,'durga'}
2) s # {0, 100, 'durga', 200, 10} ֍ If we want to represent a group of values as key-value pairs then we should go for
3) s[0]  TypeError: 'set' object does not support indexing dict data type.

֍ set is growable in nature, based on our requirement we can increase or decrease the ֍ Eg: d = {101:'durga',102:'ravi',103:'shiva'}
size.
֍ Duplicate keys are not allowed but values can be duplicated. If we are trying to
1) >>> s.add(60) insert an entry with duplicate key then old value will be replaced with new value.
2) >>> s
3) {0, 100, 'durga', 200, 10, 60} Eg:
4) >>> s.remove(100)
5) >>> s 1) >>> d={101:'durga',102:'ravi',103:'shiva'}
6) {0, 'durga', 200, 10, 60} 2) >>> d[101]='sunny'
3) >>> d
4) {101: 'sunny', 102: 'ravi', 103: 'shiva'}
12) frozenset Data Type: 5)
6) We can create empty dictionary as follows
֍ It is exactly same as set except that it is immutable. 7) d={ }
֍ Hence we cannot use add or remove functions. 8) We can add key-value pairs as follows
9) d['a']='apple'
1) >>> s={10,20,30,40} 10) d['b']='banana'
2) >>> fs=frozenset(s) 11) print(d)
3) >>> type(fs)
4) <class 'frozenset'> Note: dict is mutable and the order won’t be preserved.
5) >>> fs
6) frozenset({40, 10, 20, 30})
Note:
7) >>> for i in fs:print(i)
8) ...
9) 40 1) In general we can use bytes and bytearray data types to represent binary information
10) 10 like images, video files etc
11) 20 2) In Python2 long data type is available. But in Python3 it is not available and we can
12) 30 represent long values also by using int type only.
13) 3) In Python there is no char data type. Hence we can represent char values also by using
14) >>> fs.add(70) str type.
15) AttributeError: 'frozenset' object has no attribute 'add'
16) >>> fs.remove(10)
17) AttributeError: 'frozenset' object has no attribute 'remove'

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
28  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]
Summary of Datatypes in Python 3 ordered collection of >>> type(l)
objects <class 'list'>
Datatype Description Is Immutable? Example
tuple To represent an Immutable >>> t=(1,2,3,4,5)
Int We can use to Immutable >>> a=10
ordered collections of >>> type(t)
represent the >>> type(a)
objects <class 'tuple'>
whole/integral <class 'int'>
numbers set To represent an Mutable >>> s={1,2,3,4,5,6}
unordered collection >>> type(s)
Float We can use to Immutable >>> b=10.5
of unique objects <class 'set'>
represent the >>> type(b)
decimal/floating <class 'float'> frozenset To represent an Immutable >>> s={11,2,3,'Durga',100,'Ramu'}
point numbers unordered collection >>> fs=frozenset(s)
of unique objects >>> type(fs)
Complex We can use to Immutable >>> c=10+5j
<class 'frozenset'>
represent the >>> type(c)
complex numbers <class 'complex'> dict To represent a group Mutable >>>
>>> c.real of key value pairs d = {101:'durga', 102:'ramu',
10.0 103:'hari'}
>>> c.imag >>> type(d)
5.0 <class 'dict'>
Bool We can use to Immutable >>> flag=True
represent the logical >>> flag=False
values (Only allowed >>> type(flag) 14) None Data Type:
values are True and <class 'bool'>
False)  None means nothing or No value associated.
Str To represent Immutable >>> s='durga'  If the value is not available, then to handle such type of cases None introduced.
sequence of >>> type(s)  It is something like null value in Java.
Characters <class 'str'>
>>> s="durga" Eg:
>>> s='''Durga Software def m1():
Solutions... Ameerpet''' a=10
>>> type(s)
<class 'str'> print(m1())
bytes To represent a Immutable >>> list=[1,2,3,4] None
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 nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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

OPERATORS
13) >>> s="This is \" symbol"
14) >>> print(s)
15) This is " symbol

The following are various important escape characters in Python

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

 It is just convention but we can change the value.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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. a//b= 5
 Python provides the following set of operators a%b= 0
a**b= 100
1) Arithmetic Operators
2) Relational Operators OR Comparison Operators Eg:
3) Logical operators
4) Bitwise oeprators 1) a = 10.5
5) Assignment operators 2) b=2
6) Special operators 3)
4) a+b= 12.5
5) a-b= 8.5
1) Arithmetic Operators: 6) a*b= 21.0
7) a/b= 5.25
1) +  Addition 8) a//b= 5.0
9) a%b= 0.5
2) –  Subtraction 10) a**b= 110.25

3) *  Multiplication Eg:
10/2  5.0
4) /  Division Operator 10//2  5
10.0/2  5.0
5) %  Modulo Operator 10.0//2  5.0

6) //  Floor Division Operator Note:


֍ / operator always performs floating point arithmetic. Hence it will always returns float
7) **  Exponent Operator OR Power Operator
value.
Eg: test.py ֍ 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
1) a=10
result is float type.
2) b=2
3) print('a+b=',a+b)
4) print('a-b=',a-b)
Note:
5) print('a*b=',a*b) ֍ We can use +,* operators for str type also.
6) print('a/b=',a/b) ֍ If we want to use + operator for str type then compulsory both arguments should be
7) print('a//b=',a//b) str type only otherwise we will get error.
8) print('a%b=',a%b)
9) print('a**b=',a**b) 1) >>> "durga"+10
2) TypeError: must be str, not int
3) >>> "durga"+"10"
Output:
4) 'durga10'
Python test.py OR py test.py
a+b = 12
֍ If we use * operator for str type then compulsory one argument should be int and
a-b= 8
other argument should be str type.
a*b= 20
a/b= 5.0

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
34  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
֍ 2*"durga" Eg:
"durga"*2
2.5*"durga"  TypeError: can't multiply sequence by non-int of type 'float' 1) print(True>True) False
"durga"*"durga"  TypeError: can't multiply sequence by non-int of type 'str' 2) print(True>=True) True
3) print(10 >True) True
֍ +  String Concatenation Operator 4) print(False > True) False
֍ *  String Multiplication Operator 5)
6) print(10>'durga')
Note: For any number x, 7) TypeError: '>' not supported between instances of 'int' and 'str'
x/0 and x%0 always raises "ZeroDivisionError"
Eg:
10/0
10.0/0 1) a=10
..... 2) b=20
3) if(a>b):
4) print("a is greater than b")
2) Relational Operators: >, >=, <, <= 5) else:
6) print("a is not greater than b")
1) a=10
2) b=20 Output: a is not greater than b
3) print("a > b is ",a>b)
4) print("a >= b is ",a>=b) Note: Chaining of relational operators is possible. In the chaining, if all comparisons
5) print("a < b is ",a<b) returns True then only result is True. If atleast one comparison returns False then the
6) print("a <= b is ",a<=b) result is False
7)
8) a > b is False 1) 10<20  True
9) a >= b is False 2) 10<20<30  True
10) a < b is True 3) 10<20<30<40  True
11) a <= b is True 4) 10<20<30<40>50  False
We can apply relational operators for str types also.
3) Equality Operators: ==, !=
Eg 2: We can apply these operators for any type even for incompatible types also.

1) a="durga" 1) >>> 10==20


2) b="durga" 2) False
3) print("a > b is ",a>b) 3) >>> 10!= 20
4) print("a >= b is ",a>=b) 4) True
5) print("a < b is ",a<b) 5) >>> 10==True
6) print("a <= b is ",a<=b) 6) False
7) 7) >>> False==False
8) a > b is False 8) True
9) a >= b is True 9) >>> "durga"=="durga"
10) a < b is False 10) True
11) a <= b is True 11) >>> 10=="durga"

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
36  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
12) False not x:
If x is evalutates to False then result is True otherwise 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. not 10  False
not 0  True
1) >>> 10==20==30==40
2) False
3) >>> 10==10==10==10
Eg:
4) True
1) "durga" and "durgasoft" ==>durgasoft
2) "" and "durga" ==>""
4) Logical Operators: and, or, not 3) "durga" and "" ==>""
We can apply for all types. 4) "" or "durga" ==>"durga"
5) "durga" or ""==>"durga"
6) not ""==>True
 For boolean Types Behaviour: 7) not "durga" ==>False
and  If both arguments are True then only result is True
or  If atleast one arugemnt is True then result is True
not  Complement 5) Bitwise Operators:
True and False  False ֍ We can apply these operators bitwise.
True or False  True ֍ These operators are applicable only for int and boolean types.
not False  True ֍ By mistake if we are trying to apply for any other type then we will get Error.

 For non-boolean Types Behaviour: ֍ &, |, ^, ~, <<, >>


0 means False
non-zero means True ֍ print(4&5)  Valid
empty string is always treated as False ֍ print(10.5 & 5.6)
 TypeError: unsupported operand type(s) for &: 'float' and 'float'

x and y: ֍ print(True & True)  Valid


If x is evaluates to false return x otherwise return y
Eg: ֍ &  If both bits are 1 then only result is 1 otherwise result is 0
10 and 20 ֍ | If atleast one bit is 1 then result is 1 otherwise result is 0
0 and 20 ֍ ^  If bits are different then only result is 1 otherwise result is 0
֍ ~  bitwise complement operator
If first argument is zero then result is zero otherwise result is y ֍ 10 & 01
֍ <<  Bitwise Left Shift
x or y: ֍ >>  Bitwise Right Shift
If x evaluates to True then result is x otherwise result is y
֍ print(4&5)  4
10 or 20  10 ֍ print(4|5)  5
0 or 20  20 ֍ print(4^5)  1

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
38  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
Operator Description
& If both bits are 1 then only result is 1 otherwise result is 0 ֍ print(True & False)  False
֍ print(True | False)  True
| If atleast one bit is 1 then result is 1 otherwise result is 0
֍ print(True ^ False)  True
^ If bits are different then only result is 1 otherwise result is 0 ֍ print(~True)  -2
~ bitwise complement operator i.e 1 means 0 and 0 means 1 ֍ print(True<<2)  4
>> Bitwise Left shift Operator ֍ print(True>>2)  0

<< Bitwise Right shift Operator


7) Assignment Operators:
Bitwise Complement Operator (~): ֍ We can use assignment operator to assign value to the variable.
We have to apply complement for total bits. Eg: x = 10

Eg: print(~5) -6 ֍ We can combine asignment operator with some other operator to form compound
assignment operator.
Note: Eg: x += 10  x = x+10
֍ The most significant bit acts as sign bit. 0 value represents +ve number where as 1
represents -ve value. The following is the list of all possible compound assignment operators in Python.
֍ 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 Eg:

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

print(10>>2)  2 Eg:
0 0 0 0 1 0 1 0 1) x=10
2) x&=5
0 0 0 0 0 0 1 0 3) print(x)  0
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
40  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg:
8) Ternary Operator OR Conditional Operator
1) a=int(input("Enter First Number:"))
Syntax: x = firstValue if condition else secondValue 2) b=int(input("Enter Second Number:"))
3) print("Both numbers are equal" if a==b else "First Number is Less than Second Nu
If condition is True then firstValue will be considered else secondValue will be considered. mber" if a<b else "First Number Greater than Second Number")

Eg 1: Output:
D:\python_classes>py test.py
1) a,b=10,20 Enter First Number:10
2) x=30 if a<b else 40 Enter Second Number:10
3) print(x) #30 Both numbers are equal

D:\python_classes>py test.py
Eg 2: Read two numbers from the keyboard and print minimum value Enter First Number:10
Enter Second Number:20
1) a=int(input("Enter First Number:")) First Number is Less than Second Number
2) b=int(input("Enter Second Number:"))
3) min=a if a<b else b D:\python_classes>py test.py
4) print("Minimum Value:",min) Enter First Number:20
Enter Second Number:10
Output: First Number Greater than Second Number
Enter First Number:10
Enter Second Number:30
Minimum Value: 10 9) Special Operators:
Python defines the following 2 special operators
Note: Nesting of Ternary Operator is Possible. 1) Identity Operators
2) Membership operators
Q) Program for Minimum of 3 Numbers
1) Identity Operators
1) a=int(input("Enter First Number:"))
 We can use identity operators for address comparison.
2) b=int(input("Enter Second Number:"))
 There are 2 identity operators are available
3) c=int(input("Enter Third Number:"))
1) is
4) min=a if a<b and a<c else b if b<c else c
2) is not
5) print("Minimum Value:",min)
 r1 is r2 returns True if both r1 and r2 are pointing to the same object.
Q) Program for Maximum of 3 Numbers  r1 is not r2 returns True if both r1 and r2 are not pointing to the same object.

1) a=int(input("Enter First Number:"))


Eg:
2) b=int(input("Enter Second Number:"))
3) c=int(input("Enter Third Number:"))
1) a=10
4) max=a if a>b and a>c else b if b>c else c
2) b=10
5) print("Maximum Value:",max)
3) print(a is b) True
4) x=True

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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 Operator Precedence:
Eg: If multiple operators present then which operator will be evaluated first is decided by
operator precedence.
1) a="durga"
2) b="durga" Eg:
3) print(id(a)) print(3+10*2)  23
4) print(id(b)) print((3+10)*2)  26
5) print(a is b)
The following list describes operator precedence in Python
Eg:
1) ()  Parenthesis
1) list1=["one","two","three"] 2) **  Exponential Operator
2) list2=["one","two","three"] 3) ~, -  Bitwise Complement Operator, Unary Minus Operator
3) print(id(list1)) 4) *, /, %, //  Multiplication, Division, Modulo, Floor Division
4) print(id(list2)) 5) +, -  Addition, Subtraction
5) print(list1 is list2) False 6) <<, >>  Left and Right Shift
6) print(list1 is not list2) True 7) &  Bitwise And
7) print(list1 == list2) True 8) ^  Bitwise X-OR
9) |  Bitwise OR
Note: We can use is operator for address comparison where as == operator for content 10) >, >=, <, <=, ==, !=  Relational OR Comparison Operators
comparison. 11) =, +=, -=, *=...  Assignment Operators
12) is , is not  Identity Operators
13) in , not in  Membership operators
2) Membership Operators: 14) not  Logical not
 We can use Membership operators to check whether the given object present in the 15) and  Logical and
given collection. (It may be String, List, Set, Tuple OR Dict) 16) or  Logical or
 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 1) a=30
2) b=20
Eg: 3) c=10
4) d=5
1) x="hello learning Python is very easy!!!" 5) print((a+b)*c/d)  100.0
2) print('h' in x) True 6) print((a+b)*(c/d))  100.0
3) print('d' in x) False 7) print(a+(b*c)/d)  70.0
4) print('d' not in x) True 8)
5) print('Python' in x) True 9) 3/2*4+3+(10/5)**3-2
10) 3/2*4+3+2.0**3-2
Eg: 11) 3/2*4+3+8.0-2
12) 1.5*4+3+8.0-2
1) list1=["sunny","bunny","chinny","pinny"] 13) 6.0+3+8.0-2
2) print("sunny" in list1) True 14) 15.0
3) print("tunny" in list1) False
4) print("tunny" not in list1) True

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
44  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Mathematical Functions (math Module) Important Functions of math Module:
1) ceil(x)
֍ A Module is collection of functions, variables and classes etc.
2) floor(x)
֍ math is a module that contains several functions to perform mathematical operations.
3) pow(x,y)
֍ If we want to use any module in Python, first we have to import that module. 4) factorial(x)
import math 5) trunc(x)
֍ Once we import a module then we can call any function of that module. 6) gcd(x,y)
7) sin(x)
1) import math 8) cos(x)
2) print(math.sqrt(16)) 9) tan(x)
3) print(math.pi) 10) ....

Output
4.0 Important Variables of math Module:
3.141592653589793
pi3.14
֍ We can create alias name by using as keyword. import math as m e  2.71
֍ Once we create alias name, by using that we can access functions and variables of that inf  infinity
module. nan  not a number

1) import math as m Q) Write a Python Program to find Area of Circle pi*r**2


2) print(m.sqrt(16))
3) print(m.pi) 1) from math import pi
2) r = 16
֍ We can import a particular member of a module explicitly as follows 3) print("Area of Circle is :",pi*r**2)
from math import sqrt
from math import sqrt,pi Output: Area of Circle is: 804.247719318987

֍ If we import a member explicitly then it is not required to use module name while
accessing.

1) from math import sqrt,pi


2) print(sqrt(16))
3) print(pi)
4) print NameError: name (math.pi) 'math' is not defined

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
46  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
INPUT AND OUTPUT STATEMENTS 8) Enter value:True
9) <class 'str'>

Q) Write a program to read 2 numbers from the keyboard and print sum
Reading Dynamic Input from the Keyboard:
In Python 2 the following 2 functions are available to read dynamic input from the 1) x=input("Enter First Number:")
keyboard. 2) y=input("Enter Second Number:")
3) i = int(x)
1) raw_input() 4) j = int(y)
2) input() 5) print("The Sum:",i+j)

1) raw_input(): Enter First Number: 100


This function always reads the data from the keyboard in the form of String Format. Enter Second Number: 200
We have to convert that string type to our required type by using the corresponding The Sum: 300
type casting methods. -----------------------------------------------------

Eg: x = raw_input("Enter First Number:") 1) x=int(input("Enter First Number:"))


print(type(x))  It will always print str type only for any input type 2) y=int(input("Enter Second Number:"))
3) print("The Sum:",x+y)

2) input(): -----------------------------------------------------------
input() function can be used to read data directly in our required format.We are not
required to perform type casting. print("The Sum:",int(input("Enter First Number:"))+int(input("Enter Second Number:")))

x = input("Enter Value) Q) Write a Program to read Employee Data from the Keyboard and
type(x)
print that Data
10  int
1) eno=int(input("Enter Employee No:"))
"durga" str
2) ename=input("Enter Employee Name:")
10.5  float
True  bool 3) esal=float(input("Enter Employee Salary:"))
4) eaddr=input("Enter Employee Address:")
5) married=bool(input("Employee Married ?[True|False]:"))
***Note:
6) print("Please Confirm Information")
 But in Python 3 we have only input() method and raw_input() method is not available. 7) print("Employee No :",eno)
 Python3 input() function behaviour exactly same as raw_input() method of Python2. 8) print("Employee Name :",ename)
i.e every input value is treated as str type only. 9) print("Employee Salary :",esal)
 raw_input() function of Python 2 is renamed as input() function in Python 3. 10) print("Employee Address :",eaddr)
11) print("Employee Married ? :",married)
1) >>> type(input("Enter value:"))
2) Enter value:10 D:\Python_classes>py test.py
3) <class 'str'> Enter Employee No:100
4) Enter Employee Name:Sunny
5) Enter value:10.5 Enter Employee Salary:1000
6) <class 'str'> Enter Employee Address:Mumbai
7)
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
47  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
48  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Employee Married ?[True|False]:True eval() can evaluate the Input to list, tuple, set, etc based the provided Input.
Please Confirm Information
Eg: Write a Program to accept list from the keynboard on the display
Employee No : 100
Employee Name : Sunny 1) l = eval(input(“Enter List”))
Employee Salary : 1000.0 2) print (type(l))
Employee Address : Mumbai 3) print(l)
Employee Married ? : True

How to read multiple values from the keyboard in a COMMAND LINE ARGUMENTS
single line:  argv is not Array it is a List. It is available sys Module.
 The Argument which are passing at the time of execution are called Command Line
1) a,b= [int(x) for x in input("Enter 2 numbers :").split()] Arguments.
2) print("Product is :", a*b)
Eg: D:\Python_classes py test.py 10 20 30
D:\Python_classes>py test.py
Enter 2 numbers :10 20 Command Line Arguments
Product is : 200
Within the Python Program this Command Line Arguments are available in argv. Which is
Note: split() function can take space as seperator by default .But we can pass present in SYS Module.
anything as seperator.
test.py 10 20 30
Q) Write a program to read 3 float numbers from the keyboard
Note: argv[0] represents Name of Program. But not first Command Line Argument.
with, seperator and print their sum argv[1] represent First Command Line Argument.
1) a,b,c= [float(x) for x in input("Enter 3 float numbers :").split(',')]
2) print("The Sum is :", a+b+c) Program: To check type of argv from sys

D:\Python_classes>py test.py import argv


Enter 3 float numbers :10.5,20.6,20.1 print(type(argv))
The Sum is : 51.2
D:\Python_classes\py test.py

eval():
eval Function take a String and evaluate the Result.
Write a Program to display Command Line Arguments
Eg: x = eval(“10+20+30”) 1) from sys import argv
print(x) 2) print(“The Number of Command Line Arguments:”, len(argv))
Output: 60 3) print(“The List of Command Line Arguments:”, argv)
4) print(“Command Line Arguments one by one:”)
Eg: x = eval(input(“Enter Expression”)) 5) for x in argv:
Enter Expression: 10+2*3/4 6) print(x)
Output: 11.5

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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 D:\Python_classes>py test.py 10 20
The Number of Command Line Arguments: 4 1020
The List of Command Line Arguments: [‘test.py’, ‘10’,’20’,’30’] 30
Command Line Arguments one by one:
test.py Note 3: If we are trying to access command line arguments with out of range index then
10 we will get Error.
20
30 1) from sys import argv
--------------------------- 2) print(argv[100])

1) from sys import argv D:\Python_classes>py test.py 10 20


2) sum=0 IndexError: list index out of range
3) args=argv[1:]
4) for x in args : Note: In Python there is argparse module to parse command line arguments and display
5) n=int(x) some help messages whenever end user enters wrong input.
6) sum=sum+n
7) print("The Sum:",sum) input()
raw_input()
D:\Python_classes>py test.py 10 20 30 40
The Sum: 100 Command Line Arguments

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
Output Statements:
single quotes)
We can use print() function to display output.
1) from sys import argv
2) print(argv[1]) Form-1: print() without any argument
Just it prints new line character
D:\Python_classes>py test.py Sunny Leone
Sunny Form-2:

D:\Python_classes>py test.py 'Sunny Leone' 1) print(String):


'Sunny 2) print("Hello World")
3) We can use escape characters also
D:\Python_classes>py test.py "Sunny Leone" 4) print("Hello \n World")
Sunny Leone 5) print("Hello\tWorld")
6) We can use repetetion operator (*) in the string
Note 2: Within the Python program command line arguments are available in the String 7) print(10*"Hello")
form. Based on our requirement, we can convert into corresponding type by using type 8) print("Hello"*10)
casting methods. 9) We can use + operator also
10) print("Hello"+"World")
1) from sys import argv
2) print(argv[1]+argv[2])
3) print(int(argv[1])+int(argv[2]))

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
52  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note: If we want output in the same line with space
֍ 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 1) print("Hello",end=' ')
Error. 2) print("Durga",end=' ')
֍ If both arguments are number type then + operator acts as arithmetic addition 3) print("Soft")
operator.
Output: Hello Durga Soft
Note:
Note: The default value for end attribute is \n, which is nothing but new line character.
1) print("Hello"+"World")
2) print("Hello","World") Form-5: print(object) statement
HelloWorld We can pass any object (like list, tuple, set etc) as argument to the print() statement.
Hello World
1) l=[10,20,30,40]
Form-3: print() with variable number of arguments 2) t=(10,20,30,40)
3) print(l)
1) a,b,c=10,20,30 4) print(t)
2) print("The Values are :",a,b,c)
Form-6: print(String, variable list)
Output: The Values are : 10 20 30
We can use print() statement with String and any number of arguments.
By default output values are seperated by space.If we want we can specify seperator by
using "sep" attribute 1) s = "Durga"
2) a = 48
1) a,b,c=10,20,30 3) s1 ="Java"
2) print(a,b,c,sep=',') 4) s2 ="Python"
3) print(a,b,c,sep=':') 5) print("Hello",s,"Your Age is",a)
6) print("You are teaching",s1,"and",s2)
D:\Python_classes>py test.py
10,20,30 Output:
10:20:30 Hello Durga Your Age is 48
You are teaching java and Python
Form-4:print() with end attribute
Form-7: print (formatted string)
1) print("Hello")
2) print("Durga") 1) %i  int
3) print("Soft") 2) %d  int
3) %f  float
Output: 4) %s  String type
Hello
Durga Syntax: print("formatted string" %(variable list))
Soft

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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"

FLOW
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]

Form-8: print() with replacement operator {}

Eg:

1) name = "Durga"

CONTROL
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 nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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. D:\Python_classes>py test.py
Enter Name: Ravi
How are you!!!
Control Flow
2) if-else:
if condition:
Action-1
else:
Conditional Transfer Iterative Action-2
Statements Statements Statements
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" :
1) if 1) break 1) for 3) print("Hello Durga Good Morning")
2) if-elif 2) continue 2) while 4) else:
3) if-elif-else 3) pass 5) print("Hello Guest Good Moring")
6) print("How are you!!!")

I. Conditional Statements D:\Python_classes>py test.py


Enter Name:durga
Hello Durga Good Morning
1) if How are you!!!
if condition : statement
OR D:\Python_classes>py test.py
Enter Name:Ravi
if condition : Hello Guest Good Moring
statement-1 How are you!!!
statement-2
statement-3
3) if-elif-else:
If condition is true then statements will be executed. if condition1:
Action-1
Eg: elif condition2:
Action-2
1) name=input("Enter Name:") elif condition3:
2) if name=="durga" : Action-3
3) print("Hello Durga Good Morning") elif condition4:
4) print("How are you!!!") Action-4
...
D:\Python_classes>py test.py else:
Enter Name:durga Default Action
Hello Durga Good Morning
How are you!!! Based condition the corresponding action will be executed.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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:") Q) Write a Program to find Biggest of given 3 Numbers from the
2) if brand=="RC" :
3) print("It is childrens brand") Commad Prompt?
4) elif brand=="KF":
5) print("It is not that much kick") 1) n1=int(input("Enter First Number:"))
6) elif brand=="FO": 2) n2=int(input("Enter Second Number:"))
7) print("Buy one get Free One") 3) n3=int(input("Enter Third Number:"))
8) else : 4) if n1>n2 and n1>n3:
9) print("Other Brands are not recommended") 5) print("Biggest Number is:",n1)
6) elif n2>n3:
D:\Python_classes>py test.py 7) print("Biggest Number is:",n2)
Enter Your Favourite Brand:RC 8) else :
It is childrens brand 9) print("Biggest Number is:",n3)

D:\Python_classes>py test.py D:\Python_classes>py test.py


Enter Your Favourite Brand:KF Enter First Number:10
It is not that much kick Enter Second Number:20
Enter Third Number:30
D:\Python_classes>py test.py Biggest Number is: 30
Enter Your Favourite Brand: KALYANI
Other Brands are not recommended D:\Python_classes>py test.py
Enter First Number:10
Enter Second Number:30
Note: Enter Third Number:20
1) else part is always optional. Hence the following are various possible syntaxes. Biggest Number is: 30
1) If
2) if – else Q) Write a program to find smallest of given 2 numbers?
3) if-elif-else Q) Write a program to find smallest of given 3 numbers?
4) if-elif Q) Write a program to check whether the given number is even or odd?
2) There is no switch statement in Python
Q) Write a Program to Check whether the given Number is in
Q) Write a Program to find Biggest of given 2 Numbers from the
between 1 and 100?
Commad Prompt?
1) n=int(input("Enter Number:"))
1) n1=int(input("Enter First Number:")) 2) if n>=1 and n<=10 :
2) n2=int(input("Enter Second Number:")) 3) print("The number",n,"is in between 1 to 10")
3) if n1>n2: 4) else:
4) print("Biggest Number is:",n1) 5) print("The number",n,"is not in between 1 to 10")
5) else :
6) print("Biggest Number is:",n2)

D:\Python_classes>py test.py
Enter First Number:10
Enter Second Number:20
Biggest Number is: 20

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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 II. Iterative Statements
Board and Print is Value in English Word? ֍ If we want to execute a group of statements multiple times then we should go for
Iterative statements.
1) 0  ZERO ֍ Python supports 2 types of iterative statements.
2) 1  ONE 1) for loop
3) 2) while loop
4) n=int(input("Enter a digit from o to 9:"))
5) if n==0 :
6) print("ZERO") 1) for loop:
7) elif n==1: If we want to execute some action for every element present in some sequence
8) print("ONE") (it may be string or collection) then we should go for for loop.
9) elif n==2:
10) print("TWO") Syntax: for x in sequence:
11) elif n==3: Body
12) print("THREE")
13) elif n==4: Where sequence can be string or any collection.
14) print("FOUR") Body will be executed for every element present in the sequence.
15) elif n==5:
16) print("FIVE") Eg 1: To print characters present in the given string
17) elif n==6:
18) print("SIX") 1) s="Sunny Leone"
19) elif n==7: 2) for x in s :
20) print("SEVEN") 3) print(x)
21) elif n==8:
22) print("EIGHT") Output
23) elif n==9: S
24) print("NINE") u
25) else: n
26) print("PLEASE ENTER A DIGIT FROM 0 TO 9") n
y

L
e
o
n
e

Eg 2: To print characters present in string index wise:

1) s=input("Enter some String: ")


2) i=0
3) for x in s :
4) print("The character present at ",i,"index is :",x)
5) i=i+1

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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 D:\Python_classes>py test.py
Enter some String: Sunny Leone Enter List:[10,20,30,40]
The character present at 0 index is : S The Sum= 100
The character present at 1 index is : u
The character present at 2 index is : n D:\Python_classes>py test.py
The character present at 3 index is : n Enter List:[45,67]
The character present at 4 index is : y The Sum= 112
The character present at 5 index is :
The character present at 6 index is : L
The character present at 7 index is : e
2) while loop:
The character present at 8 index is : o If we want to execute a group of statements iteratively until some condition false,then
The character present at 9 index is : n we should go for while loop.
The character present at 10 index is : e
Syntax: while condition :
Eg 3: To print Hello 10 times body

1) for x in range(10) : Eg: To print numbers from 1 to 10 by using while loop


2) print("Hello")
1) x = 1
Eg 4: To display numbers from 0 to 10 2) while x <= 10:
3) print(x)
1) for x in range(11) : 4) x = x+1
2) print(x)
Eg: To display the sum of first n numbers
Eg 5: To display odd numbers from 0 to 20
1) n=int(input("Enter number:"))
1) for x in range(21) : 2) sum=0
2) if (x%2!=0): 3) i=1
3) print(x) 4) while i<=n:
5) sum=sum+i
Eg 6: To display numbers from 10 to 1 in descending order 6) i=i+1
7) print("The sum of first",n,"numbers is :",sum)
1) for x in range(10,0,-1) :
2) print(x) Eg: Write a program to prompt user to enter some name until entering Durga

Eg 7: To print sum of numbers presenst inside list 1) name=""


2) while name!="durga":
1) list = eval(input("Enter List:")) 3) name=input("Enter Name:")
2) sum=0; 4) print("Thanks for confirmation")
3) for x in list:
4) sum=sum+x;
5) print("The Sum=",sum)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
64  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Infinite Loops: Q) Write a Program to display *'s in Pyramid Style
(Also known as Equivalent Triangle)
1) i=0;
2) while True : *
3) i=i+1; ** 1) n = int(input("Enter number of rows:"))
4) print("Hello",i) *** 2) for i in range(1,n+1):
**** 3) print(" " * (n-i),end="")
Nested Loops: ***** 4) print("* "*i)
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) III. Transfer Statements
Output
D:\Python_classes>py test.py 1) break:
i= 0 j= 0 We can use break statement inside loops to break loop execution based on some
i= 0 j= 1 condition.
i= 0 j= 2
i= 0 j= 3 1) for i in range(10):
i= 1 j= 0 2) if i==7:
i= 1 j= 1 3) print("processing is enough..plz break")
i= 1 j= 2 4) break
i= 1 j= 3 5) print(i)
i= 2 j= 0
i= 2 j= 1 D:\Python_classes>py test.py
i= 2 j= 2 0
i= 2 j= 3 1
i= 3 j= 0 2
i= 3 j= 1 3
i= 3 j= 2 4
i= 3 j= 3 5
6
processing is enough..plz break
Q) Write a Program to dispaly *'s in Right Angled Triangled Form
Eg:
* 1) n = int(input("Enter number of rows:"))
** 2) for i in range(1,n+1): 1) cart=[10,20,600,60,70]
*** 3) for j in range(1,i+1): 2) for item in cart:
**** 4) print("*",end=" ")
Alternative Way 3) if item>500:
***** 5) print()
4) print("To place this order insurence must be required")
****** 1) n = int(input("Enter number of rows:")) 5) break
******* 2) for i in range(1,n+1): 6) print(item)
3) print("* " * i)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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 Eg 3:
10
20 1) numbers=[10,20,0,5,0,30]
To place this order insurence must be required 2) for n in numbers:
3) if n==0:
2) continue: 4) print("Hey how we can divide with zero..just skipping")
5) continue
We can use continue statement to skip current iteration and continue next iteration.
6) print("100/{} = {}".format(n,100/n))
Eg 1: To print odd numbers in the range 0 to 9
Output
100/10 = 10.0
1) for i in range(10):
100/20 = 5.0
2) if i%2==0:
Hey how we can divide with zero..just skipping
3) continue
100/5 = 20.0
4) print(i)
Hey how we can divide with zero..just skipping
100/30 = 3.3333333333333335
D:\Python_classes>py test.py
1
3 Loops with else Block:
5  Inside loop execution, if break statement not executed, then only else part will be
7 executed.
9
 else means loop without break.

Eg 2: 1) cart=[10,20,30,40,50]
2) for item in cart:
1) cart=[10,20,500,700,50,60] 3) if item>=500:
2) for item in cart: 4) print("We cannot process this order")
3) if item>=500: 5) break
4) print("We cannot process this item :",item) 6) print(item)
5) continue 7) else:
6) print(item) 8) print("Congrats ...all items processed successfully")

D:\Python_classes>py test.py
Output
10
10
20
20
We cannot process this item : 500
30
We cannot process this item : 700
40
50
50
60
Congrats ...all items processed successfully

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
68  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg: def m1():
SyntaxError: unexpected EOF while parsing
1) cart=[10,20,600,30,40,50]
2) for item in cart: def m1(): pass
3) if item>=500:
4)
5)
print("We cannot process this order")
break
Use Case of pass:
6) print(item)
Sometimes in the parent class we have to declare a function with empty body and child
7) else:
class responsible to provide proper implementation. Such type of empty body we can
8) print("Congrats ...all items processed successfully")
define by using pass keyword. (It is something like abstract method in Java)
Output Eg: def m1(): pass
D:\Python_classes>py test.py
1) for i in range(100):
10
2) if i%9==0:
20
3) print(i)
We cannot process this order
4) else:pass

Q) What is the difference between for loop and while loop D:\Python_classes>py test.py
in Python? 0
9
֍ We can use loops to repeat code execution
18
֍ Repeat code for every item in sequence  for loop
27
֍ Repeat code as long as condition is true  while loop 36
45
Q) How to exit from the loop? By using break statement 54
63
Q)How to skip some iterations inside loop? By using continue statement. 72
81
Q)When else part will be executed wrt loops? If loop executed without break 90
99
3) pass statement:
 pass is a keyword in Python. del Statement:
 In our programming syntactically if block is required which won't do anything then we  del is a keyword in Python.
can define that empty block with pass keyword.  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.
pass  We can delete variable by using del keyword.
|- It is an empty statement
|- It is null statement 1) x = 10
|- It won't do anything 2) print(x)
3) del x
Eg: if True:
SyntaxError: unexpected EOF while parsing
if True: pass  valid

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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)

NameError: name 'x' is not defined.

Note: We can delete variables which are pointing to immutable objects.But we cannot
delete the elements present inside immutable object.

1) s = "durga"
2) print(s)
3) del s  valid
4) del s[0]  TypeError: 'str' object doesn't support item deletion

STRING
Difference between del and None:
In the case del, the variable will be removed and we cannot access that variable(unbind
operation)

1) s = "durga"
2) del s

DATA TYPE
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 nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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 How to Access Characters of a String?
only. Hence we should aware complete information about String data type.
We can access characters of a string by using the following ways.
1) By using index
What is String? 2) By using slice operator
Any sequence of characters within either single quotes or double quotes is considered as a
String. 1) Accessing Characters By using Index:
 Python supports both +ve and -ve Index.
Syntax:  +ve Index means Left to Right (Forward Direction)
s = 'durga'  -ve Index means Right to Left (Backward Direction)
s = "durga"
Eg: s = 'durga'
Note: In most of other languges like C, C++, Java, a single character with in single quotes 1) >>> s='durga'
is treated as char data type value. But in Python we are not having char data type.Hence it 2) >>> s[0]
is treated as String only. 3) 'd'
4) >>> s[4]
Eg: 5) 'a'
>>> ch = 'a' 6) >>> s[-1]
>>> type(ch) 7) 'a'
<class 'str'> 8) >>> s[10]
9) IndexError: string index out of range
How to define multi-line String Literals?
We can define multi-line String literals by using triple single or double quotes. Note: If we are trying to access characters of a string with out of range index then we will
get error saying: IndexError
Eg:
>>> s = '''durga Q) Write a Program to Accept some String from the Keyboard and display its
software Characters by Index wise (both Positive and Negative Index)
solutions'''
test.py:
We can also use triple quotes to use single quotes or double quotes as symbol inside
String literal. 1) s=input("Enter Some String:")
2) i=0
1) s = 'This is ' single quote symbol'  Invalid 3) for x in s:
2) s = 'This is \' single quote symbol'  Valid 4) print("The character present at positive index {} and at nEgative index {} is {}".fo
3) s = "This is ' single quote symbol"  Valid rmat(i,i-len(s),x))
4) s = 'This is " double quotes symbol'  Valid 5) i=i+1
5) s = 'The "Python Notes" by 'durga' is very helpful'  Invalid
6) s = "The "Python Notes" by 'durga' is very helpful"  Invalid Output: D:\python_classes>py test.py
7) s = 'The \"Python Notes\" by \'durga\' is very helpful'  Valid Enter Some String:durga
8) s = '''The "Python Notes" by 'durga' is very helpful'''  Valid The character present at positive index 0 and at nEgative index -5 is d
The character present at positive index 1 and at nEgative index -4 is u
The character present at positive index 2 and at nEgative index -3 is r
The character present at positive index 3 and at nEgative index -2 is g
The character present at positive index 4 and at nEgative index -1 is a

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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: In Forward Direction:
 Syntax: s[bEginindex:endindex:step] default value for bEgin: 0
default value for end: length of string
 Begin Index: From where we have to consider slice (substring) default value for step: +1
 End Index: We have to terminate the slice (substring) at endindex-1
 Step: Incremented Value. In Backward Direction:
default value for bEgin: -1
Note: default value for end: -(length of string+1)
 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. Note: Either forward or backward direction, we can take both +ve and -ve values for
 The default value for step is 1. bEgin and end index.

1) >>> s="Learning Python is very very easy!!!"


2) >>> s[1:7:1] Slice Operator Case Study:
3) 'earnin' 1) S = 'abcdefghij'
4) >>> s[1:7] 2) s[1:6:2]  'bdf'
5) 'earnin' 3) s[::1]  'abcdefghij'
6) >>> s[1:7:2] 4) s[::-1]  'jihgfedcba'
7) 'eri' 5) s[3:7:-1]  ''
8) >>> s[:7] 6) s[7:4:-1]  'hgf'
9) 'Learnin' 7) s[0:10000:1]  'abcdefghij'
10) >>> s[7:] 8) s[-4:1:-1]  'gfedc'
11) 'g Python is very very easy!!!' 9) s[-4:1:-2]  'gec'
12) >>> s[::] 10) s[5:0:1]  ''
13) 'Learning Python is very very easy!!!' 11) s[9:0:0]  ValueError: slice step cannot be zero
14) >>> s[:] 12) s[0:-10:-1]  ''
15) 'Learning Python is very very easy!!!' 13) s[0:-11:-1]  'a'
16) >>> s[::-1] 14) s[0:0:1]  ''
17) '!!!ysae yrev yrev si nohtyP gninraeL' 15) s[0:-9:-2]  ''
16) s[-5:-9:-2]  'fd'
17) s[10:-1:-1]  ''
Behaviour of Slice Operator: 18) s[10000:2:-1]  'jihgfed'
1) s[bEgin:end:step]
2) Step value can be either +ve or –ve Note: Slice operator never raises IndexError
3) If +ve then it should be forward direction(left to right) and we have to consider bEgin
to end-1
4) If -ve then it should be backward direction (right to left) and we have to consider bEgin Mathematical Operators for String:
to end+1.
We can apply the following mathematical operators for Strings.
***Note: 1) + operator for concatenation
 In the backward direction if end value is -1 then result is always empty. 2) * operator for repetition
 In the forward direction if end value is 0 then result is always empty.
 print("durga"+"soft")  durgasoft
 print("durga"*2)  durgadurga

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
76  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Note: Checking Membership:
1) To use + operator for Strings, compulsory both arguments should be str type.
We can check whether the character or string is the member of another string or not by
2) To use * operator for Strings, compulsory one argument should be str and other
using in and not in operators
argument should be int.
s = 'durga'
len() in-built Function: print('d' in s)  True
We can use len() function to find the number of characters present in the string. print('z' in s)  False
Eg:
s = 'durga' 1) s = input("Enter main string:")
print(len(s))  5 2) subs = input("Enter sub string:")
3) if subs in s:
4) print(subs,"is found in main string")
Q) Write a Program to access each Character of String in 5) else:
Forward and Backward Direction by using while Loop? 6) print(subs,"is not found in main string")

1) s = "Learning Python is very easy !!!" Output:


2) n = len(s) D:\python_classes>py test.py
3) i = 0 Enter main string:durgasoftwaresolutions
4) print("Forward direction") Enter sub string:durga
5) while i<n: durga is found in main string
6) print(s[i],end=' ')
7) i +=1 D:\python_classes>py test.py
8) print("Backward direction") Enter main string:durgasoftwaresolutions
9) i = -1 Enter sub string:python
10) while i >= -n: python is not found in main string
11) print(s[i],end=' ')
12) i = i-1
Comparison of Strings:
Alternative ways:  We can use comparison operators (<, <=, >, >=) and equality operators (==, !=) for
strings.
1) s = "Learning Python is very easy !!!"  Comparison will be performed based on alphabetical order.
2) print("Forward direction")
3) for i in s: 1) s1=input("Enter first string:")
4) print(i,end=' ') 2) s2=input("Enter Second string:")
5) print("Forward direction") 3) if s1==s2:
6) for i in s[::]: 4) print("Both strings are equal")
7) print(i,end=' ') 5) elif s1<s2:
8) 6) print("First String is less than Second String")
9) print("Backward direction") 7) else:
10) for i in s[::-1]: 8) print("First String is greater than Second String")
11) print(i,end=' ')
Output:
D:\python_classes>py test.py
Enter first string:durga

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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
find():
D:\python_classes>py test.py s.find(substring)
Enter first string:durga Returns index of first occurrence of the given substring. If it is not available then we will
Enter Second string:ravi get -1.
First String is less than Second String
1) s="Learning Python is very easy"
D:\python_classes>py test.py 2) print(s.find("Python")) #9
Enter first string:durga 3) print(s.find("Java")) # -1
Enter Second string:anil 4) print(s.find("r"))#3
First String is greater than Second String 5) print(s.rfind("r"))#21

Note: By default find() method can search total string. We can also specify the
Removing Spaces from the String: boundaries to search.

We can use the following 3 methods s.find(substring,bEgin,end)


It will always search from bEgin index to end-1 index.
1) rstrip()  To remove spaces at right hand side
2) lstrip() To remove spaces at left hand side 1) s="durgaravipavanshiva"
3) strip()  To remove spaces both sides 2) print(s.find('a'))#4
3) print(s.find('a',7,15))#10
1) city=input("Enter your city Name:")
4) print(s.find('z',7,15))#-1
2) scity=city.strip()
3) if scity=='Hyderabad':
4) print("Hello Hyderbadi..Adab") index():
5) elif scity=='Chennai': index() method is exactly same as find() method except that if the specified substring is
6) print("Hello Madrasi...Vanakkam") not available then we will get ValueError.
7) elif scity=="Bangalore":
8) print("Hello Kannadiga...Shubhodaya") 1) s=input("Enter main string:")
9) else: 2) subs=input("Enter sub string:")
10) print("your entered city is invalid") 3) try:
4) n=s.index(subs)
5) except ValueError:
Finding Substrings: 6) print("substring not found")
7) else:
We can use the following 4 methods
8) print("substring found")

For forward direction: Output:


1) find() D:\python_classes>py test.py
2) index() Enter main string:learning python is very easy
Enter sub string:python
substring found
For backward direction:
1) rfind()
2) rindex()
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
79  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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 1) s="abcabcabcabcadda"
Enter main string:learning python is very easy 2) print(s.count('a'))
Enter sub string:java 3) print(s.count('ab'))
substring not found 4) print(s.count('a',3,7))

Q) Program to display all Positions of Substring in a given Output:


6
Main String 4
2
1) s=input("Enter main string:")
2) subs=input("Enter sub string:")
3) flag=False Replacing a String with another String:
4) pos=-1 s.replace(oldstring, newstring)
5) n=len(s) inside s, every occurrence of old String will be replaced with new String.
6) while True:
7) pos=s.find(subs,pos+1,n) Eg 1:
8) if pos==-1: s = "Learning Python is very difficult"
9) break s1 = s.replace("difficult","easy")
10) print("Found at position",pos) print(s1)
11) flag=True
12) if flag==False: Output: Learning Python is very easy
13) print("Not Found")
Eg 2: All occurrences will be replaced
Output: s = "ababababababab"
D:\python_classes>py test.py s1 = s.replace("a","b")
Enter main string:abbababababacdefg print(s1)
Enter sub string:a
Found at position 0
Output: bbbbbbbbbbbbbb
Found at position 3
Found at position 5
Found at position 7 Q) String Objects are Immutable then how we can change the
Found at position 9 Content by using replace() Method
Found at position 11  Once we creates string object, we cannot change the content.This non changeable
behaviour is nothing but immutability. If we are trying to change the content by using
D:\python_classes>py test.py any method, then with those changes a new object will be created and changes won't
Enter main string:abbababababacdefg be happend in existing object.
Enter sub string:bb  Hence with replace() method also a new object got created but existing object won't
Found at position 1 be changed.

Counting substring in the given String: Eg:


We can find the number of occurrences of substring present in the given string by using s = "abab"
count() method. s1 = s.replace("a","b")
1) s.count(substring)  It will search through out the string. print(s,"is available at :",id(s))
2) s.count(substring, bEgin, end)  It will search from bEgin index to end-1 index. print(s1,"is available at :",id(s1))

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
82  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output: Eg 2:
abab is available at : 4568672 l = ['hyderabad', 'singapore', 'london', 'dubai']
bbbb is available at : 4568704 s = ':'.join(l)
print(s)
In the above example, original object is available and we can see new object which was
created because of replace() method. Output: hyderabad:singapore:london:dubai

Splitting of Strings:
 We can split the given string according to specified seperator by using split() method. Changing Case of a String:
 l = s.split(seperator) We can change case of a string by using the following 4 methods.
 The default seperator is space. The return type of split() method is List.
1) upper()  To convert all characters to upper case
1) s="durga software solutions" 2) lower()  To convert all characters to lower case
2) l=s.split() 3) swapcase()  Converts all lower case characters to upper case and all upper case
3) for x in l: characters to lower case
4) print(x) 4) title()  To convert all character to title case. i.e first character in every word should
be upper case and all remaining characters should be in lower case.
Output: 5) capitalize()  Only first character will be converted to upper case and all remaining
durga characters can be converted to lower case
software
solutions 1) s = 'learning Python is very Easy'
2) print(s.upper())
1) s="22-02-2018" 3) print(s.lower())
2) l=s.split('-') 4) print(s.swapcase())
3) for x in l: 5) print(s.title())
4) print(x) 6) print(s.capitalize())

Output: Output:
22 LEARNING PYTHON IS VERY EASY
02 learning python is very easy
2018 LEARNING pYTHON IS VERY eASY
Learning Python Is Very Easy
Learning python is very easy
Joining of Strings:
We can join a Group of Strings (List OR Tuple) wrt the given Seperator.
s = seperator.join(group of strings) Checking Starting and Ending Part of the String:
Python contains the following methods for this purpose
Eg 1: 1) s.startswith(substring)
t = ('sunny', 'bunny', 'chinny') 2) s.endswith(substring)
s = '-'.join(t)
print(s) 1) s = 'learning Python is very easy'
2) print(s.startswith('learning'))
Output: sunny-bunny-chinny 3) print(s.endswith('learning'))
4) print(s.endswith('easy'))

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
84  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output: 13) print("It is space character")
True 14) else:
False 15) print("Non Space Special Character")
True
D:\python_classes>py test.py
Enter any character:7
To Check Type of Characters Present in a String: Alpha Numeric Character
Python contains the following methods for this purpose. it is a digit

1) isalnum(): Returns True if all characters are alphanumeric( a to z , A to Z ,0 to9 ) D:\python_classes>py test.py
2) isalpha(): Returns True if all characters are only alphabet symbols(a to z,A to Z) Enter any character:a
3) isdigit(): Returns True if all characters are digits only( 0 to 9) Alpha Numeric Character
4) islower(): Returns True if all characters are lower case alphabet symbols Alphabet character
5) isupper(): Returns True if all characters are upper case aplhabet symbols Lower case alphabet character
6) istitle(): Returns True if string is in title case
7) isspace(): Returns True if string contains only spaces D:\python_classes>py test.py
Enter any character:$
Eg: Non Space Special Character
1) print('Durga786'.isalnum())  True
2) print('durga786'.isalpha())  False D:\python_classes>py test.py
3) print('durga'.isalpha())  True Enter any character:A
4) print('durga'.isdigit())  False Alpha Numeric Character
5) print('786786'.isdigit())  True Alphabet character
6) print('abc'.islower())  True Upper case alphabet character
7) print('Abc'.islower())  False
8) print('abc123'.islower())  True
9) print('ABC'.isupper())  True
Formatting the Strings:
10) print('Learning python is Easy'.istitle())  False We can format the strings with variable values by using replacement operator {} and
11) print('Learning Python Is Easy'.istitle())  True format() method.
12) print(' '.isspace())  True
1) name = 'durga'
2) salary = 10000
Demo Program:
3) age = 48
4) print("{} 's salary is {} and his age is {}".format(name,salary,age))
1) s=input("Enter any character:")
5) print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
2) if s.isalnum():
6) print("{x} 's salary is {y} and his age is {z}".format(z=age,y=salary,x=name))
3) print("Alpha Numeric Character")
4) if s.isalpha():
5) print("Alphabet character") Output:
durga 's salary is 10000 and his age is 48
6) if s.islower():
durga 's salary is 10000 and his age is 48
7) print("Lower case alphabet character")
durga 's salary is 10000 and his age is 48
8) else:
9) print("Upper case alphabet character")
10) else:
11) print("it is a digit")
12) elif s.isspace():

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
86  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Important Programs regarding String Concept Q3) Program to Reverse Internal Content of each Word
Input: Durga Software Solutions
Output: agruD erawtfoS snoituloS
Q1) Write a Program to Reverse the given String
Input: durga 1) s=input("Enter Some String:")
Output: agrud 2) l=s.split()
3) l1=[]
1st Way: 4)
5)
i=0
while i<len(l):
6) l1.append(l[i][::-1])
1) s = input("Enter Some String:")
7) i=i+1
2) print(s[::-1])
8) output=' '.join(l1)
9) print(output)
2nd Way:
1) s = input("Enter Some String:")
Q4) Write a Program to Print Characters at Odd Position and
2) print(''.join(reversed(s))) Even Position for the given String?
3rd Way: 1st Way:
s = input("Enter Some String:")
1) s = input("Enter Some String:") print("Characters at Even Position:",s[0::2])
2) i=len(s)-1 print("Characters at Odd Position:",s[1::2])
3) target=''
4)
5)
while i>=0:
target=target+s[i]
2nd Way:
6) i=i-1
1) s=input("Enter Some String:")
7) print(target)
2) i=0
3) print("Characters at Even Position:")
Q2) Program to Reverse Order of Words 4) while i< len(s):
Input: Learning Python is very Easy 5) print(s[i],end=',')
Output: Easy Very is Python Learning 6) i=i+2
7) print()
1) s=input("Enter Some String:") 8) print("Characters at Odd Position:")
2) l=s.split() 9) i=1
3) l1=[] 10) while i< len(s):
4) i=len(l)-1 11) print(s[i],end=',')
5) while i>=0: 12) i=i+2
6) l1.append(l[i])
7) i=i-1
8) output=' '.join(l1)
9) print(output)

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


easy!!! very is Python Learning
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
87  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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 Q7) Write a Program for the following Requirement
String by taking Characters alternatively Input: a4b3c2
Output: aaaabbbcc
Input: s1 = "ravi"
s2 = "reja"
1) s=input("Enter Some String:")
Output: rtaevjia
2) output=''
3) for x in s:
1) s1=input("Enter First String:")
4) if x.isalpha():
2) s2=input("Enter Second String:")
5) output=output+x
3) output=''
6) previous=x
4) i,j=0,0
7) else:
5) while i<len(s1) or j<len(s2):
8) output=output+previous*(int(x)-1)
6) if i<len(s1):
9) print(output)
7) output=output+s1[i]
8) i+=1
9) if j<len(s2):
Note: chr(unicode)  The corresponding character
10) output=output+s2[j] ord(character)  The corresponding unicode value
11) j+=1
12) print(output) Q8) Write a Program to perform the following Activity
Input: a4k3b2
Output: Outpt: aeknbd
Enter First String:durga
Enter Second String:ravisoft 1) s=input("Enter Some String:")
druarvgiasoft 2) output=''
3) for x in s:
4) if x.isalpha():
Q6) Write a Program to Sort the Characters of the String and 5) output=output+x
First Alphabet Symbols followed by Numeric Values 6) previous=x
Input: B4A1D3 7) else:
Output: ABD134 8) output=output+chr(ord(previous)+int(x))
9) print(output)
1) s=input("Enter Some String:")
2) s1=s2=output='' Q9) Write a Program to Remove Duplicate Characters from
3) for x in s:
4) if x.isalpha(): the given Input String?
5) s1=s1+x Input: ABCDABBCDABBBCCCDDEEEF
6) else: Output: ABCDEF
7) s2=s2+x
8) for x in sorted(s1): 1) s = input("Enter Some String:")
9) output=output+x 2) l=[]
10) for x in sorted(s2): 3) for x in s:
11) output=output+x 4) if x not in l:
12) print(output) 5) l.append(x)
6) output=''.join(l)
7) print(output)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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 Formatting the Strings:
each Character present in the given String? ֍ We can format the strings with variable values by using replacement operator {} and
Input: ABCABCABBCDE format() method.
Output: A-3,B-4,C-3,D-1,E-1 ֍ The main objective of format() method to format string into meaningful output form.

1) s=input("Enter the Some String:") Case- 1: Basic formatting for default, positional and keyword arguments
2) d={}
3) for x in s: 1) name = 'durga'
4) if x in d.keys(): 2) salary = 10000
5) d[x]=d[x]+1 3) age = 48
6) else: 4) print("{} 's salary is {} and his age is {}".format(name,salary,age))
7) d[x]=1 5) print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
8) for k,v in d.items(): 6) print("{x} 's salary is {y} and his age is {z}".format(z=age,y=salary,x=name))
9) print("{} = {} Times".format(k,v))
Output:
Q11) Write a Program to perform the following Task? durga 's salary is 10000 and his age is 48
durga 's salary is 10000 and his age is 48
Input: 'one two three four five six seven'
durga 's salary is 10000 and his age is 48
Output: 'one owt three ruof five xis seven'

1) s = input('Enter Some String:') Case-2: Formatting Numbers


2) l = s.split()
3) l1 = [] d  Decimal IntEger
4) i = 0 f  Fixed point number(float).The default precision is 6
5) while i<len(l): b  Binary format
6) if i%2==0: o  Octal Format
7) l1.append(l[i]) x  Hexa Decimal Format (Lower case)
8) else: X  Hexa Decimal Format (Upper case)
9) l1.append(l[i][::-1])
10) i=i+1 Eg-1:
11) output=' '.join(l1)
12) print('Original String:',s) 1) print("The intEger number is: {}".format(123))
13) print('output String:',output) 2) print("The intEger number is: {:d}".format(123))
3) print("The intEger number is: {:5d}".format(123))
Output: 4) print("The intEger number is: {:05d}".format(123))
D:\durgaclasses>py test.py
Enter Some String:one two three four five six seven Output:
Original String: one two three four five six seven The intEger number is: 123
output String: one owt three ruof five xis seven The intEger number is: 123
The intEger number is: 123
The intEger number is: 00123

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
92  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg-2: Note:
1) {:5d} It takes an intEger argument and assigns a minimum width of 5.
1) print("The float number is: {}".format(123.4567)) 2) {:8.3f} It takes a float argument and assigns a minimum width of 8 including "." and
2) print("The float number is: {:f}".format(123.4567)) after decimal point excatly 3 digits are allowed with round operation if required
3) print("The float number is: {:8.3f}".format(123.4567)) 3) {:05d} The blank places can be filled with 0. In this place only 0 allowed.
4) print("The float number is: {:08.3f}".format(123.4567))
5) print("The float number is: {:08.3f}".format(123.45)) Case-3: Number formatting for signed numbers
6) print("The float number is: {:08.3f}".format(786786123.45)) ֍ While displaying positive numbers,if we want to include + then we have to write
{:+d} and {:+f}
Output: ֍ Using plus for -ve numbers there is no use and for -ve numbers - sign will come
The float number is: 123.4567 automatically.
The float number is: 123.456700
The float number is: 123.457 1) print("int value with sign:{:+d}".format(123))
The float number is: 0123.457 2) print("int value with sign:{:+d}".format(-123))
The float number is: 0123.450 3) print("float value with sign:{:+f}".format(123.456))
The float number is: 786786123.450 4) print("float value with sign:{:+f}".format(-123.456))

Note: Output:
֍ {:08.3f} int value with sign:+123
֍ Total positions should be minimum 8. int value with sign:-123
֍ After decimal point exactly 3 digits are allowed.If it is less then 0s will be placed in the float value with sign:+123.456000
last positions float value with sign:-123.456000
֍ 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. Case-4: Number formatting with alignment
֍ The extra digits we can take only 0
֍ <, >, ^ and = are used for alignment
Note: For numbers default alignment is Right Alignment (>) ֍ <  Left Alignment to the remaining space
֍ ^  Center alignment to the remaining space
Eg-3: Print Decimal value in binary, octal and hexadecimal form ֍ >  Right alignment to the remaining space
֍ =  Forces the signed(+) (-) to the left most position
1) print("Binary Form:{0:b}".format(153))
2) print("Octal Form:{0:o}".format(153)) Note: Default Alignment for numbers is Right Alignment.
3) print("Hexa decimal Form:{0:x}".format(154))
4) print("Hexa decimal Form:{0:X}".format(154)) Ex:
Output: 1) print("{:5d}".format(12))
Binary Form:10011001 2) print("{:<5d}".format(12))
Octal Form:231 3) print("{:<05d}".format(12))
Hexa decimal Form:9a 4) print("{:>5d}".format(12))
Hexa decimal Form:9A 5) print("{:>05d}".format(12))
6) print("{:^5d}".format(12))
Note: We can represent only int values in binary, octal and hexadecimal and it is not 7) print("{:=5d}".format(-12))
possible for float values. 8) print("{:^10.3f}".format(12.23456))
9) print("{:=8.3f}".format(-12.23456))

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
94  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output: dur
12 *dur*
12
12000 Case-7: Formatting dictionary members using format()
12
00012 1) person={'age':48,'name':'durga'}
12 2) print("{p[name]}'s age is: {p[age]}".format(p=person))
-12
12.235 Output:
- 12.235 durga's age is: 48
Note: p is alias name of dictionary
Case-5: String formatting with format() person dictionary we are passing as keyword argument
Similar to numbers, we can format String values also with format() method.
s.format(string) More convinient way is to use **person

1) print("{:5d}".format(12)) 1) person={'age':48,'name':'durga'}
2) print("{:5}".format("rat")) 2) print("{name}'s age is: {age}".format(**person))
3) print("{:>5}".format("rat"))
4) print("{:<5}".format("rat")) Output: durga's age is: 48
5) print("{:^5}".format("rat"))
6) print("{:*^5}".format("rat")) #Instead of * we can use any character(like +,$,a etc) Case-8: Formatting class members using format()

Output: 1) class Person:


12 2) age=48
rat 3) name="durga"
rat 4) print("{p.name}'s age is :{p.age}".format(p=Person()))
rat
rat Output: durga's age is :48
*rat*
1) class Person:
Note: For numbers default alignment is right where as for strings default alignment is left 2) def __init__(self,name,age):
3) self.name=name
Case-6: Truncating Strings with format() method 4) self.age=age
5) print("{p.name}'s age is :{p.age}".format(p=Person('durga',48)))
1) print("{:.3}".format("durgasoftware")) 6) print("{p.name}'s age is :{p.age}".format(p=Person('Ravi',50)))
2) print("{:5.3}".format("durgasoftware"))
3) print("{:>5.3}".format("durgasoftware")) Note: Here Person object is passed as keyword argument. We can access by using its
4) print("{:^5.3}".format("durgasoftware")) reference variable in the template string
5) print("{:*^5.3}".format("durgasoftware"))
Case-9: Dynamic Formatting using format()
Output:
dur 1) string="{:{fill}{align}{width}}"
dur 2) print(string.format('cat',fill='*',align='^',width=5))
dur 3) print(string.format('cat',fill='*',align='^',width=6))

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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

Case-10: Dynamic Float format template

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))

LIST
Output:
123.24
123.24

Case-11: Formatting Date values

1) import datetime
2) #datetime formatting
3) date=datetime.datetime.now()
4) print("It's now:{:%d/%m/%Y %H:%M:%S}".format(date))

DATA STRUCTURE
Output: It's now:09/03/2018 12:36:26

Case-12: Formatting complex numbers

1) complexNumber=1+2j
2) print("Real Part:{0.real} and Imaginary Part:{0.imag}".format(complexNumber))

Output: Real Part: 1.0 and Imaginary Part: 2.0

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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 4) With list() Function:
order preserved and duplicates are allowed, then we should go for List.
֍ insertion order preserved. 1) l=list(range(0,10,2))
֍ duplicate objects are allowed. 2) print(l)
֍ heterogeneous objects are allowed. 3) print(type(l))
֍ List is dynamic because based on our requirement we can increase the size and
decrease the size. D:\Python_classes>py test.py
֍ In List the elements will be placed within square brackets and with comma seperator. [0, 2, 4, 6, 8]
֍ We can differentiate duplicate elements by using index and we can preserve insertion <class 'list'>
order by using index. Hence index will play very important role.
֍ Python supports both positive and negative indexes. +ve index means from left to Eg:
right where as negative index means right to left.
1) s="durga"
[10,"A","B",20, 30, 10]
2) l=list(s)
-6 -5 -4 -3 -2 -1 3) print(l)
10 A B 20 30 10
D:\Python_classes>py test.py
0 1 2 3 4 5
['d', 'u', 'r', 'g', 'a']
֍ List objects are mutable.i.e we can change the content.
5) With split() Function:
Creation of List Objects:
1) s="Learning Python is very very easy !!!"
1) We can create empty list object as follows... 2) l=s.split()
3) print(l)
1) list=[] 4) print(type(l))
2) print(list)
3) print(type(list)) D:\Python_classes>py test.py
4) ['Learning', 'Python', 'is', 'very', 'very', 'easy', '!!!']
5) [] <class 'list'>
6) <class 'list'>
Note: Sometimes we can take list inside another list, such type of lists are called nested
2) If we know elements already then we can create list as follows list = [10, 20, 30, 40] lists.
[10, 20, [30, 40]]
3) With Dynamic Input:
Accessing Elements of List:
1) list=eval(input("Enter List:")) We can access elements of the list either by using index or by using slice operator(:)
2) print(list)
3) print(type(list))
1) By using Index:
D:\Python_classes>py test.py ֍ List follows zero based index. ie index of first element is zero.
Enter List:[10,20,30,40] ֍ List supports both +ve and -ve indexes.
[10, 20, 30, 40] ֍ +ve index meant for Left to Right
<class 'list'> ֍ -ve index meant for Right to Left
֍ list = [10, 20, 30, 40]

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
100  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
-4 -3 -2 -1 List vs Mutability:
10 20 30 40 Once we creates a List object, we can modify its content. Hence List objects are mutable.
list
0 1 2 3
1) n=[10,20,30,40]
2) print(n)
3) n[1]=777
֍ print(list[0])  10 4) print(n)
֍ print(list[-1])  40
֍ print(list[10])  IndexError: list index out of range D:\Python_classes>py test.py
[10, 20, 30, 40]
2) By using Slice Operator: [10, 777, 30, 40]

Syntax: list2 = list1[start:stop:step] Traversing the Elements of List:


The sequential access of each element in the list is called traversal.
Start  It indicates the Index where slice has to Start
Default Value is 0
1) By using while Loop:
Stop  It indicates the Index where slice has to End
Default Value is max allowed Index of List ie Length of the List 1) n = [0,1,2,3,4,5,6,7,8,9,10]
2) i = 0
Step  increment value 3) while I < len(n):
Default Value is 1 4) print(n[i])
5) i=i+1
1) n=[1,2,3,4,5,6,7,8,9,10]
2) print(n[2:7:2]) D:\Python_classes>py test.py
3) print(n[4::2]) 0
4) print(n[3:7]) 1
5) print(n[8:2:-2]) 2
6) print(n[4:100]) 3
4
Output 5
D:\Python_classes>py test.py 6
[3, 5, 7] 7
[5, 7, 9] 8
[4, 5, 6, 7] 9
[9, 7, 5] 10
[5, 6, 7, 8, 9, 10]
2) By using for Loop:
1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) for n1 in n:
3) print(n1)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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 Important Functions of List:
1
2
3
I. To get Information about List:
4
5 1) len():
6 Returns the number of elements present in the list
7 Eg: n = [10, 20, 30, 40]
8 print(len(n)  4
9
10
2) count():
It returns the number of occurrences of specified item in the list
3) To display only Even Numbers:
1) n=[1,2,2,2,2,3,3]
1) n=[0,1,2,3,4,5,6,7,8,9,10] 2) print(n.count(1))
2) for n1 in n: 3) print(n.count(2))
3) if n1%2==0: 4) print(n.count(3))
4) print(n1) 5) print(n.count(4))

D:\Python_classes>py test.py D:\Python_classes>py test.py


0 1
2 4
4 2
6 0
8
10 3) index():
Returns the index of first occurrence of the specified item.
4) To display Elements by Index wise:
1) n = [1, 2, 2, 2, 2, 3, 3]
1) l = ["A","B","C"] 2) print(n.index(1))  0
2) x = len(l) 3) print(n.index(2))  1
3) for i in range(x): 4) print(n.index(3))  5
4) print(l[i],"is available at positive index: ",i,"and at negative index: ",i-x) 5) print(n.index(4))  ValueError: 4 is not in list

D:\Python_classes>py test.py Note: If the specified element not present in the list then we will get ValueError.Hence
A is available at positive index: 0 and at negative index: -3 before index() method we have to check whether item present in the list or not by using in
B is available at positive index: 1 and at negative index: -2 operator.
C is available at positive index: 2 and at negative index: -1 print( 4 in n)  False

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
104  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
II. Manipulating Elements of List: position. If the specified index is smaller than min index then element will be inserted at
first position.
1) append() Function:
We can use append() function to add item at the end of the list. Differences between append() and insert()
1) list=[] append() insert()
2) list.append("A") In List when we add any element it will In List we can insert any element in
3) list.append("B") come in last i.e. it will be last element. particular index number
4) list.append("C")
5) print(list) 3) extend() Function:
To add all items of one list to another list
D:\Python_classes>py test.py
l1.extend(l2)
['A', 'B', 'C']
all items present in l2 will be added to l1
Eg: To add all elements to list upto 100 which are divisible by 10 1) order1=["Chicken","Mutton","Fish"]
2) order2=["RC","KF","FO"]
1) list=[] 3) order1.extend(order2)
2) for i in range(101): 4) print(order1)
3) if i%10==0:
4) list.append(i) D:\Python_classes>py test.py
5) print(list) ['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']

D:\Python_classes>py test.py 1) order = ["Chicken","Mutton","Fish"]


[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] 2) order.extend("Mushroom")
3) print(order)
2) insert() Function:
To insert item at specified index position D:\Python_classes>py test.py
['Chicken', 'Mutton', 'Fish', 'M', 'u', 's', 'h', 'r', 'o', 'o', 'm']
1) n=[1,2,3,4,5]
2) n.insert(1,888) 4) remove() Function:
3) print(n) 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.
D:\Python_classes>py test.py
[1, 888, 2, 3, 4, 5] 1) n=[10,20,10,30]
2) n.remove(10)
1) n=[1,2,3,4,5] 3) print(n)
2) n.insert(10,777)
3) n.insert(-10,999) D:\Python_classes>py test.py
4) print(n) [20, 10, 30]

D:\Python_classes>py test.py If the specified item not present in list then we will get ValueError
[999, 1, 2, 3, 4, 5, 777]

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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] Differences between remove() and pop()
2) n.remove(40)
3) print(n) remove() pop()
1) We can use to remove special element 1) We can use to remove last element
ValueError: list.remove(x): x not in list from the List. from the List.
2) It can’t return any value. 2) It returned removed element.
Note: Hence before using remove() method first we have to check specified element 3) If special element not available then we 3) If List is empty then we get Error.
present in the list or not by using in operator. get VALUE ERROR.

5) pop() Function: Note: List Objects are dynamic. i.e based on our requirement we can increase and
 It removes and returns the last element of the list. decrease the size.
 This is only function which manipulates list and returns some element.
append(), insert(), extend()  for increasing the size/growable nature
1) n=[10,20,30,40] remove(), pop()  for decreasing the size /shrinking nature
2) print(n.pop())
3) print(n.pop())
4) print(n) III) Ordering Elements of List:
D:\Python_classes>py test.py
40 1) reverse():
30
We can use to reverse() order of elements of list.
[10, 20]
1) n=[10,20,30,40]
If the list is empty then pop() function raises IndexError 2) n.reverse()
3) print(n)
1) n = []
2) print(n.pop())  IndexError: pop from empty list D:\Python_classes>py test.py
[40, 30, 20, 10]
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 2) sort():
by using list,which follows LIFO(Last In First Out) order. 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.
In general we can use pop() function to remove last element of the list. But we can use to
remove elements based on index.  For numbers  Default Natural sorting Order is Ascending Order
 For Strings  Default Natural sorting order is Alphabetical Order
n.pop(index)  To remove and return element present at specified index.
n.pop()  To remove and return last element of the list 1) n = [20,5,15,10,0]
2) n.sort()
1) n = [10,20,30,40,50,60] 3) print(n)  [0,5,10,15,20]
2) print(n.pop())  60 4)
3) print(n.pop(1))  20 5) s = ["Dog","Banana","Cat","Apple"]
4) print(n.pop(10))  IndexError: pop index out of range 6) s.sort()
7) print(s)  ['Apple','Banana','Cat','Dog']

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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. 4) print(x)  [10,777,30,40]
Otherwise we will get TypeError
To overcome this problem we should go for cloning.
1) n=[20,10,"A","B"] The process of creating exactly duplicate independent object is called cloning.
2) n.sort()
3) print(n) We can implement cloning by using slice operator or by using copy() function.

TypeError: '<' not supported between instances of 'str' and 'int'


1) By using Slice Operator:
Note: In Python 2 if List contains both numbers and Strings then sort() function first sort 1) x = [10,20,30,40]
numbers followed by strings 2) y = x[:]
3) y[1] = 777
1) n=[20,"B",10,"A"] 4) print(x)  [10, 20, 30, 40]
2) n.sort() 5) print(y)  [10, 777, 30, 40]
3) print(n)# [10,20,'A','B']

But in Python 3 it is invalid. 10 20 30 40


x
10 20 30 40
To Sort in Reverse of Default Natural Sorting Order: 777
We can sort according to reverse of default natural sorting order by using reverse=True y
argument.
2) By using copy() Function:
1) n = [40,10,30,20]
2) n.sort() 1) x = [10,20,30,40]
3) print(n)  [10,20,30,40] 2) y = x.copy()
4) n.sort(reverse = True) 3) y[1] = 777
5) print(n)  [40,30,20,10] 4) print(x)  [10, 20, 30, 40]
6) n.sort(reverse = False) 5) print(y)  [10, 777, 30, 40]
7) print(n)  [10,20,30,40]
10 20 30 40
Aliasing and Cloning of List Objects: x
The process of giving another reference variable to the existing list is called aliasing.
10 20 30 40
777
1) x=[10,20,30,40]
10 20 30 40 y
2) y=x
x
3) print(id(x)) y
4) print(id(y))
Q) Difference between = Operator and copy() Function
The problem in this approach is by using one reference variable if we are changing ֍ = Operator meant for aliasing
content, then those changes will be reflected to the other reference variable. ֍ copy() Function meant for cloning

1) x = [10,20,30,40]
10 20 30 40
2) y = x
x 777
3) y[1] = 777
y
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
110  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) x = [50, 20, 30]
Using Mathematical Operators for List Objects: 2) y = [40, 50, 60, 100, 200]
We can use + and * operators for List objects. 3) print(x>y)  True
4) print(x>=y)  True
1) Concatenation Operator (+): 5) print(x<y)  False
We can use + to concatenate 2 lists into a single list 6) print(x<=y)  False

1) a = [10, 20, 30] Eg:


2) b = [40, 50, 60]
3) c = a+b 1) x = ["Dog", "Cat", "Rat"]
4) print(c)  [10, 20, 30, 40, 50, 60] 2) y=["Rat", "Cat", "Dog"]
3) print(x>y)  False
4) print(x>=y)  False
Note: To use + operator compulsory both arguments should be list objects, otherwise we
5) print(x<y)  True
will get TypeError.
6) print(x<=y)  True

Eg:
c = a+40  TypeError: can only concatenate list (not "int") to list. Membership Operators:
c = a+[40]  Valid We can check whether element is a member of the list or not by using memebership
operators.
2) Repetition Operator (*):
We can use repetition operator * to repeat elements of list specified number of times. 1) in Operator
2) not in Operator
1) x = [10, 20, 30]
2) y = x*3 1) n=[10,20,30,40]
3) print(y)  [10, 20, 30, 10, 20, 30, 10, 20, 30] 2) print (10 in n)
3) print (10 not in n)
4) print (50 in n)
Comparing List Objects 5) print (50 not in n)
We can use comparison operators for List objects.
Output
1) x = ["Dog", "Cat", "Rat"] True
2) y = ["Dog", "Cat", "Rat"] False
3) z = ["DOG", "CAT", "RAT"] False
4) print(x == y)  True True
5) print(x == z)  False
6) print(x != z)  True
clear() Function:
Note: Whenever we are using comparison operators (==, !=) for List objects then the We can use clear() function to remove all elements of List.
following should be considered
1) The Number of Elements 1) n=[10,20,30,40]
2) The Order of Elements 2) print(n)
3) The Content of Elements (Case Sensitive) 3) n.clear()
4) print(n)
Note: When ever we are using relatational Operators (<, <=, >, >=) between List Objects,
only 1ST Element comparison will be performed.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
112  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output Output
D:\Python_classes>py test.py D:\Python_classes>py test.py
[10, 20, 30, 40] [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
[]
Elements by Row wise:
[10, 20, 30]
Nested Lists: [40, 50, 60]
Sometimes we can take one list inside another list. Such type of lists are called nested [70, 80, 90]
lists.
Elements by Matrix style:
1) n=[10,20,[30,40]] 10 20 30
2) print(n) 40 50 60
3) print(n[0]) 70 80 90
4) print(n[2])
5) print(n[2][0])
6) print(n[2][1]) List Comprehensions:
It is very easy and compact way of creating list objects from any iterable objects
Output (Like List, Tuple, Dictionary, Range etc) based on some condition.
D:\Python_classes>py test.py
[10, 20, [30, 40]] Syntax: list = [expression for item in list if condition]
10
[30, 40] 1) s = [ x*x for x in range(1,11)]
30 2) print(s)
40 3) v = [2**x for x in range(1,6)]
4) print(v)
Note: We can access nested list elements by using index just like accessing multi 5) m = [x for x in s if x%2==0]
dimensional array elements. 6) print(m)

D:\Python_classes>py test.py
Nested List as Matrix: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In Python we can represent matrix by using nested lists. [2, 4, 8, 16, 32]
[4, 16, 36, 64, 100]
1) n=[[10,20,30],[40,50,60],[70,80,90]]
2) print(n) 1) words=["Balaiah","Nag","Venkatesh","Chiranjeevi"]
3) print("Elements by Row wise:") 2) l=[w[0] for w in words]
4) for r in n: 3) print(l)
5) print(r)
6) print("Elements by Matrix style:") Output: ['B', 'N', 'V', 'C']
7) for i in range(len(n)):
8) for j in range(len(n[i])): 1) num1=[10,20,30,40]
9) print(n[i][j],end=' ') 2) num2=[30,40,50,60]
10) print() 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 nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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:

1) words="the quick brown fox jumps over the lazy dog".split()


2) print(words)
3) l=[[w.upper(),len(w)] for w in words]
4) print(l)

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]]

TUPLE
Q) Write a Program to display Unique Vowels present in the
given Word?
1) vowels=['a','e','i','o','u']
2) word=input("Enter the word to search for vowels: ")
3) found=[]
4) for letter in word:

DATA STRUCTURE
5) if letter in vowels:
6) if letter not in found:
7) found.append(letter)
8) print(found)
9) print("The number of different vowels present in",word,"is",len(found))

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 nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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.
Q) Which of the following are valid Tuples?
2) Hence Tuple is Read only version of List. 1) t = ()
3) If our data is fixed and never changes then we should go for Tuple. 2) t = 10, 20, 30, 40
4) Insertion Order is preserved 3) t = 10
5) Duplicates are allowed 4) t = 10,
6) Heterogeneous objects are allowed. 5) t = (10)
7) We can preserve insertion order and we can differentiate duplicate objects by using 6) t = (10,)
index. Hence index will play very important role in Tuple also. 7) t = (10, 20, 30, 40)
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.
Tuple Creation:
10) Parenethesis are optional but recommended to use.
1) t = ()
1) t=10,20,30,40 Creation of Empty Tuple
2) print(t)
3) print(type(t))
4)
2) t = (10,)
5) Output t = 10,
6) (10, 20, 30, 40) Creation of Single valued Tuple, Parenthesis are Optional, should ends with Comma
7)
8) <class 'tuple'> 3) t = 10, 20, 30
9) t=() t = (10, 20, 30)
10) print(type(t)  tuple Creation of multi values Tuples & Parenthesis are Optional.

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.
4) By using tuple() Function:
1) t=(10) 1) list=[10,20,30]
2) print(t) 2) t=tuple(list)
3) print(type(t)) 3) print(t)
4) 4)
5) Output 5) t=tuple(range(10,20,2))
6) 10 6) print(t)
7) <class 'int'>
Accessing Elements of Tuple:
Eg: We can access either by index or by slice operator
1) t=(10,)
2) print(t) 1) By using Index:
3) print(type(t))
4) 1) t = (10, 20, 30, 40, 50, 60)
5) Output 2) print(t[0])  10
6) (10,) 3) print(t[-1])  60
7) <class 'tuple'> 4) print(t[100])  IndexError: tuple index out of range

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
118  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
2) By using Slice Operator: Important Functions of Tuple:
1) t=(10,20,30,40,50,60)
2) print(t[2:5]) 1) len()
3) print(t[2:100]) To return number of elements present in the tuple.
4) print(t[::2])
Eg: t = (10,20,30,40)
Output print(len(t))  4
(30, 40, 50)
(30, 40, 50, 60) 2) count()
(10, 30, 50)
To return number of occurrences of given element in the tuple

Tuple vs Immutability: Eg: t = (10, 20, 10, 10, 20)


 Once we creates tuple, we cannot change its content. print(t.count(10))  3
 Hence tuple objects are immutable.
3) index()
Eg:  Returns index of first occurrence of the given element.
t = (10, 20, 30, 40)  If the specified element is not available then we will get ValueError.
t[1] = 70  TypeError: 'tuple' object does not support item assignment
Eg: t = (10, 20, 10, 10, 20)
Mathematical Operators for Tuple: print(t.index(10))  0
We can apply + and * operators for tuple print(t.index(30))  ValueError: tuple.index(x): x not in tuple

1) Concatenation Operator (+): 4) sorted()


To sort elements based on default natural sorting order
1) t1=(10,20,30)
1) t=(40,10,30,20)
2) t2=(40,50,60)
2) t1=sorted(t)
3) t3=t1+t2
4) print(t3)  (10,20,30,40,50,60) 3) print(t1)
4) print(t)

2) Multiplication Operator OR Repetition Operator (*) Output


[10, 20, 30, 40]
1) t1=(10,20,30) (40, 10, 30, 20)
2) t2=t1*3
3) print(t2)  (10,20,30,10,20,30,10,20,30) We can sort according to reverse of default natural sorting order as follows
t1 = sorted(t, reverse = True)
print(t1)  [40, 30, 20, 10]

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
120  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5) min() And max() Functions: Note: At the time of tuple unpacking the number of variables and number of values
These functions return min and max values according to default natural sorting order. should be same, otherwise we will get ValueError.

1) t = (40,10,30,20) Eg:
2) print(min(t))  10 t = (10,20,30,40)
3) print(max(t))  40 a, b, c = t  ValueError: too many values to unpack (expected 3)

6) cmp(): Tuple Comprehension:


֍ It compares the elements of both tuples.  Tuple Comprehension is not supported by Python.
֍ If both tuples are equal then returns 0  t = ( x**2 for x in range(1,6))
֍ If the first tuple is less than second tuple then it returns -1  Here we are not getting tuple object and we are getting generator object.
֍ If the first tuple is greater than second tuple then it returns +1
1) t= ( x**2 for x in range(1,6))
1) t1=(10,20,30) 2) print(type(t))
2) t2=(40,50,60) 3) for x in t:
3) t3=(10,20,30) 4) print(x)
4) print(cmp(t1,t2))  -1
5) print(cmp(t1,t3))  0 D:\Python_classes>py test.py
6) print(cmp(t2,t3))  +1 <class 'generator'>
1
Note: cmp() function is available only in Python2 but not in Python 3 4
9
16
Tuple Packing and Unpacking: 25
We can create a tuple by packing a group of variables.
Q) Write a Program to take a Tuple of Numbers from the Keyboard
Eg:
a = 10 and Print its Sum and Average?
b = 20
c = 30 1) t=eval(input("Enter Tuple of Numbers:"))
d = 40 2) l=len(t)
t = a, b, c, d 3) sum=0
print(t)  (10, 20, 30, 40) 4) for x in t:
5) sum=sum+x
 Here a, b, c, d are packed into a Tuple t. This is nothing but Tuple packing. 6) print("The Sum=",sum)
7) print("The Average=",sum/l)
 Tuple unpacking is the reverse process of Tuple packing.
 We can unpack a Tuple and assign its values to different variables.
D:\Python_classes>py test.py
Enter Tuple of Numbers:(10,20,30,40)
1) t=(10,20,30,40)
The Sum= 100
2) a,b,c,d=t
The Average= 25.0
3) print("a=",a,"b=",b,"c=",c,"d=",d)
D:\Python_classes>py test.py
Output: a= 10 b= 20 c= 30 d= 40
Enter Tuple of Numbers: (100,200,300)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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

Differences between List and Tuple:


 List and Tuple are exactly same except small difference: List objects are mutable where
as Tuple objects are immutable.
 In both cases insertion order is preserved, duplicate objects are allowed, heterogenous
objects are allowed, index and slicing are supported.

List Tuple

SET
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

DATA STRUCTURE
Hashable and Immutable. Hashable and Immutable.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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 Output
for set. {}
 Duplicates are not allowed. <class 'dict'>
 Insertion order is not preserved.But we can sort the elements.
 Indexing and slicing not allowed for the set. Eg:
 Heterogeneous elements are allowed.
 Set objects are mutable i.e once we creates set object we can perform any changes in 1) s=set()
that object based on our requirement. 2) print(s)
 We can represent set elements within curly braces and with comma seperation 3) print(type(s))
 We can apply mathematical operations like union, intersection, difference etc on set
objects. Output
set()
Creation of Set Objects: <class 'set'>

1) s={10,20,30,40}
2) print(s)
Important Functions of Set:
3) print(type(s))
1) add(x):
Output Adds item x to the set.
{40, 10, 20, 30}
<class 'set'> 1) s={10,20,30}
2) s.add(40);
We can create set objects by using set() Function s = set(any sequence) 3) print(s) #{40, 10, 20, 30}

Eg 1: 2) update(x,y,z):
 To add multiple items to the set.
1) l = [10,20,30,40,10,20,10]  Arguments are not individual elements and these are Iterable objects like List, Range
2) s=set(l) etc.
3) print(s) # {40, 10, 20, 30}
 All elements present in the given Iterable objects will be added to the set.

Eg 2: 1) s={10,20,30}
2) l=[40,50,60,10]
1) s=set(range(5)) 3) s.update(l,range(5))
2) print(s) #{0, 1, 2, 3, 4} 4) print(s)

Note: Output: {0, 1, 2, 3, 4, 40, 10, 50, 20, 60, 30}


֍ 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.
Q) What is the difference between add() and update()
Functions in Set?
1) s={}  We can use add() to add individual item to the Set,where as we can use update()
2) print(s) function to add multiple items to Set.
3) print(type(s))  add() function can take only one argument where as update() function can take any
number of arguments but all arguments should be iterable objects.
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
126  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 for set s? 3) print {(s) 20, 30}
4) s.discard(50)
1) s.add(10)
5) print {(s) 20, 30}
2) s.add(10,20,30)  TypeError: add() takes exactly one argument (3 given)
3) s.update(10)  TypeError: 'int' object is not iterable
Q) What is the difference between remove() and discard() functions in Set?
4) s.update(range(1,10,2),range(0,10,2))
Q) Explain differences between pop(),remove() and discard() functionsin Set?

3) copy(): 7) clear():
 Returns copy of the set.
To remove all elements from the Set.
 It is cloned object.
1) s={10,20,30}
1) s = {10,20,30}
2) print(s)
2) s1 = s.copy()
3) s.clear()
3) print(s1)
4) print(s)

4) pop(): Output
It removes and returns some random element from the set. {10, 20, 30}
set()
1) s={40,10,30,20}
2) print(s)
3) print(s.pop())
4) print(s) Mathematical Operations on the Set:
Output 1) union():
{40, 10, 20, 30}  x.union(y)  We can use this function to return all elements present in both sets
40  x.union(y) OR x|y.
{10, 20, 30}
1) x = {10, 20, 30, 40}
5) remove(x): 2) y = {30, 40, 50, 60}
3) print (x.union(y))  {10, 20, 30, 40, 50, 60}
 It removes specified element from the set.
4) print (x|y)  {10, 20, 30, 40, 50, 60}
 If the specified element not present in the Set then we will get KeyError.

1) s = {40, 10, 30, 20} 2) intersection():


2) s.remove(30)  x.intersection(y) OR x&y.
3) print {(s) 40, 10, 20}  Returns common elements present in both x and y.
4) s.remove(50 KeyError: ) 50
1) x = {10, 20, 30, 40}
6) discard(x): 2) y = {30, 40, 50, 60}
3) print (x.intersection(y))  {40, 30}
1) It removes the specified element from the set.
4) print(x&y)  {40, 30}
2) If the specified element not present in the set then we won't get any error.

1) s = {10, 20, 30}


2) s.discard(10)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
128  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
3) difference(): Set Objects won't support indexing and slicing:
 x.difference(y) OR x-y.
 Returns the elements present in x but not in y. 1) s = {10,20,30,40}
2) print(s[0])  TypeError: 'set' object does not support indexing
1) x = {10, 20, 30, 40} 3) print(s[1:3])  TypeError: 'set' object is not subscriptable
2) y = {30, 40, 50, 60}
3) print (x.difference(y))  10, 20
4) print (x-y)  {10, 20} Q) Write a Program to eliminate Duplicates Present in the
5) print (y-x)  {50, 60} List?
4) symmetric_difference(): Approach - 1 Approach - 2
 x.symmetric_difference(y) OR x^y.
1) l=eval(input("Enter List of values: ")) 1) l=eval(input("Enter List of values: "))
 Returns elements present in either x OR y but not in both.
2) s=set(l) 2) l1=[]
1) x = {10, 20, 30, 40} 3) print(s) 3) for x in l:
2) y = {30, 40, 50, 60} 4) if x not in l1:
D:\Python_classes>py test.py 5) l1.append(x)
3) print (x.symmetric_difference(y))  {10, 50, 20, 60}
Enter List of values: [10,20,30,10,20,40] 6) print(l1)
4) print(x^y)  {10, 50, 20, 60}
{40, 10, 20, 30}
D:\Python_classes>py test.py
Membership Operators: (in, not in) Enter List of values: [10,20,30,10,20,40]
[10, 20, 30, 40]
1) s=set("durga")
2) print(s)
3) print('d' in s) Q) Write a Program to Print different Vowels Present in the
4) print('z' in s)
given Word?
Output
1) w=input("Enter word to search for vowels: ")
{'u', 'g', 'r', 'd', 'a'}
2) s=set(w)
True
3) v={'a','e','i','o','u'}
False
4) d=s.intersection(v)
5) print("The different vowel present in",w,"are",d)
Set Comprehension:
Set comprehension is possible. D:\Python_classes>py test.py
Enter word to search for vowels: durga
1) s = {x*x for x in range(5)} The different vowel present in durga are {'u', 'a'}
2) print (s)  {0, 1, 4, 9, 16}
3)
4) s = {2**x for x in range(2,10,2)}
5) print (s)  {16, 256, 64, 4}

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
130  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

֍ Duplicate keys are not allowed but values can be duplicated.


֍ Hetrogeneous objects are allowed for both key and values.
֍ Insertion order is not preserved
֍ Dictionaries are mutable
֍ Dictionaries are dynamic

DICTIONARY
֍ indexing and slicing concepts are not applicable

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

How to Create Dictionary?


DATA STRUCTURE 

d = {} OR d = dict()
We are creating empty dictionary. We can add entries as follows

1) d[100]="durga"
2) d[200]="ravi"
3) d[300]="shiva"
4) print(d)  {100: 'durga', 200: 'ravi', 300: 'shiva'}

 If we know data in advance then we can create dictionary as follows

 d = {100:'durga' ,200:'ravi', 300:'shiva'}


 d = {key:value, key:value}

How to Access Data from the Dictionary?


We can access data by using keys.

1) d = {100:'durga',200:'ravi', 300:'shiva'}
2) print(d[100]) #durga
3) print(d[300]) #shiva

If the specified key is not available then we will get KeyError

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
132  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
print(d[400])  KeyError: 400
How to Update Dictionaries?
We can prevent this by checking whether key is already available or not by using ֍ d[key] = value
has_key() function or by using in operator. ֍ If the key is not available then a new entry will be added to the dictionary with the
specified key-value pair
d.has_key(400)  Returns 1 if key is available otherwise returns 0 ֍ If the key is already available then old value will be replaced with new value.

But has_key() function is available only in Python 2 but not in Python 3. Hence 1) d={100:"durga",200:"ravi",300:"shiva"}
compulsory we have to use in operator. 2) print(d)
3) d[400]="pavan"
if 400 in d: 4) print(d)
print(d[400]) 5) d[100]="sunny"
6) print(d)

Q) Write a Program to Enter Name and Percentage Marks Output


in a Dictionary and Display Information on the Screen {100: 'durga', 200: 'ravi', 300: 'shiva'}
{100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
1) rec={} {100: 'sunny', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
2) n=int(input("Enter number of students: "))
3) i=1
4) while i <=n:
How to Delete Elements from Dictionary?
5) name=input("Enter Student Name: ")
6) marks=input("Enter % of Marks of Student: ") 1) del d[key]
7) rec[name]=marks  It deletes entry associated with the specified key.
8) i=i+1  If the key is not available then we will get KeyError.
9) print("Name of Student","\t","% of marks")
10) for x in rec: 1) d={100:"durga",200:"ravi",300:"shiva"}
11) print("\t",x,"\t\t",rec[x]) 2) print(d)
3) del d[100]
D:\Python_classes>py test.py 4) print(d)
Enter number of students: 3 5) del d[400]
Enter Student Name: durga
Enter % of Marks of Student: 60%
Output
Enter Student Name: ravi
{100: 'durga', 200: 'ravi', 300: 'shiva'}
Enter % of Marks of Student: 70%
{200: 'ravi', 300: 'shiva'}
Enter Student Name: shiva
KeyError: 400
Enter % of Marks of Student: 80%

Name of Student % of marks 2) d.clear()


--------------- ------------ To remove all entries from the dictionary.
durga 60%
ravi 70 % 1) d={100:"durga",200:"ravi",300:"shiva"}
shiva 80% 2) print(d)
3) d.clear()
4) print(d)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
134  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output d.get(key,defaultvalue)
{100: 'durga', 200: 'ravi', 300: 'shiva'} If the key is available then returns the corresponding value otherwise returns default
{} value.

1) d={100:"durga",200:"ravi",300:"shiva"}
3) del d 2) print(d[100])  durga
To delete total dictionary.Now we cannot access d.
3) print(d[400])  KeyError:400
4) print(d.get(100))  durga
1) d={100:"durga",200:"ravi",300:"shiva"}
5) print(d.get(400))  None
2) print(d)
6) print(d.get(100,"Guest"))  durga
3) del d
7) print(d.get(400,"Guest"))  Guest
4) print(d)

Output 5) pop():
{100: 'durga', 200: 'ravi', 300: 'shiva'} d.pop(key)
NameError: name 'd' is not defined  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.
Important Functions of Dictionary:
1) d={100:"durga",200:"ravi",300:"shiva"}
1) dict(): 2) print(d.pop(100))
3) print(d)
To create a dictionary
4) print(d.pop(400))
 d = dict()  It creates empty dictionary
 d = dict({100:"durga",200:"ravi"})  It creates dictionary with specified elements
Output
durga
 d = dict([(100,"durga"),(200,"shiva"),(300,"ravi")])
{200: 'ravi', 300: 'shiva'}
 It creates dictionary with the given list of tuple elements
KeyError: 400

2) len() 6) popitem():
Returns the number of items in the dictionary. It removes an arbitrary item(key-value) from the dictionaty and returns it.

3) clear(): 1) d={100:"durga",200:"ravi",300:"shiva"}
To remove all elements from the dictionary. 2) print(d)
3) print(d.popitem())
4) print(d)
4) get():
To get the value associated with the key Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
d.get(key) (300, 'shiva')
If the key is available then returns the corresponding value otherwise returns None.It {100: 'durga', 200: 'ravi'}
wont raise any error. If the dictionary is empty then we will get KeyError
d={}
print(d.popitem()) ==>KeyError: 'popitem(): dictionary is empty'

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
136  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
7) keys(): 10) copy():
It returns all keys associated eith dictionary. To create exactly duplicate dictionary (cloned copy)
d1 = d.copy();
1) d={100:"durga",200:"ravi",300:"shiva"}
2) print(d.keys())
3) for k in d.keys():
11) setdefault():
d.setdefault(k,v)
4) print(k)
 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
Output
the dictionary.
dict_keys([100, 200, 300])
100
1) d={100:"durga",200:"ravi",300:"shiva"}
200
2) print(d.setdefault(400,"pavan"))
300
3) print(d)
4) print(d.setdefault(100,"sachin"))
8) values(): 5) print(d)
It returns all values associated with the dictionary.
Output
1) d={100:"durga",200:"ravi",300:"shiva"} pavan
2) print(d.values()) {100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
3) for v in d.values(): durga
4) print(v) {100: 'durga', 200: 'ravi', 300: 'shiva', 400: 'pavan'}

Output 12) update():


dict_values(['durga', 'ravi', 'shiva'])
d.update(x)
durga
All items present in the dictionary x will be added to dictionary d
ravi
shiva
Q) Write a Program to take Dictionary from the Keyboard
9) items(): and print the Sum of Values?
It returns list of tuples representing key-value pairs.
[(k,v),(k,v),(k,v)] 1) d=eval(input("Enter dictionary:"))
2) s=sum(d.values())
1) d={100:"durga",200:"ravi",300:"shiva"} 3) print("Sum= ",s)
2) for k,v in d.items():
3) print(k,"--",v) Output
D:\Python_classes>py test.py
Output Enter dictionary:{'A':100,'B':200,'C':300}
100 -- durga Sum= 600
200 -- ravi
300 -- shiva

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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 Q) Write a Program to accept Student Name and Marks from the
present in the given String? Keyboard and creates a Dictionary. Also display Student Marks
by taking Student Name as Input?
1) word=input("Enter any word: ")
2) d={} 1) n=int(input("Enter the number of students: "))
3) for x in word: 2) d={}
4) d[x]=d.get(x,0)+1 3) for i in range(n):
5) for k,v in d.items(): 4) name=input("Enter Student Name: ")
6) print(k,"occurred ",v," times") 5) marks=input("Enter Student Marks: ")
6) d[name]=marks
Output 7) while True:
D:\Python_classes>py test.py 8) name=input("Enter Student Name to get Marks: ")
Enter any word: mississippi 9) marks=d.get(name,-1)
m occurred 1 times 10) if marks== -1:
i occurred 4 times 11) print("Student Not Found")
s occurred 4 times 12) else:
p occurred 2 times 13) print("The Marks of",name,"are",marks)
14) option=input("Do you want to find another student marks[Yes|No]")
Q) Write a Program to find Number of Occurrences of each Vowel 15) if option=="No":
present in the given String? 16) break
17) print("Thanks for using our application")
1) word=input("Enter any word: ")
2) vowels={'a','e','i','o','u'} Output
3) d={} D:\Python_classes>py test.py
4) for x in word: Enter the number of students: 5
5) if x in vowels:
6) d[x]=d.get(x,0)+1 Enter Student Name: sunny
7) for k,v in sorted(d.items()): Enter Student Marks: 90
8) print(k,"occurred ",v," times")
Enter Student Name: banny
Output Enter Student Marks: 80
D:\Python_classes>py test.py
Enter any word: doganimaldoganimal Enter Student Name: chinny
Enter Student Marks: 70
a occurred 4 times
i occurred 2 times
Enter Student Name: pinny
o occurred 2 times
Enter Student Marks: 60

Enter Student Name: vinny


Enter Student Marks: 50

Enter Student Name to get Marks: sunny


The Marks of sunny are 90

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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

Enter Student Name to get Marks: durga


Student Not Found

Do you want to find another student marks[Yes|No]No


Thanks for using our application

Dictionary Comprehension:
Comprehension concept applicable for dictionaries also.

1) squares={x:x*x for x in range(1,6)}


2) print(squares)
3) doubles={x:2*x for x in range(1,6)}
4) print(doubles)

Output

FUNCTIONS
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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 4) wish()
these statements everytime seperately.We have to define these statements as a single 5) wish()
unit and we can call that unit any number of times based on our requirement without
rewriting. This unit is nothing but function.
Parameters
֍ The main advantage of functions is code Reusability. Parameters are inputs to the function. If a function contains parameters, then at the time
֍ Note: In other languages functions are known as methods,procedures,subroutines etc 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
֍ Python supports 2 types of functions name.
1) Built in Functions
2) User Defined Functions 1) def wish(name):
2) print("Hello",name," Good Morning")
1) Built in Functions: 3) wish("Durga")
4) wish("Ravi")
The functions which are coming along with Python software automatically, are called
built in functions or pre defined functions.
D:\Python_classes>py test.py
Eg: id() Hello Durga Good Morning
type() Hello Ravi Good Morning
input()
eval()
Eg: Write a function to take number as input and print its square value
etc..
1) def squareIt(number):
2) User Defined Functions: 2) print("The Square of",number,"is", number*number)
The functions which are developed by programmer explicitly according to business 3) squareIt(4)
requirements, are called user defined functions. 4) squareIt(5)

Syntax to Create User defined Functions: D:\Python_classes>py test.py


def function_name(parameters) : The Square of 4 is 16
""" doc string""" The Square of 5 is 25
----
-----
return value Return Statement:
Function can take input values as parameters and executes business logic, and returns
Note: While creating functions we can use 2 keywords output to the caller with return statement.
1) def (mandatory)
2) return (optional) Q) Write a Function to accept 2 Numbers as Input and
Eg 1: Write a function to print Hello return Sum
1) def add(x,y):
test.py 2) return x+y
3) result=add(10,20)
1) def wish(): 4) print("The sum is",result)
2) print("Hello Good Morning") 5) print("The sum is",add(100,200))
3) wish()
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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 Output
The sum is 30 D:\Python_classes>py test.py
The sum is 300 The Factorial of 1 is : 1
The Factorial of 2 is : 2
If we are not writing return statement then default return value is None. The Factorial of 3 is : 6
The Factorial of 4 is : 24
1) def f1():
2) print("Hello")
3) f1() Returning Multiple Values from a Function:
4) print(f1()) In other languages like C,C++ and Java, function can return atmost one value. But in
Python, a function can return any number of values.
Output
Hello Eg 1:
Hello
None 1) def sum_sub(a,b):
2) sum=a+b
Q) Write a Function to check whether the given Number is 3) sub=a-b
4) return sum,sub
Even OR Odd? 5) x,y=sum_sub(100,50)
6) print("The Sum is :",x)
1) def even_odd(num): 7) print("The Subtraction is :",y)
2) if num%2==0:
3) print(num,"is Even Number") Output
4) else: The Sum is : 150
5) print(num,"is Odd Number") The Subtraction is : 50
6) even_odd(10)
7) even_odd(15) Eg 2:
Output 1) def calc(a,b):
D:\Python_classes>py test.py 2) sum=a+b
10 is Even Number 3) sub=a-b
15 is Odd Number 4) mul=a*b
5) div=a/b
Q) Write a Function to find Factorial of given Number? 6) return sum,sub,mul,div
7) t=calc(100,50)
1) def fact(num): 8) print("The Results are")
2) result=1 9) for i in t:
3) while num>=1: 10) print(i)
4) result=result*num
5) num=num-1 Output
6) return result The Results are
7) for i in range(1,5): 150
8) print("The Factorial of",i,"is :",fact(i)) 50
5000
2.0
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
146  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
Types of Arguments have to take positional arguments and then keyword arguments,otherwise we will get
def f1(a,b): syntaxerror.
------
------ 1) def wish(name,msg):
------ 2) print("Hello",name,msg)
f1(10,20) 3) wish("Durga","GoodMorning")  Valid
4) wish("Durga",msg="GoodMorning")  Valid
a, b are formal arguments where as 10,20 are actual arguments. 5) wish(name="Durga","GoodMorning")  Invalid
6) SyntaxError: positional argument follows keyword argument
There are 4 types are actual arguments are allowed in Python.
1) Positional Arguments
2) Keyword Arguments 3) Default Arguments:
3) Default Arguments Sometimes we can provide default values for our positional arguments.
4) Variable Length Arguments
1) def wish(name="Guest"):
2) print("Hello",name,"Good Morning")
1) Positional Arguments: 3) wish("Durga")
 These are the arguments passed to function in correct positional order. 4) wish()
def sub(a, b):
print(a-b) Output
Hello Durga Good Morning
sub(100, 200) Hello Guest Good Morning
sub(200, 100) If we are not passing any name then only default value will be considered.

 The number of arguments and position of arguments must be matched. If we change ***Note:
the order then result may be changed. After default arguments we should not take non default arguments.
 If we change the number of arguments then we will get error.
1) def wish(name="Guest",msg="Good Morning"):  Valid
2) Keyword Arguments: 2) def wish(name,msg="Good Morning"):  Valid
3) def wish(name="Guest",msg):  Invalid
We can pass argument values by keyword i.e by parameter name.
SyntaxError: non-default argument follows default argument
1) def wish(name,msg):
2) print("Hello",name,msg)
3) wish(name="Durga",msg="Good Morning") 4) Variable Length Arguments:
4) wish(msg="Good Morning",name="Durga")  Sometimes we can pass variable number of arguments to our function, such type of
arguments are called variable length arguments.
Output  We can declare a variable length argument with * symbol as follows
Hello Durga Good Morning  def f1(*n):
Hello Durga Good Morning  We can call this function by passing any number of arguments including zero number.
Here the order of arguments is not important but number of arguments must be matched.  Internally all these values represented in the form of tuple.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
148  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) def sum(*n): 1) def f1(*s,n1):
2) total=0 2) for s1 in s:
3) for n1 in n: 3) print(s1)
4) total=total+n1 4) print(n1)
5) print("The Sum=",total) 5)
6) 6) f1("A","B",n1=10)
7) sum()
8) sum(10) Output
9) sum(10,20) A
10) sum(10,20,30,40) B
10
Output f1("A","B",10)  Invalid
The Sum= 0 TypeError: f1() missing 1 required keyword-only argument: 'n1'
The Sum= 10
The Sum= 30 Note: We can declare key word variable length arguments also.
The Sum= 100
 For this we have to use **.
Note: We can mix variable length arguments with positional arguments.  def f1(**n):
 We can call this function by passing any number of keyword arguments. Internally
1) def f1(n1,*s): these keyword arguments will be stored inside a dictionary.
2) print(n1)
3) for s1 in s: 1) def display(**kwargs):
4) print(s1) 2) for k,v in kwargs.items():
5) 3) print(k,"=",v)
6) f1(10) 4) display(n1=10,n2=20,n3=30)
7) f1(10,20,30,40) 5) display(rno=100,name="Durga",marks=70,subject="Java")
8) f1(10,"A",30,"B")
Output
Output n1 = 10
10 n2 = 20
10 n3 = 30
20 rno = 100
30 name = Durga
40 marks = 70
10 subject = Java
A
30
B

Note: After variable length argument,if we are taking any other arguments then we
should provide values as keyword arguments.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
150  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Case Study: Types of Variables
def f(arg1,arg2,arg3=4,arg4=8): Python supports 2 types of variables.
print(arg1,arg2,arg3,arg4)
1) Global Variables
1) f(3,2)  3 2 4 8 2) Local Variables

2) f(10,20,30,40)  10 20 30 40 1) Global Variables


 The variables which are declared outside of function are called global variables.
3) f(25,50,arg4=100)  25 50 4 100  These variables can be accessed in all functions of that module.

4) f(arg4=2,arg1=3,arg2=4)  3 4 4 2 1) a=10 # global variable


2) def f1():
5) f()  Invalid 3) print(a)
TypeError: f() missing 2 required positional arguments: 'arg1' and 'arg2' 4)
5) def f2():
6) f(arg3=10, arg4=20, 30, 40)  Invalid 6) print(a)
SyntaxError: positional argument follows keyword argument 7)
[After keyword arguments we should not take positional arguments] 8) f1()
9) f2()
7) f(4, 5, arg2 = 6)  Invalid
TypeError: f() got multiple values for argument 'arg2' Output
10
8) f(4, 5, arg3 = 5, arg5 = 6)  Invalid 10
TypeError: f() got an unexpected keyword argument 'arg5'

Note: Function vs Module vs Library


2) Local Variables:
 The variables which are declared inside a function are called local variables.
1) A group of lines with some name is called a function
 Local variables are available only for the function in which we declared it.i.e from
2) A group of functions saved to a file, is called Module
outside of function we cannot access.
3) A group of Modules is nothing but Library
1) def f1():
Library Function 2) a=10
3) print(a) # valid
Module 1 Module 2 -----------------
4)
-----------------
----------------- 5) def f2():
Function 1 Function 1 6) print(a) #invalid
-----------------
----------------- 7)
Function 2 Function 2 ----------------- 8) f1()
----------------- 9) f2()
Function 3 Function 3 -----------------
----------------- NameError: name 'a' is not defined
-

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
152  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
8) f1()
global Keyword: 9) f2()
We can use global keyword for the following 2 purposes:
1) To declare global variable inside function Output: NameError: name 'a' is not defined
2) To make global variable available to the function so that we can perform required
modifications 1) def f1():
2) global a
1) a=10 3) a=10
2) def f1(): 4) print(a)
3) a=777 5)
4) print(a) 6) def f2():
5) 7) print(a)
6) def f2(): 8)
7) print(a) 9) f1()
8) 10) f2()
9) f1()
10) f2() Output
11)
10
10
Output
777
Note: If global variable and local variable having the same name then we can access
10
global variable inside a function as follows
1) a=10
1) a = 10  Global Variable
2) def f1():
2) def f1():
3) global a
3) a=777  Local Variable
4) a=777
4) print(a)
5) print(a)
5) print(globals()['a'])
6) def f2():
6) f1()
7) print(a)
8)
9) f1() Output
10) f2() 777
10
Output
777 Recursive Functions
777 A function that calls itself is known as Recursive Function.
1) def f1():
2) a=10
Eg:
factorial(3) = 3 * factorial(2)
3) print(a)
4) = 3 * 2 * factorial(1)
5) def f2(): = 3 * 2 * 1 * factorial(0)
=3*2*1*1
6) print(a)
=6
7)
factorial(n) = n * factorial(n-1)
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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: Q) Write a Program to create a Lambda Function to find Square of
1) We can reduce length of the code and improves readability.
2) We can solve complex problems very easily. given Number?
1) s=lambda n:n*n
Q) Write a Python Function to find Factorial of given 2) print("The Square of 4 is :",s(4))
Number with Recursion 3) print("The Square of 5 is :",s(5))

1) def factorial(n): Output


2) if n==0: The Square of 4 is : 16
3) result=1 The Square of 5 is : 25
4) else:
5) result=n*factorial(n-1) Q) Lambda Function to find Sum of 2 given Numbers
6) return result
7) print("Factorial of 4 is :",factorial(4)) 1) s=lambda a,b:a+b
8) print("Factorial of 5 is :",factorial(5)) 2) print("The Sum of 10,20 is:",s(10,20))
3) print("The Sum of 100,200 is:",s(100,200))
Output
Factorial of 4 is : 24 Output
Factorial of 5 is : 120 The Sum of 10,20 is: 30
The Sum of 100,200 is: 300
Anonymous Functions:
 Sometimes we can declare a function without any name,such type of nameless Q) Lambda Function to find biggest of given Values
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) 1) s=lambda a,b:a if a>b else b
2) print("The Biggest of 10,20 is:",s(10,20))
3) print("The Biggest of 100,200 is:",s(100,200))
Normal Function:
We can define by using def keyword. Output
def squareIt(n): The Biggest of 10,20 is: 20
return n*n The Biggest of 100,200 is: 200

Note: Lambda Function internally returns expression value and we are not required to
Lambda Function: write return statement explicitly.
We can define by using lambda keyword lambda n:n*n
Note: Sometimes we can pass function as argument to another function. In such cases
Syntax of lambda Function: lambda argument_list : expression lambda functions are best choice.

Note: By using Lambda Functions we can write very concise code so that readability of We can use lambda functions very commonly with filter(), map() and reduce() functions,
the program will be improved. because these functions expect function as argument.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
156  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
filter() Function: Without Lambda
We can use filter() function to filter values from the given sequence based on some
condition. 1) l=[1,2,3,4,5]
2) def doubleIt(x):
filter(function,sequence) 3) return 2*x
Where Function Argument is responsible to perform conditional check Sequence can be 4) l1=list(map(doubleIt,l))
List OR Tuple OR String. 5) print(l1) #[2, 4, 6, 8, 10]

Q) Program to filter only Even Numbers from the List by using With Lambda
filter() Function? 1) l=[1,2,3,4,5]
2) l1=list(map(lambda x:2*x,l))
Without Lambda Function: 3) print(l1) #[2, 4, 6, 8, 10]

1) def isEven(x): -------------------------------------------------------------


2) if x%2==0: Eg 2: To find square of given numbers
3) return True
4) else: 1) l=[1,2,3,4,5]
5) return False 2) l1=list(map(lambda x:x*x,l))
6) l=[0,5,10,15,20,25,30] 3) print(l1) #[1, 4, 9, 16, 25]
7) l1=list(filter(isEven,l))
8) print(l1) #[0,10,20,30] We can apply map() function on multiple lists also.But make sure all list should have same
length.
With Lambda Function:
Syntax: map(lambda x,y:x*y,l1,l2))
1) l=[0,5,10,15,20,25,30] x is from l1 and y is from l2
2) l1=list(filter(lambda x:x%2==0,l))
3) print(l1) #[0,10,20,30] 1) l1=[1,2,3,4]
4) l2=list(filter(lambda x:x%2!=0,l)) 2) l2=[2,3,4,5]
5) print(l2) #[5,15,25] 3) l3=list(map(lambda x,y:x*y,l1,l2))
4) print(l3) #[2, 6, 12, 20]

map() Function:
 For every element present in the given sequence,apply some functionality and reduce() Function:
generate new element with the required modification. For this requirement we  reduce() function reduces sequence of elements into a single element by applying the
should go for map() function. specified function.
 reduce(function,sequence)
 Eg: For every element present in the list perform double and generate new list of  reduce() function present in functools module and hence we should write import
doubles. statement.

 Syntax: map(function, sequence) 1) from functools import *


2) l=[10,20,30,40,50]
3) result=reduce(lambda x,y:x+y,l)
 The function can be applied on each element of sequence and generates new
4) print(result) # 150
sequence.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
158  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg: Note:
 In the above example only one function is available but we can call that function by
1) result=reduce(lambda x,y:x*y,l) using either wish name or greeting name.
2) print(result) #12000000  If we delete one name still we can access that function by using alias name.

Eg: 1) def wish(name):


2) print("Good Morning:",name)
1) from functools import * 3)
2) result=reduce(lambda x,y:x+y,range(1,101)) 4) greeting=wish
3) print(result) #5050 5)
6) greeting('Durga')
7) wish('Durga')
Everything is an Object: 8)
 In Python every thing is treated as object. 9) del wish
 Even functions also internally treated as objects only. 10) #wish('Durga')  NameError: name 'wish' is not defined
11) greeting('Pavan')
1) def f1():
2) print("Hello")
Output:
3) print(f1)
Good Morning: Durga
4) print(id(f1))
Good Morning: Durga
Good Morning: Pavan
Output:
<function f1 at 0x00419618>
4298264 Nested Functions:
We can declare a function inside another function,such type of functions are called Nested
functions.
Function Aliasing:
For the existing function we can give another name, which is nothing but function aliasing. 1) def outer():
2) print("outer function started")
1) def wish(name): 3) def inner():
2) print("Good Morning:",name) 4) print("inner function execution")
3) 5) print("outer function calling inner function")
4) greeting=wish 6) inner()
5) print(id(wish)) 7) outer()
6) print(id(greeting)) 8) #inner()  NameError: name 'inner' is not defined
7)
8) greeting('Durga')
Output:
9) wish('Durga')
outer function started
outer function calling inner function
Output: inner function execution
4429336
4429336 In the above example inner() function is local to outer() function and hence it is not
Good Morning: Durga possible to call directly from outside of outer() function.
Good Morning: Durga
Note: A function can return another function.
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
160  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) def outer():
2) print("outer function started")
3) def inner():
4) print("inner function execution")
5) print("outer function returning inner function")
6) return inner
7) f1=outer()
8) f1()
9) f1()
10) f1()

Output:
outer function started
outer function returning inner function
inner function execution

MODULES
inner function execution
inner function execution

Q) What is the differenece between the following lines?


f1 = outer
f1 = outer()

 In the first case for the outer() function we are providing another name f1
(function aliasing).
 But in the second case we calling outer() function,which returns inner function.For
that inner function() we are providing another name f1

Note: We can pass function as argument to another function


Eg: filter(function,sequence)
map(function,sequence)
reduce(function,sequence)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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.
Renaming a Module at the time of import
 Every Python file (.py) acts as a module. (Module Aliasing):
 Eg: import durgamath as m
durgamath.py  Here durgamath is original module name and m is alias name.
 We can access members by using alias name m
1) x = 888
2) test.py:
3) def add(a,b):
4) print("The Sum:",a+b) 1) import durgamath as m
5) 2) print(m.x)
6) def product(a,b): 3) m.add(10,20)
7) print("The Product:",a*b) 4) m.product(10,20)
 durgamath module contains one variable and 2 functions.
 If we want to use members of module in our program then we should import that from ... import:
module. We can import particular members of module by using from ... import .
import modulename The main advantage of this is we can access members directly without using module
name.
 We can access members by using module name.
modulename.variable 1) from durgamath import x,add
modulename.function() 2) print(x)
3) add(10,20)
test.py: 4) product(10,20)  NameError: name 'product' is not defined

1) import durgamath We can import all members of a module as follows from durgamath import *
2) print(durgamath.x)
3) durgamath.add(10,20) test.py:
4) durgamath.product(10,20)
1) from durgamath import *
Output 2) print(x)
888 3) add(10,20)
The Sum: 30 4) product(10,20)
The Product: 200
Various Possibilties of import:
Note: Whenever we are using a module in our program, for that module compiled file 1) import modulename
will be generated and stored in the hard disk permanently. 2) import module1,module2,module3
3) import module1 as m
4) import module1 as m1,module2 as m2,module3
5) from module import member
6) from module import member1,member2,memebr3
7) from module import memeber1 as x
8) from module import *

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
164  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Member Aliasing: test.py:

1) import module1
1) from durgamath import x as y,add as sum
2) import module1
2) print(y)
3) from imp import reload
3) sum(10,20)
4) reload(module1)
5) reload(module1)
Once we defined as alias name,we should use alias name only and we should not use
6) reload(module1)
original name
7) print("This is test module")
1) from durgamath import x as y
In the above program module1 will be loaded 4 times in that 1 time by default and 3 times
2) print(x)  NameError: name 'x' is not defined
explicitly. In this case output is

Reloading a Module: 1) This is from module1


By default module will be loaded only once eventhough we are importing multiple 2) This is from module1
multiple times. 3) This is from module1
4) This is from module1
module1.py: 5) This is test module
print("This is from module1")
The main advantage of explicit module reloading is we can ensure that updated version is
always available to our program.
test.py

1) import module1 Finding Members of Module by using dir() Function:


2) import module1 Python provides inbuilt function dir() to list out all members of current module or a
3) import module1 specified module.
4) import module1
5) print("This is test module") dir()  To list out all members of current module
dir(moduleName)  To list out all members of specified module
Output
This is from module1 Eg 1: test.py
This is test module
1) x=10
 In the above program test module will be loaded only once eventhough we are 2) y=20
importing multiple times. 3) def f1():
4) print("Hello")
 The problem in this approach is after loading a module if it is updated outside then 5) print(dir()) # To print all members of current module
updated version of module1 is not available to our program.
Output
 We can solve this problem by reloading module explicitly based on our requirement. ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__nam
 We can reload by using reload() function of imp module. e__', '__package__', '__spec__', 'f1', 'x', 'y']
1) import imp
2) imp.reload(module1)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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 test.py

durgamath.py: 1) <_frozen_importlib_external.SourceFileLoader object at 0x00572170>


2) __main__
1) x=888 3) None
2) 4) None
3) def add(a,b):
4) print("The Sum:",a+b) The Special Variable __name__:
5)
6) def product(a,b):
 For every Python program, a special variable __name__ will be added internally.
7) print("The Product:",a*b)
 This variable stores information regarding whether the program is executed as an
individual program or as a module.
test.py:
 If the program executed as an individual program then the value of this variable is
1) import durgamath
__main__
2) print(dir(durgamath))
 If the program executed as a module from some other program then the value of this
Output variable is the name of module where it is defined.
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'add', 'product', 'x']
 Hence by using this __name__ variable we can identify whether the program executed
directly or as a module.
Note: For every module at the time of execution Python interpreter will add some special
properties automatically for internal use.
Demo program:
Eg: __builtins__,__cached__,'__doc__,__file__, __loader__, __name__,__package__,
__spec__ module1.py:

Based on our requirement we can access these properties also in our program. 1) def f1():
2) if __name__=='__main__':
3) print("The code executed as a program")
Eg: test.py 4) else:
5) print("The code executed as a module from some other program")
1) print(__builtins__ ) 6) f1()
2) print(__cached__ )
3) print(__doc__) test.py:
4) print(__file__)
5) print(__loader__) 1) import module1
6) print(__name__) 2) module1.f1()
7) print(__package__)
8) print(__spec__) D:\Python_classes>py module1.py
The code executed as a program
Output
<module 'builtins' (built-in)> D:\Python_classes>py test.py
None The code executed as a module from some other program
None The code executed as a module from some other program
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
168  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) from random import *
Working with math Module: 2) for i in range(10):
 Python provides inbuilt module math. 3) print(random())
 This module defines several functions which can be used for mathematical operations.
 The main important functions are Output
1) sqrt(x) 0.4572685609302056
2) ceil(x) 0.6584325233197768
3) floor(x) 0.15444034016553587
4) fabs(x) 0.18351427005232201
5) log(x) 0.1330257265904884
6) sin(x) 0.9291139798071045
7) tan(x) 0.6586741197891783
8) .... 0.8901649834019002
0.25540891083913053
1) from math import * 0.7290504335962871
2) print(sqrt(4))
3) print(ceil(10.1))
4) print(floor(10.1)) 2) randint() Function:
5) print(fabs(-10.6)) To generate random integer beween two given numbers(inclusive)
6) print(fabs(10.6))
1) from random import *
Output 2) for i in range(10):
2.0 3) print(randint(1,100)) # generate random int value between 1 and 100(inclusive)
11
10 Output
10.6 51
10.6 44
39
Note: We can find help for any module by using help() function 70
49
74
Eg:
52
import math
10
help(math)
40
8
Working with random Module:
 This module defines several functions to generate random numbers. 3) uniform() Function:
 We can use these functions while developing games,in cryptography and to generate It returns random float values between 2 given numbers (not inclusive)
random numbers on fly for authentication.
1) from random import *
1) random() Function: 2) for i in range(10):
3) print(uniform(1,10))
This function always generate some float value between 0 and 1 ( not inclusive)
0<x<1

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
170  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output Output: 2
9.787695398230332 2
6.81102218793548 8
8.068672144377329 10
8.567976357239834 3
6.363511674803802 5
2.176137584071641 9
4.822867939432386 1
6.0801725149678445 6
7.508457735544763 3
1.9982221862917555
1) from random import *
random()  in between 0 and 1 (not inclusive) 2) for i in range(10):
randint(x,y)  in between x and y ( inclusive) 3) print(randrange(1,11,2))
uniform(x,y)  in between x and y ( not inclusive)
Output: 1
4) randrange ([start], stop, [step]) 3
9
 Returns a random number from range
5
 start <= x < stop
7
 start argument is optional and default value is 0
1
 step argument is optional and default value is 1
1
1
 randrange(10)  generates a number from 0 to 9 7
 randrange(1,11)  generates a number from 1 to 10 3
 randrange(1,11,2)  generates a number from 1,3,5,7,9

1) from random import * 5) choice() Function:


2) for i in range(10):  It won’t return random number.
3) print(randrange(10))  It will return a random object from the given list or tuple.

Output: 9 1) from random import *


4 2) list=["Sunny","Bunny","Chinny","Vinny","pinny"]
0 3) for i in range(10):
2 4) print(choice(list))
9 Output
4 Bunny
8 pinny
9 Bunny
5 Sunny
9 Bunny
pinny
1) from random import * pinny
2) for i in range(10): Vinny
3) print(randrange(1,11)) Bunny
Sunny
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
172  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

x.py y.py m.py n.py

PACKAGES Home Loan Vehicle Loan

Loan

__init__.py

File 1

File 1 File 1

__init__.py __init__.py

Module 1 Module 1 Module 1 Module 1

Home Loan Vehicle Loan

Loan

The main advantages of package statement are


1) We can resolve naming conflicts
2) We can identify our components uniquely
3) It improves modularity of the application

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
174  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg 1: test.py
D:\Python_classes>
|-test.py 1) from com.module1 import f1
|-pack1 2) from com.durgasoft.module2 import f2
|-module1.py 3) f1()
|-__init__.py 4) f2()

__init__.py: Output
empty file D:\Python_classes>py test.py
Hello this is from module1 present in com
module1.py: Hello this is from module2 present in com.durgasoft
def f1():
print("Hello this is from module1 present in pack1") Note: Summary diagram of library, packages, modules which contains functions, classes
and variables.
test.py (version-1):
import pack1.module1 Library
pack1.module1.f1()

test.py (version-2):
from pack1.module1 import f1 pack 1 pack 2 --------------- pack n
f1()

Eg 2: module 1 module 2 module n module 1 module 2 module n


D:\Python_classes>
|-test.py
|-com
|-module1.py
|-__init__.py
function 1 function 2 function n variables classes
|-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 nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
176  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-1:
**********
**********

100
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

PATTERN
8888888888
9999999999
10 10 10 10 10 10 10 10 10 10

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

PROGRAMS
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 nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
178  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-4: Pattern-7:
AAAAAAAAAA 10 9 8 7 6 5 4 3 2 1
BBBBBBBBBB 10 9 8 7 6 5 4 3 2 1
CCCCCCCCCC 1) n=int(input("Enter the number of rows: ")) 10 9 8 7 6 5 4 3 2 1 1) n=int(input("Enter the number of rows: "))
DDDDDDDDDD 2) for i in range(1,n+1): 10 9 8 7 6 5 4 3 2 1 2) for i in range(1,n+1):
EEEEEEEEEE 3) for j in range(1,n+1): 10 9 8 7 6 5 4 3 2 1 3) for j in range(1,n+1):
FFFFFFFFFF 4) print(chr(64+i),end=" ") 10 9 8 7 6 5 4 3 2 1 4) print(n+1-j,end=" ")
GGGGGGGGGG 5) print() 10 9 8 7 6 5 4 3 2 1 5) print()
HHHHHHHHHH 10 9 8 7 6 5 4 3 2 1
IIIIIIIIII 10 9 8 7 6 5 4 3 2 1
JJJJJJJJJJ 10 9 8 7 6 5 4 3 2 1

Pattern-8:
Pattern-5:
JJJJJJJJJJ
ABCDEFGHIJ IIIIIIIIII
ABCDEFGHIJ HHHHHHHHHH 1) n=int(input("Enter the number of rows: "))
ABCDEFGHIJ GGGGGGGGGG 2) for i in range(1,n+1):
ABCDEFGHIJ 1) n=int(input("Enter the number of rows: ")) FFFFFFFFFF 3) for j in range(1,n+1):
ABCDEFGHIJ 2) for i in range(1,n+1): EEEEEEEEEE 4) print(chr(65+n-i),end=" ")
ABCDEFGHIJ 3) for j in range(1,n+1): DDDDDDDDDD 5) print()
ABCDEFGHIJ 4) print(chr(64+j),end=" ") CCCCCCCCCC
ABCDEFGHIJ 5) print() BBBBBBBBBB
ABCDEFGHIJ AAAAAAAAAA
ABCDEFGHIJ

Pattern-6: Pattern-9:
10 10 10 10 10 10 10 10 10 10 JIHGFEDCBA
9999999999 JIHGFEDCBA
8888888888 1) n=int(input("Enter the number of rows: ")) JIHGFEDCBA 1) n=int(input("Enter the number of rows: "))
7777777777 2) for i in range(1,n+1): JIHGFEDCBA 2) for i in range(1,n+1):
6666666666 3) for j in range(1,n+1): JIHGFEDCBA 3) for j in range(1,n+1):
5555555555 4) print(n+1-i,end=" ") JIHGFEDCBA 4) print(chr(65+n-j),end=" ")
4444444444 5) print() JIHGFEDCBA 5) print()
3333333333 JIHGFEDCBA
2222222222 JIHGFEDCBA
1111111111 JIHGFEDCBA

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
180  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-10: Code - 1 Pattern-13:
1) n=int(input("Enter the number of rows:"))
* 2) for i in range(1,n+1): A
** 3) for j in range(1,i+1): BB
*** 4) print("*",end=" ") CCC 1) n=int(input("Enter the number of rows: "))
**** 5) print() DDDD 2) for i in range(1,n+1):
***** EEEEE 3) for j in range(1,i+1):
****** Code - 2 FFFFFF 4) print(chr(64+i),end=" ")
******* 1) n=int(input("Enter the number of rows:")) GGGGGGG 5) print()
******** 2) for i in range(1,n+1): HHHHHHHH
********* 3) print("* "*i) IIIIIIIII
********** JJJJJJJJJJ

Pattern-11: Pattern-14:
1 A
1) n=int(input("Enter the number of rows: ")) AB
22
2) for i in range(1,n+1): ABC
333 1) n=int(input("Enter the number of rows: "))
3) for j in range(1,i+1): ABCD
4444 2) for i in range(1,n+1):
4) print(i,end=" ") ABCDE
55555 3) for j in range(1,i+1):
5) print() ABCDEF
666666 4) print(chr(64+j),end=" ")
7777777 ABCDEFG
5) print()
88888888 ABCDEFGH
999999999 ABCDEFGHI
10 10 10 10 10 10 10 10 10 10 ABCDEFGHIJ

Pattern-12: 1) Squares
2) Right Angled Triangle
1 3) Reverse of Right Angled Triangle
12
123
1234 1) n=int(input("Enter the number of rows: "))
2) for i in range(1,n+1):
Pattern-15:
12345
123456 3) for j in range(1,i+1): **********
1234567 4) print(j,end=" ") *********
12345678 5) print() ********
1) n=int(input("Enter the number of rows: "))
123456789 *******
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+2-i):
*****
4) print("*",end=" ")
****
5) print()
***
**
*
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
182  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-16: Pattern-19:
1111111111 ABCDEFGHIJ
222222222 ABCDEFGHI
33333333 ABCDEFGH 1) n=int(input("Enter the number of rows: "))
1) n=int(input("Enter the number of rows: "))
4444444 ABCDEFG 2) for i in range(1,n+1):
2) for i in range(1,n+1):
555555 ABCDEF 3) for j in range(1,n+2-i):
3) for j in range(1,n+2-i):
66666 ABCDE 4) print(chr(64+j),end=" ")
4) print(i,end=" ")
7777 ABCD 5) print()
5) print()
888 ABC
99 AB
10 A

Pattern-17: Pattern-20:
1 2 3 4 5 6 7 8 9 10 10 10 10 10 10 10 10 10 10 10
123456789 999999999
12345678 1) n=int(input("Enter the number of rows: ")) 88888888
1) n=int(input("Enter the number of rows: "))
1234567 2) for i in range(1,n+1): 7777777
2) for i in range(1,n+1):
123456 3) for j in range(1,n+2-i): 666666
3) for j in range(1,n+2-i):
12345 4) print(j,end=" ") 55555
4) print(n+1-i,end=" ")
1234 5) print() 4444
5) print()
123 333
12 22
1 1

Pattern-18:
Pattern-21:
AAAAAAAAAA
BBBBBBBBB 10 9 8 7 6 5 4 3 2 1
CCCCCCCC 10 9 8 7 6 5 4 3 2
DDDDDDD 1) n=int(input("Enter the number of rows: ")) 10 9 8 7 6 5 4 3
EEEEEE 2) for i in range(1,n+1): 10 9 8 7 6 5 4 1) n=int(input("Enter the number of rows: "))
FFFFF 3) for j in range(1,n+2-i): 10 9 8 7 6 5 2) for i in range(1,n+1):
GGGG 4) print(chr(64+i),end=" ") 10 9 8 7 6 3) for j in range(1,n+2-i):
HHH 5) print() 10 9 8 7 4) print(n+1-j,end=" ")
II 10 9 8 5) print()
J 10 9
10

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
184  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-22: Pattern-25:
JJJJJJJJJJ *
IIIIIIIII **
HHHHHHHH *** 1) n=int(input("Enter the number of rows: "))
1) n=int(input("Enter the number of rows: ")) 2) for i in range(1,n+1):
GGGGGGG 2) for i in range(1,n+1): ****
FFFFFF ***** 3) print(" "*(n-i),end="")
3) for j in range(1,n+2-i): 4) for j in range(1,i+1):
EEEEE 4) print(chr(65+n-i),end=" ") ******
DDDD ******* 5) print("*",end=" ")
5) print() 6) print()
CCC ********
BB *********
A **********

Pattern-26:
Pattern-23:
1
JIHGFEDCBA
JIHGFEDCB 22
JIHGFEDC
JIHGFED 1) n=int(input("Enter the number of rows: ")) 333
JIHGFE 2) for i in range(1,n+1):
JIHGF 3) for j in range(1,n+2-i): 4444 1) n=int(input("Enter the number of rows: "))
JIHG 4) print(chr(65+n-j),end=" ") 2) for i in range(1,n+1):
JIH 5) print() 55555 3) print(" "*(n-i),(str(i)+" ")*i)
JI 4) print()
J 666666

Pattern-24: 7777777

88888888
*
** 999999999
***
**** 10 10 10 10 10 10 10 10 10 10
***** 1) n=int(input("Enter the number of rows: "))
****** 2) for i in range(1,n+1):
******* 3) print(" "*(n-i),"*"*i,end=" ")
******** 4) print()
*********
**********

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
186  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-27: Pattern-30:
1 *****
12 **** 1) n=int(input("Enter the number of rows: "))
1) n=int(input("Enter the number of rows: "))
123 *** 2) for i in range(1,n+1):
2) for i in range(1,n+1):
1234 ** 3) print(" "*(i-1),"* "*(n+1-i))
3) print(" "*(n-i),end="")
12345 4) for j in range(1,i+1): *

Pattern-31:
123456 5) print(j,end=" ")
1234567 6) print()
12345678
123456789 55555
1 2 3 4 5 6 7 8 9 10 4444 1) n=int(input("Enter the number of rows: "))
333 2) for i in range(1,n+1):
3) print(" "*(i-1),(str(n+1-i)+" ")*(n+1-i))
Pattern-28:
22
1

Pattern-32:
A

BB
12345 1) n=int(input("Enter the number of rows: "))
CCC 1234 2) for i in range(1,n+1):
1) n=int(input("Enter the number of rows: ")) 123 3) print(" "*(i-1),end="")
DDDD 2) for i in range(1,n+1): 12 4) for j in range(1,n+2-i):
3) print(" "*(n-i),(chr(64+i)+" ")*i) 1 5) print(j,end=" ")
EEEEE 4) print() 6) print()

FFFFFF
Pattern-33:
GGGGGGG
EEEEE
DDDD 1) n=int(input("Enter the number of rows: "))
HHHHHHHH
CCC 2) for i in range(1,n+1):
3) print(" "*(i-1),(str(chr(65+n-i))+" ")*(n+1-i))
Pattern-29:
BB
A
A
AB Pattern-34:
ABC
1) n=int(input("Enter the number of rows: ")) ABCDE
ABCD 1) n=int(input("Enter the number of rows: "))
2) for i in range(1,n+1): ABCD
ABCDE 2) for i in range(1,n+1):
3) print(" "*(n-i),end="") ABC
ABCDEF 3) print(" "*(i-1),end="")
4) for j in range(1,i+1): AB
ABCDEFG 4) for j in range(65,66+n-i):
5) print(chr(64+j),end=" ") A
ABCDEFGH 5) print(chr(j),end=" ")
6) print()
ABCDEFGHI 6) print()
ABCDEFGHIJ

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
188  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-35: Pattern-40:
1) n=int(input("Enter the number of rows: "))
* 1) n=int(input("Enter the number of rows: ")) 1 2) for i in range(1,n+1):
*** 2) for i in range(1,n+1): 321 3) print(" "*(n-i),end="")
***** 3) print(" "*(n-i),"* "*(2*i-1)) 54321 4) for j in range(2*i-1,0,-1):
******* 7654321 5) print(j,end=" ")
********* 987654321 6) print()

Pattern-36: Pattern-41:
1) n=int(input("Enter the number of rows: "))
1 A 2) for i in range(1,n+1):
222 1) n=int(input("Enter the number of rows: ")) ABC
2) for i in range(1,n+1): 3) print(" "*(n-i),end="")
33333 ABCDE 4) for j in range(65,65+2*i-1):
4444444 3) print(" "*(n-i),(str(i)+" ")*(2*i-1)) ABCDEFG 5) print(chr(j),end=" ")
555555555 ABCDEFGHI 6) print()

Pattern-42:
Pattern-37: 1) n=int(input("Enter the number of rows: "))
A 2) for i in range(1,n+1):
A CBA 3) print(" "*(n-i),end="")
BBB 1) n=int(input("Enter the number of rows: ")) EDCBA 4) for j in range(65+2*i-2,64,-1):
CCCCC 2) for i in range(1,n+1): GFEDCBA 5) print(chr(j),end=" ")
DDDDDDD 3) print(" "*(n-i),(str(chr(64+i)+" "))*(2*i-1)) IHGFEDCBA 6) print()
EEEEEEEEE

Pattern-43:
Pattern-38: 1) n=int(input("Enter the number of rows: "))
0 2) for i in range(1,n+1):
A 101 3) print(" "*(n-i),end="")
1) n=int(input("Enter the number of rows: "))
CCC 21012 4) for j in range(1,i):
2) for i in range(1,n+1):
EEEEE 3210123 5) print(i-j,end=" ")
3) print(" "*(n-i),(str(chr(64+2*i-1)+" "))*(2*i-1))
GGGGGGG 432101234 6) for k in range(0,i):
IIIIIIIII 7) print(k,end=" ")
8) print()

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 nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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: "))
Pattern-48: 1) num=int(input("Enter a number:"))
2) for i in range(1,n+1): 2) for i in range(1,num+1):
A ********* 3) print(" "*(i-1),end="")
3) print(" "*(n-i),end="")
BAB ******* 4) for j in range(1,num+2-i):
4) for j in range(1,i):
CBABC ***** 5) print("*",end=" ")
5) print(chr(i-j+65),end=" ")
DCBABCD *** 6) for k in range(1,num+1-i):
6) for k in range(0,i):
EDCBABCDE * 7) print("*",end=" ")
7) print(chr(k+65),end=" ")
8) print() 8) print()

Pattern-49: 1) num=int(input("Enter a number:"))


Pattern-45: 1) n=int(input("Enter the number of rows: "))
2) for i in range(1,n+1): 555555555
2) for i in range(1,num+1):
3) print(" "*(i-1),end="")
3) print(" "*(n-i),end="") 4444444 4) for j in range(0,num+1-i):
1 33333
4) for j in range(1,i+1): 5) print(num+1-i,end=" ")
121 222
5) print(j,end=" ") 6) for k in range(1,num+1-i):
12321 1
6) for k in range(i-1,0,-1): 7) print(num+1-i,end=" ")
1234321
7) print(k,end=" ") 8) print()
123454321
8) print()

Pattern-50: 1) num=int(input("Enter a number:"))


Pattern-46: 1) n=int(input("Enter the number of rows: "))
2) for i in range(1,num+1):
3) print(" "*(i-1),end="")
2) for i in range(1,n+1): 999999999 4) for j in range(0,num+1-i):
A 3) print(" "*(n-i),end="") 7777777 5) print(2*num+1-2*i,end=" ")
ABA 4) for j in range(1,i+1): 55555 6) for k in range(1,num+1-i):
ABCAB 5) print(chr(64+j),end=" ") 333 7) print(2*num+1-2*i,end=" ")
ABCDABC 6) for k in range(1,i): 1 8) print()
ABCDEABCD 7) print(chr(64+k),end=" ")
8) print()
Pattern-47:
1) n=int(input("Enter a number:"))
Pattern-51:
5 1) num=int(input("Enter a number:"))
2) for i in range(1,n+1):
54 1234567 2) for i in range(1,num+1):
3) print(" "*(n-i),end="")
543 12345 3) print(" "*(i-1),end="")
4) for j in range(1,i+1):
5432 123 4) for j in range(1,num+2-i):
5) print(n+1-j,end=" ")
54321 1 5) print(j,end=" ")
6) print()
6) for k in range(2,num+2-i):
7) print(num+k-i,end=" ")
8) print()

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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:")) Pattern-56:
1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
EEEEEEEEE * 2) for i in range(1,num+1):
3) print(" "*(i-1),end="")
DDDDDDD ** 3) print(" "*(num-i),end="")
4) for j in range(1,num+2-i):
CCCCC *** 4) for j in range(1,i+1):
5) print(chr(65+num-i),end=" ")
BBB **** 5) print("*",end=" ")
6) for k in range(2,num+2-i):
A ***** 6) print()
7) print(chr(65+num-i),end=" ")
**** 7) for k in range(1,num):
8) print()
*** 8) print(" "*k,end="")
** 9) for l in range(1,num+1-k):
* 10) print("*",end=" ")

Pattern-53:
11) print()
1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
3) print(" "*(i-1),end="")
I I I I I I I I I 4) for j in range(1,num+2-i):
1) num=int(input("Enter a number:"))
Pattern-57:
G G G G G G G 5) print(chr(65+2*num-2*i),end=" ")
E E E E E 2) for i in range(1,num+1):
6) for k in range(2,num+2-i):
C C C 3) print(" "*(num-i),end="")
7) print(chr(65+2*num-2*i),end=" ")
A 4 4) for j in range(1,i+1):
8) print()
43 5) print(num-j,end=" ")
432 6) print()
4321 7) for k in range(1,num):
1) num=int(input("Enter a number:"))
Pattern-54: 43210 8) print(" "*k,end="")
2) for i in range(1,num+1): 4321 9) for l in range(1,num+1-k):
3) print(" "*(i-1),end="") 432 10) print(num-l,end=" ")
ABCDEFG 4) for j in range(1,num+2-i): 43 11) print()
ABCDE 5) print(chr(64+j),end=" ") 4
ABC 6) for k in range(2,num+2-i):
A 7) print(chr(68+k-i),end=" ")
8) print()
1) num=int(input("Enter a number:"))
Pattern-58: 2) for i in range(1,num+1):
3) print(" "*(num-i),end="")
Pattern-55: 1) num=int(input("Enter a number:"))
2) for i in range(1,num+1): 3
4) for j in range(0,i):
5) print(num+j-i,end=" ")
3) print(" "*(num-i),end="") 23
1 6) print()
4) for j in range(1,i+1): 123
12 7) for k in range(1,num):
5) print(j,end=" ") 0123
123 8) print(" "*k,end="")
6) print() 123
1234 9) for l in range(1,num+1-k):
7) for k in range(1,num): 23
12345 10) print(l+k-1,end=" ")
8) print(" "*k,end="") 3
1234 11) print()
9) for l in range(1,num+1-k):
123 10) print(l,end=" ")
12 11) print()
1

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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:"))
Pattern-62:
2) for i in range(1,num+1):
E 4 1) num=int(input("Enter a number:"))
3) print(" "*(num-i),end="")
DE 4) for j in range(0,i): 34 2) for i in range(1,num+1):
CDE 5) print(chr(65+num+j-i),end=" ") 234 3) for j in range(1,i+1):
BCDE 6) print() 1234 4) print(num-i+j-1,end=" ")
ABCDE 7) for k in range(1,num): 01234 5) print()
BCDE 8) print(" "*k,end="") 1234 6) for a in range(1,num+1):
CDE 9) for l in range(0,num-k): 234 7) for k in range(0,num-a):
DE 10) print(chr(65+k+l),end=" ") 34 8) print(k+a,end=" ")
E 11) print() 4 9) print()

Pattern-60: Pattern-63:
1) num=int(input("Enter a number:"))
* E 1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
** DD 2) for i in range(1,num+1):
3) for j in range(1,i+1):
*** CCC 3) for j in range(1,i+1):
4) print("*",end=" ")
**** BBBB 4) print(chr(65+num-i),end=" ")
5) print()
***** AAAAA 5) print()
6) for a in range(1,num+1):
**** BBBB 6) for a in range(1,num+1):
7) for k in range(1,num+1-a):
*** CCC 7) for k in range(0,num-a):
8) print("*",end=" ")
** DD 8) print(chr(65+a),end=" ")
9) print()
* E 9) print()

Pattern-61: Pattern-64:
4 1) num=int(input("Enter a number:")) E 1) for i in range(1,num+1):
43 2) for i in range(1,num+1): ED 2) for j in range(1,i+1):
432 3) for j in range(1,i+1): EDC 3) print(chr(65+num-j),end=" ")
4321 4) print(num-j,end=" ") EDCB 4) print()
43210 5) print() EDCBA 5) for a in range(1,num+1):
4321 6) for a in range(1,num+1): EDCB 6) for k in range(num-a,0,-1):
432 7) for k in range(1,num+1-a): EDC 7) print(chr(64+k+a),end=" ")
43 8) print(num-k,end=" ") ED 8) print()
4 9) print() E 9) num=int(input("Enter a number:"))

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
196  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pattern-65: Pattern-69:
1) num=int(input("Enter a number:"))
E 1) num=int(input("Enter a number:")) A 2) for i in range(1,num+1):
DE 2) for i in range(1,num+1): BB 3) print(" "*(num-i),end="")
CDE 3) for j in range(1,i+1): CCC 4) for j in range(1,1+i):
BCDE 4) print(chr(64+num-i+j),end=" ") DDDD 5) print(chr(64+i),end=" ")
ABCDE 5) print() EEEEE 6) print()
BCDE 6) for a in range(1,num+1):
CDE 7) for k in range(1,num-a+1):
DE
E
8)
9)
print(chr(64+k+a),end=" ")
print() Pattern-70: 1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
A 3) print(" "*(num-i),end="")

Pattern-66:
AB 4) for j in range(1,1+i):
ABC 5) print(chr(64+j),end=" ")
1) num=int(input("Enter a number:"))
ABCD 6) print()
2) for i in range(1,num+1):
* ABCDE
3) print(" "*(num-i),end="")
**
4) for j in range(1,i+1):
***
5) print("*",end=" ")
****
*****
6) print() Pattern-71:
1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
*****
3) print(" "*(i-1),end="")
Pattern-67:
****
4) for j in range(1,num+2-i):
***
1) num=int(input("Enter a number:")) 5) print("*",end=" ")
**
2) for i in range(1,num+1): 6) print()
1 *
22 3) print(" "*(num-i),end="")
333 4) for j in range(1,i+1):

Pattern-72:
4444 5) print(i,end=" ")
55555 6) print()
1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
55555
3) print(" "*(i-1),end="")
Pattern-68:
4444
4) for j in range(1,num+2-i):
333
5) print(num-i+1,end=" ")
22
6) print()
1 1) num=int(input("Enter a number:")) 1

Pattern-73:
12 2) for i in range(1,num+1):
123 3) print(" "*(num-i),end="")
1234 4) for j in range(1,1+i): 1) num=int(input("Enter a number:"))
12345 5) print(j,end=" ") 54321 2) for i in range(1,num+1):
6) print() 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 nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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:"))
Pattern-78: 1) num=int(input("Enter a number:"))
2) for i in range(1,num+1): 2) for i in range(1,num+1):
EEEEE 3) print(" "*(i-1),end="") 1
3) print(" "*(num-i),end="")
DDDD 4) for j in range(1,num+2-i): 22
4) for j in range(1,i+1):
CCC 5) print(chr(65+num-i),end=" ") 333
5) print(i,end=" ")
BB 6) print() 4444
6) print()
A 55555
7) for p in range(1,num):
Pattern-75:
4444
8) print(" "*p,end="")
333
1) num=int(input("Enter a number:")) 9) for q in range(1,num+1-p):
22
2) for i in range(1,num+1): 10) print(num-p,end=" ")
EDCBA 1
11) print()
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() 1) num=int(input("Enter a number:"))
Pattern-79: 2) for i in range(1,num+1):
3) print(" "*(num-i),end="")
Pattern-76: 1) num=int(input("Enter a number:")) 1
4)
5)
for j in range(1,i+1):
print(j,end=" ")
2) for i in range(1,num+1): 12
6) print()
ABCDE 3) print(" "*(i-1),end="") 123
7) for p in range(1,num):
ABCD 4) for j in range(1,num+2-i): 1234
8) print(" "*p,end="")
ABC 5) print(chr(64+j),end=" ") 12345
9) for q in range(1,num+1-p):
AB 6) print() 2345
10) print(q+p,end=" ")
A 345
11) print()
45
5

Pattern-77: 1) num=int(input("Enter a number:"))


2) for i in range(1,num+1):
3) print(" "*(num-i),end="")
1) num=int(input("Enter a number:"))
Pattern-80:
* 4) for j in range(1,i+1):
* * 2) for i in range(1,num+1):
5) print("*",end=" ")
* * * 3) print(" "*(num-i),end="")
6) print()
* * * * 1 4) for j in range(1,i+1):
7) for p in range(1,num):
* * * * * 12 5) print(j,end=" ")
8) print(" "*p,end="")
* * * * 123 6) print()
9) for q in range(1,num+1-p):
* * * 1234 7) for p in range(1,num):
10) print("*",end=" ")
* * 12345 8) print(" "*p,end="")
11) print()
* 1234 9) for q in range(1,num+1-p):
123 10) print(q,end=" ")
12 11) print()
1

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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:")) Pattern-84: 1) while True:
2) for i in range(1,num+1): 2) n=int(input("Enter a number:"))
A 3) print(" "*(num-i),end="") 5 3) for i in range(1,n+1):
BB 4) for j in range(1,i+1): 545 4) print(" "*(n-i),end="")
CCC 5) print(chr(64+i),end=" ") 54345 5) for j in range(1,i+1):
DDDD 6) print() 5432345 6) print(n+1-j,end=" ")
EEEEE 7) for p in range(1,num): 543212345 7) for k in range(2,i+1):
DDDD 8) print(" "*p,end="") 5432345 8) print(n-i+k,end=" ")
CCC 9) for q in range(1,num+1-p): 54345 9) print()
BB 10) print(chr(64+num-p),end=" ") 545 10) for i in range(1,n+1):
A 11) print() 5 11) print(" "*i,end="")
12) for j in range(1,n+1-i):
13) print(n+1-j,end=" ")

Pattern-82: 1) num=int(input("Enter a number:")) 14) for k in range(2,n+1-i):


2) for i in range(1,num+1): 15) print(i+k,end=" ")
3) print(" "*(num-i),end="") 16) print()
A 4) for j in range(1,i+1):
AB 5) print(chr(64+j),end=" ")
ABC 6) print() 1) num=int(input("Enter a number:"))
ABCD
ABCDE
7) for p in range(1,num): Pattern-85: 2) for i in range(1,num+1):
3) print(" "*(num-i),end="")
8) print(" "*p,end="")
BCDE 9) for q in range(1,num+1-p): 4) for j in range(i,i+1):
CDE * 5) print("*",end=" ")
10) print(chr(64+q+p),end=" ")
DE ** 6) if i>=2:
11) print()
E * * 7) print(" "*(2*i-4),end="")
* * 8) for k in range(i,i+1):
* * 9) print("*",end=" ")
1) n=int(input("Enter a number:")) 10) print()
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=" ") 1) num=int(input("Enter a number:"))
5 2) for i in range(1,num+1):
6) for k in range(2,i+1):
454
34543
7) print(n+1-k,end=" ") Pattern-86: 3) print(" "*(num-i),end="")
8) print() 4) for j in range(i,i+1):
2345432 5) print(i,end=" ")
123454321 9) for i in range(1,n+1): 1
10) print(" "*i,end="") 6) if i>=2:
2345432 22
11) for j in range(1+i,n+1): 7) print(" "*(2*i-4),end="")
34543 3 3
12) print(j,end=" ") 8) for k in range(i,i+1):
454 4 4
13) for k in range(2,n+1-i): 9) print(i,end=" ")
5 5 5
14) print(n+1-k,end=" ") 10) print()
15) print()

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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:")) Pattern-90: 1) num=int(input("Enter a number:"))
2) for i in range(1,num+1):
2) for i in range(1,num+1):
3) print(" "*(i-1),end="")
5 3) print(" "*(num-i),end="") * *
4) for j in range(i,i+1):
44 4) for j in range(i,i+1): * *
5) print("*",end=" ")
3 3 5) print(num+1-i,end=" ") * *
6) if i<=4:
2 2 6) if i>=2: **
7) print(" "*(2*num-2*i-2),end="")
1 1 7) print(" "*(2*i-4),end="") *
8) for k in range(i,i+1):
8) for k in range(i,i+1):
9) print("*",end=" ")
9) print(num+1-i,end=" ")
10) print()
10) print()

1) num=int(input("Enter a number:"))
1) num=int(input("Enter a number:"))
Pattern-88: Pattern-91:
2) for i in range(1,num+1):
2) for i in range(1,num+1):
3) print(" "*(i-1),end="")
3) print(" "*(num-i),end="")
4) for j in range(i,i+1):
4) for j in range(i,i+1):
E 1 1 5) print(i,end=" ")
5) print(chr(64+num+1-i),end=" ")
DD 2 2 6) if i<num:
6) if i>=2:
C C 3 3 7) print(" "*(2*num-2*i-2),end="")
7) print(" "*(2*i-4),end="")
B B 44 8) for k in range(i,i+1):
8) for k in range(i,i+1):
A A 5 9) print(i,end=" ")
9) print(chr(64+num+1-i),end=" ")
10) print()
10) print()

1) num=int(input("Enter a number:"))
Pattern-92:
1) num=int(input("Enter a number:")) 2) for i in range(1,num+1):
2) for i in range(1,num+1): 3) print(" "*(i-1),end="")
Pattern-89:
3) print(" "*(num-i),end="") 4) for j in range(i,i+1):
4) for j in range(i,i+1): 5 5 5) print(num-i+1,end=" ")
5) print(chr(64+i),end=" ") 4 4 6) if i<=4:
A 6) if i>=2: 3 3 7) print(" "*(2*num-2*i-2),end="")
BB 7) print(" "*(2*i-4),end="") 22 8) for k in range(i,i+1):
C C 8) for k in range(i,i+1): 1 9) print(num-i+1,end=" ")
D D 9) print(chr(64+i),end=" ") 10) print()
E E 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 nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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:")) Pattern-98:
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): ** 1) num=int(input("Enter a number:"))
C C 5) print(chr(64+i),end=" ") *** 2) for i in range(1,num+1):
DD 6) if i<=4: **** 3) print(" "*(2*num-i+3),end="")
E 7) print(" "*(2*num-2*i-2),end="") *** 4) for j in range(1,i+1):
8) for k in range(i,i+1): **** 5) print("*",end=" ")
9) print(chr(64+i),end=" ") ***** 6) print()
10) print() ****** 7) for i in range(1,num+3):
******* 8) print(" "*(2*num-i+1),end="")
Pattern-95: ********
****
9) for j in range(-1,i+1):
1) num=int(input("Enter a number:")) 10) print("*",end=" ")
2) for i in range(1,num+1): ***** 11) print()
***** ******
3) print(" "*(i-1),end="") 12) for i in range(1,num+5):
***** *******
4) for j in range(1,num+1): 13) print(" "*(2*num-i),end="")
***** ********
5) print("*",end=" ") 14) for j in range(-2,i+1):
***** *********
6) print() 15) print("*",end=" ")
***** ********** 16) print()
*********** 17) for i in range(1,num+3):
*** 18) print(" "*((2*num)),end="")
1) num=int(input("Enter a number:")) *** 19) print("* "*3)
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-99: 1) num=int(input("Enter a number"))
2) for i in range(1,num+1):
3) print(" "*(2*num-i),end="")
*
4) for j in range(1,i+1):
Pattern-97: **
***
5) print("*",end=" ")
1) n=int(input("Enter a number:")) 6) print()
****
1 2) for i in range(1,n+1): 7) for i in range(1,num+1):
*****
01 3) for j in range(1,i+1): 8) print(" "*(num-i),end="")
* *
101 4) if (i%2!=0 and j%2!=0 )or(i%2==0 and j%2==0): 9) for j in range(1,i+1):
** **
0101 5) print("1",end=" ") 10) print("*",end=" ")
*** ***
10101 6) else: 11) print(" "*(num-i),end="")
**** ****
010101 7) print("0",end=" ") 12) for k in range(1,i+1):
**********
1010101 8) print() 13) print("*",end=" ")
14) print()

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, 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
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) ********
*********
**********
***********
************
*************
**************
***
***
***
***
***
***
***
***

D D
U U
R R
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, G DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, G
207  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy