0% found this document useful (0 votes)
0 views126 pages

Corepythonnew PDF

Python is a high-level, general-purpose programming language created by Guido Van Rossum and released in 1991, known for its simplicity and readability. It supports multiple programming paradigms, including procedural and object-oriented programming, and is widely used in various applications such as web development, data analysis, and machine learning. Python's dynamic typing, extensive libraries, and platform independence make it a popular choice among developers, despite some limitations in performance and mobile application development.
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)
0 views126 pages

Corepythonnew PDF

Python is a high-level, general-purpose programming language created by Guido Van Rossum and released in 1991, known for its simplicity and readability. It supports multiple programming paradigms, including procedural and object-oriented programming, and is widely used in various applications such as web development, data analysis, and machine learning. Python's dynamic typing, extensive libraries, and platform independence make it a popular choice among developers, despite some limitations in performance and mobile application development.
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/ 126

Core-PYTHON

Introduction:
 Python is a general-purpose high-level programming language.
 Python was developed by Guido Van Rossam in 1989 while working in National Research
Institute at Netherlands.
 But officially Python was made available to public in 1991. The Official Data Of Birth for Python
is: Feb 20th 1991.
 Python is recommended as first programming Language for beginners.
Eg-1:To Print Hello world

Java:
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}

C:

#include <stdio.h>
#include <conio.h>
void main()
{clrscr();
printf("Hello, world\n");
getch();
}

Python:
print("Hello World")
Eg-2: To print the sum of 2 numbers

Java:
public class Add
{
public static void main(String[] args)
{int a,b;
a=10;
b=20;
System.out.println("The Sum:"+(a+b));
}
}

C:
#include <stdio.h>
#include <conio.h>
void main()
{int a,b;clrscr();
a=10;
b=20;
printf("The Sum:%d",(a+b));
getch();
}

Python:
a=10
b=20
print("The sum=",(a+b))

The name Python was selected from the TV show


“The Complete Monty Python’s Circus”, which was broadcasted in BBC from 1969 to 1974.

Guido developed Python Language by taking almost all Programming Features from different
Languages

1. Functional Programming Features from C


2. Object Oriented Programming Features from C++
3. Scripting Language Features from Perl and Shell Script
4. Modular Programming Features from Modula-3

Most of syntaxes In Python Derived from C and ABC languages.

Where we can use Python:


We can use everywhere. The Important application areas are
1. For Developing Desktop Applications
2. For Developing web Applications
3. For Developing database Applications
4. For Networking Programming
5. For Developing Games
6. For Data Analysis Applications
7. For Machine Learning
8. For Developing Artificial Intelligence Applications
….

Notes:
Internally Google and Youtube use Python Coding.
NASA and Network Stock Exchange Applications developed by Python.
Top Software companies like Google, Microsoft, IBM, Yahoo using Python.

Features of Python:

1) Simple and easy to learn:


 Python is a simple Programming Language. When we read Python program, we can feed
like reading English statements.
 The Syntaxes are very simple and only 30+ keywords are available.
 When compared with other Languages, we can write programs with very less number of
lines. Hence more readability and simplicity.
 We can reduce development and cost of the project.

2) Freeware and Open Source:


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

3) High Level Programming Language:


 Python is High level Programming Language Hence it is programming Friendly Language.
 Being a programmer, we are not required to concentrate low level activities like memory
management and security etc.

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

5) Portability:
 Python programs are portable. Ie we can migrate from one platform to another platform very
easily. Python programs will provide same result on any platform.

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

7) Both Procedure Oriented and Object Oriented:


 Python Language Supports both procedure oriented (like C, Pascal etc) and Object Oriented
(like C++, Java) features. Hence, we can get benefits of both like security and reusability etc.

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

9) Extensible:
 We can use other language programs in Python.
 The main advantages of this approach are:
 We can use already existing legacy non-Python code
 We can improve performance of the application

10) Embedded:
 We can use Python programs in any other Language Programs.
 i.e. we can embed Python programs anywhere.

11) Extensive Library:


 Python has a rich inbuilt library.
 Being a programmer, we can use this library directly and we are not responsible to
implement the functionality. Etc

Limitations of Python:
1) Performance wise not up to the mark because it is interpreted language.
2) Not using for mobile Applications
3) Not using for Enterprises Applications(Banking and Telecom Applications)
4) To develop the Machine Learning Application Python is the best choice
Numpy(mathematics library),pandas(import dataset library), mat plot library(for import graph
chart....) all these modules are developing the ML, Python Library are available.
5) Performance is low because Python is a interpreted Application.Overtake this problem JIT
Compiler is added to PVM
JITCOMPILER+PVM---PYPY Flavour (Python for speed)

Flavours of Python:

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

Python Flavours:

 Python 1.0V introduced in Jan 1994


 Python 2.0V introduced in October 2000
 Python 3.0V introduced in December 2008

Note: Python 3 won’t provide backward compatibility to Python2 i.e. there is no guarantee that
Python2 programs will run in Python3.

Current Versions: Python 3.10.5 is Present In Python 2.7.13

IDENTIFIERS
A Name in Python Program is called Identifier.
It can be class Name OR Function Name OR Module Name OR Variable Name
Eg: a=10

Rules to define Identifiers in Python:

1. The only allowed characters in Python are


 Alphabet symbols (either lower case or upper case)
 Digits (0-9)
 Underscore symbol ( _ )
By mistake if we are using any other symbol like $ then we will get syntax error.
 Cash=10 (valid)
 Ca$h=20 (invalid)
2. Identifiers Should not starts with digit
 123total (invalid)
 total123 (valid)
3. Identifiers are case sensitive. Of course, Python language is case sensitive language.
 total =10
 TOTAL = 999
 print(total) #10
 print (TOTAL) #999

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

Q) Which of the following are valid Python Identifiers?


1) 123total (Invalid)
2) total123 (valid)
3) java2share (valid)
4) ca$h (Invalid)
5) _abc_abc_ (valid)
6) def (Invalid)
7) if (Invalid)

Note:
1) If Identifier starts with _ symbol then it indicates that it is private
2) If Identifier starts with __ (two underscore symbols) indicating that strongly private Identifier.
3) If the identifier starts and ends with two underscore symbols then the identifier is language
defined special name, which is also known as magic methods.
x = normal variable
_x = protected variable
__ x = private variable
__ x __= magic variable

Eg: __ add __

RESERVED WORDS
In Python some words are reserved to represent some meaning or functionality. Such type of words
are called reserved words.

These are 33 reserved words available in Python.


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

Note:
1) All Reserved words Python contains only alphabet symbols.
2) Except the following 3 reserved words, all contain only lower case alphabet symbols.
 True
 False
 None
Eg:
a=true (invalid)
a=True (valid)

>>> import keyword


>>>print(keyword.kwlist)
['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

DATA TYPES

 Data type represents the type of data present inside a variable.


 In Python we are not required to specify the type explicitly. Based on value provided, the
type will be assigned automatically. Hence Python is dynamically Typed Language.

Python contains the following inbuilt data types


1) Int
2) Float
3) Complex
4) Bool
5) Str
6) Byte
7) Bytearray
8) Range
9) List
10) Tuple
11) Set
12) Frozenset
13) Dict
14) None

Note: Python contains several in-built Functions

1) type() : to check the type of variable


2) id() : to get address of object
3) print() : to print the value

In Python everything is an Object.

1) int Data Type:


We can use int data type to represent whole numbers (integral values)
Eg: a=10
type(a) # int

Note:
 In Python2 we have long data type to represent very large integral values.
 But in Python3 there is no long type explicitly and we can represent long values also by
using int type only.

We can represent int values in the following ways


1) Decimal Form
2) Binary Form
3) Octal Form
4) Hexa Decimal Form

I) Decimal Form (Base -10):

 It is the default number system in Python


 The allowed digits are: 0 to 9
 Eg: a=10

II) Binary Form (Base -2):

 The allowed digits are: 0 & 1


 Literal value should be prefixed with 0b or 0B
 Eg: a = 0B1111
a = 0B123
a = b111(invalid)
III)Octal Form (Base -8):

 The allowed digits are: 0 to 7


 Literal value should be prefixed with 0o or 0O.
 Eg: a = 0o123
a = 0O786 (invalid)
IV)HexaDecimal Form (Base -16):

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

Base Conversions:

Python provide the following in-built functions for base conversions

1) bin():
We can use bin() to convert from any base to binary.

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

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

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

3) hex():
We can use hex () to convert from any base to hexa decimal.

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

2) Float Data Type:


 We can use float data type to represent floating point values(decimal values)
Eg: f= 1.234
type(f) #float
 We can also represent floating point values by using exponential form (Scientific Notation)
Eg: f=1.2e3  instead of ‘e’ we can use ‘E’
print(f) 1200.0

 The main advantage of exponential form is we can represent big values in less memory.

***Note:
We can represent int values in decimal, binary, octal and hexa decimal forms. But we can
represent float values only by using decimal form.

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

3) Complex Data Type:


 A Complex number is of the form

 ‘a’ and ‘b’ contain integers OR Floating Point Values.


Eg: 3+5j
10+ 5.5j
0.5+0.1j

 In the real part if we use int value then we can specify that either by decimal, octal, binary or
hexa decimal form.
 But Imaginary part should be specified only by using decimal form.

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

 Even we can perform operations on complex type values.

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

Note: Complex data type has some inbuilt attributes to retrieve the real part and imaginary part

>>> c=10.5+3.6j
>>>c.real
10.5
>>>c.imag
3.6
We can use complex type generally in scientific Applications and electrical engineering Applications.

4) bool Data Type:


 We can use this data type to represent Boolean values.
 The only allowed values for this data type are:
 True and False
 Internally Python represent True as 1 and False as 0
b = True
type(b) bool
Eg:
a =10
b = 20
c = a<b
print(c)  1

True + True  2
True – False  1

5) str Data Type:


 str represent String data type.
 A string is a sequence of characters enclosed within single quotes or double quotes.
 S1= ‘Naresh’
 S1=”Naresh”
 By using single quotes or double quotes we cannot represent multi line string literals.

 S1=”Nice
Computers”

 For this requirement we should for triple single quotes (''') or triple double quotes ( " " " )

s1='''nice
computer
education'''

 We can also use triple quotes to use single quotes or double quotes in our string.

'''this is " character'''


'This is " character '

We can embed one string in another string


'''This "Python class very helpful" for java students'''

Slicing of Strings:

1. Slice means a piece


2. [ ] operator is called slice operator, which can be used to retrieve parts of String.
3. In Python Strings follows zero based index.
4. The index can be either +ve or –ve.
5. +ve index means forward direction from Left to Right.
6. –ve index means backward direction from Right to Left

1) >>> s="navya"
2) >>>s[0]
3) 'n'
4) >>>s[1]
5) 'a'
6) >>>s[-1]
7) 'a'
8) >>>s[40]
9) IndexError: string index out of range

1) >>>s[1:40]
2) 'avya'
3) >>>s[1:]
4) 'avya'
5) >>>s[:4]
6) 'navy'
7) >>>s[:]
8) 'navya'
9) >>> s*3
10) 'navyanavyanavya'
11) >>>len(s)
12) 5

Note:
1) In python the following data types are considered as Fundamental Data types
 int
 float
 complex
 bool
 str
2) In Python, we can represent char values also by using str type and explicitly char type is not
available.
 >>> c='a'
 >>> type(c)
 <class 'str'>
3 ) Long Data type is available in Python2 but not in Python3. In Python3 long values also we can
represent by using int type only.
 In Python we can present char values also by using str Type and explicitly char Type is not
available.
TYPE CASTING
 We can convert one type value to another type. This conversion is called Typecasting or Type
coersion.
 The following are various inbuilt functions for type casting.
1) int()
2) float()
3) complex()
4) bool()
5) srt()
1. int():
We can use this function to convert values from other types to int

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

Note:

1) We can convert from any type to int except complex type


2) If we want to convert str type to int type, compulsory str should contain only integral value and
should be specified in base-10.

2. float():
We can use float() function to convert values from other type values to float type.

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

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

3. complex():
We can use complex() function to convert values from other type values 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:
>>>complex(10)
(10+0j)
>>>complex(10.5)
(10.5+0j)
>>>complex(True)
(1+0j)
>>>complex(False)
0j
>>>complex("10")
(10+0j)
>>>complex("10.5")
(10.5+0j)
>>> complex("ten")
ValueError: complex() arg is a malformed string
>>>
Form-2: complex(x,y)
We can use this method to convert x and y into complex number such that x will be real part y will
be imaginary part.

Eg:
>>>complex(10,-2)
(10-2j)
>>>complex(True,False)
(1+0j)
>>>

4. bool():
We can use this function to convert from other type values to bool type.

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

5. str():
We can use this function to convert from other type values to str type.
>>>str(10)
'10'
>>>str(10.5)
'10.5'
>>> str(10+5j)
'(10+5j)'
>>>str(True)
'True'
>>>

Fundamental Data Types vs Immutability:

 All Fundamental data types are Immutable. i.e once we creates an object, we cannot perform
any changes in that object. If we are trying to change then with those changes a new object will
be created. This non-changeable behaviour is called immutability.
 In Python if a new object is required, the PVM won’t create object immediately. First it will check
is any object available with the required content or not. If available then existing object will be
reused. If it is not available then only a new object will be created. The advantages of this
approach is memory utilization and performance will be improved.

 But the problem in this approach is, several references pointing to the same object, by using
one reference if we are allowed to change the content in the existing object then the remaining
references will be effected. To prevent this immutability concept is required. According to this
once creates an object we are not allowed to change content. If we are trying to change with
those changes a new object will be created.

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

6. Byte Data Type():


Byte data type represents a group of byte numbers just like an array.

1) >>> x=[10,20,30,40]
2) >>> b=bytes(x)
3) >>> type(b)
4) <class 'bytes'>
5) >>> print(b[0])
6) 10
7) >>> print(b[-1])
8) 40
9) >>> for i in b:
10) print(i)

output:
10
20
30
40

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

Conclusion 2:
Once we create bytes data type value, we cannot change its value, otherwise we will get TypeError.

>>> x=[10,20,30,40]
>>> b=bytes(x)
>>>b[0]=100
TypeError: 'bytes' object does not support item assignment
>>>

7. bytearray Data Type():


bytearray is exactly same as bytes data type except that its elements can be modified.

Eg:1
>>> x=[10,20,30,40]
>>> b=bytearray(x)
>>> for i in b:
print(i)
10
20
30
40
>>>b[0]
10
>>>b[0]=100
>>> for i in b:
print(i)

100
20
30
40
>>>
Eg:2
>>> x=[10,256]
>>> b=bytearray(x)
ValueError: byte must be in range(0, 256)
8. List Data Type():
If we want to represent a group of values as a single entity where insertion order required to
preserve and duplicates are allowed then we should go for list data type.

1) Insertion order is preserved


2) Heterogeneous Objects are allowed
3) Duplicates are allowed
4) Growable in nature
5) Values should be enclosed within square brackets.
Eg:
>>> list=[10,10.5,'naresh',True,10]
>>> print(list)
[10, 10.5, 'naresh', True, 10]

Eg:
>>> list=[10,10.5,'naresh',True,10]
>>> print(list)
[10, 10.5, 'naresh', True, 10]
>>>
>>> list=[10,20,30,40]
>>>list[0]
10
>>>list[-1]
40
>>>list[1:3]
[20, 30]
>>>list[0]=100
>>> for i in list:
print(i)

100
20
30
40
>>>
List is growable in nature, i.e based on our requirement we can increase or decrease the size.

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

Note: An ordered, mutable, heterogeneous collection of elements is nothing but list,where


duplicates also allowed.

9. Tuple Data Type():


Tuple daya type is exactly same as list data type except that it is immutable. i.e we cannot change
the values.
Tuple elements can be represented within parenthesis.

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

Note: Tuple is the read only version of list

10. Range Data Type():


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

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

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

Form-3:range(10,20,2)
2 means increment value
Eg:
r=range(10,20,2)
for i in r:print(i)-->10,12,14,16,18.

We can access elements present in the range Data Type by using index.

Eg:
r=range(10,20)
r[0] 10
r[15] Index error: range object index out of range

We cannot modify the values of range data type

Eg:
r[0] =100
Type error: ‘range’ object does not support item assignment
We can create a list of values with range data type

Eg:
l=list(range(10))
print(l)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

11. Set Data Type():


If we want to represents a group of values without duplicates where order is not important then we
should go for set Data Type.
1) Insertion order is not preserved
2) Duplicates are not allowed
3) Heterogeneous objects are allowed
4) Index concept is not applicable
5) It is mutable collection
6) Growable in nature
Eg:
>>> s={100,0,10,200,10,'naresh'}
>>> s
{0, 100, 'naresh', 200, 10}
>>>s[0]
TypeError: 'set' object is not subscriptable
>>>

Set is growable in nature, based on our requirement we can increase or decrease the size.
>>>s.add(60)
>>> s
{0, 100, 'naresh', 200, 10, 60}
>>>s.remove(100)
>>> s
{0, 'naresh', 200, 10, 60}
>>>

12. frozenset Data Type():


It is exactly same as set except that is immutable.
Hence we cannot use add or remove functions.

>>> s={10,20,30,40}
>>> fs=frozenset(s)
>>> type(s)
<class 'set'>
>>>type(fs)
<class 'frozenset'>
>>> fs
frozenset({40, 10, 20, 30})
>>> for i in fs:
print(i)

40
10
20
30
>>>fs.add(70)
AttributeError: 'frozenset' object has no attribute 'add'
>>>fs.remove(10)
AttributeError: 'frozenset' object has no attribute 'remove'
>>>
13. dict Data Type():
 If we want to represent a group of values as key-value pairs then we should go for dict data
type.

 Eg:d={101:'naresh',102:'ravi',103:'shiva'}

 Duplicate keys are not allowed but values can be duplicated. If we are trying to insert an entry
with duplicate key then old value will be replaced with new value.

Eg:
>>> d={101:'naresh',102:'ravi',103:'shiva'}
>>>d[101]='sunny'
>>> d
{101: 'sunny', 102: 'ravi', 103: 'shiva'}
>>> We can create empty dictionary as follows
>>> d={}
>>> We can add key-value pairs as follows
>>> d['a']='apple'
>>> d['b']='banana'
>>> print(d)
{'a': 'apple', 'b': 'banana'}
>>>
Note:dict is mutable and order won’t be preserved.

Note:
1) In general we can use bytes and bytearray data types to represent binary information like
images, video files etc
2) In python2 long data type is available. But is Python3 it is not available and we can represent
long values are also by using int type only.
3) In python there is no char data type. Hence we can represent char values also by using str
type.

Summary of Data Types in Python 3

Datatype Description Is Immutable? Example


Int We can use to Immutable >>>a=10
Represent the >>>type(a)
Whole / integral <class ‘int’>
Numbers
Float We can use to Immutable >>>b=10.5
Represent the >>>type(b)
Decimal / floating <class ‘float’>
Point numbers
Complex We can use to Immutable >>>c=10+5j
represent the >>>type(c )
Complex numbers <class ‘complex’>
>>>c.real
10.0
>>>c.imag
5.0
Bool We can use to Immutable >>>flag=True
Represent the >>>flag=Flase>>>type(flag)
logical <class ‘bool’>
Values(Only
allowed values
are True and
False
Str To represent Immutable >>>s=’Naresh;
sequence of >>>type(s)
Characters <class ‘str’>
>>>s=”Naresh”
>>>s=’’’Nice Software
solutions….Vijayawada’’’
>>>type(s)
<class ‘str’>
bytes To represent a Immutable >>>list=[1,2,3,4]
Sequence of byte >>>b=bytes(list)
Values from 0- >>>type(b)
255 <class ‘bytes’>
bytearray To represent a Mutable >>>list=[10,20,30]
Sequence of byte >>>ba=bytearray(list)
Values from 0- >>>type(ba)
255 <<<class ‘bytearray’>
range To represent a Immautable >>>r=range(10)
range of values >>>r1=range(0,10)
>>>r2=range(0,10,2)
list To represent an Mutable >>>l=[10,11,12,13,14,15]
Ordered collection >>>type(l)
of <class ‘list’>
Objects
tuple To represent an Immutable >>>t=(1,2,3,4,5)
Ordered collection >>>type(t)
of <class ‘tuple’>
Objects
set To represent an Mutable >>>s={1,2,3,4,5,6}
unordered >>>type(s)
collection of <class ‘set’>
Unique Objects
frozenset To represent an Immutable >>>s={11,2,3,’Naresh’,100,’Ramu’}
unordered >>>fs=frozenset(s)
collection of >>>type(fs)
Unique Objects <class ‘frozenset’>
dict To represent a Mutable >>>d={101:’Naresh’,102:’ramu’,103:’hari’}
group of key >>>type(d)
value pairs <class ‘dict’>

14. None Data Type():


 None means nothing or No value associated.
 If the value is not available, then to handle such type of cases None introduced.
 It is something like null value in java.

Escape Characters:
In string literals we can use escape characters to associate a special meaning.
>>> s="nice\nsoftware"
>>> print(s)
nice
software
>>> s="nice\tsoftware"
>>> print(s)
nice software
>>> s="This is " symbol"
SyntaxError: invalid syntax
>>> s="This is \" symbol "
>>> print(s)
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:
 Constant 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.

OPERATORS

 Operator is a symbol that performs certain operations.


 Python provides the following set of operations
 Types Of operators:

operators are 8 types


1)Arithmetic Operators
2)Relational operators or comparision operators
3)Logical operators
4)Bitwise Operators
5) Shift Operators
6)Assignment Operators
7)Ternary Operators (or) conditional operators:
8)Special Operators
a) identity operators
b) Member shift operators
1)Arithmetic Operators: + - * / % // **

+ ->plus (addition)
- ->minus (subtraction)
* ->star (multiplication)
/ ->forward slash (division)
% ->percentage (modulo operator)
// ->floor division (floor division)
** -> power (Exponent operator or power operator)

a=10
b=2

print("a+b=",a+b)
print("a-b=",a-b)
print("a*b=",a*b)
print("a/b=",a/b)
print("a//b=",a//b)
print("a%b=",a%b)
print("a**b=",a**b)

floor(before int)
12.3--12
13.6--13
15.7--15

ceil(next int)
ceil(12.3)--13
13.6--------14
15.7--------16

+ *
+ (addition + concatenation)
* (multiplication +repitation )

"naga" + "naresh"=naganaresh
"THOPULA"+"NARESH"=THOPULANARESH
"naga"+3--error

*
"naga"* 3==naganaganaga
"naga"*"naga"-error

2)Relational operators or comparision operators:- < <= > >=


main purpose of relational operators: condition checking

RELATIONAL OPERATIORS:-
> =GREATER THAN
< =LESSTHAN
>= =GREATERTHAN OR EQUAL TO
<= =LESSTHAN OR EQUAL TO
a=10
b=20
print("a>b =",a>b) -false
print("a>=b=",a>=b) -false
print("a<b=",a<b) -True
print("a<=b=",a<=b) -True

note: we can apply relational operators for string type also


a="naresh"
b="naresh"
a>b
a>=b
a<b
a<=b

print(True>True) -False
print(True>=True) -TRUE
print(10>True) -True
print(False>True) -False

10>'naresh' --it is not support

eg:

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

Note:
Chaining of relational operators is possible or not. IN the chaining, if all
comparisions returns True then only result is true.
if atleast one comparision returns false then the result is False.

10<20 -True
10<20<30 -True
10<20<30<40 -True
10<20<30<40>50 -False

-----------------------
Equality Operators: == , !=

we can apply these operators for any type even for incompatible type also
10==20 -False
10!=20 -True
10==True -False
Flase==False -True
'naresh'=='naresh' -True
10=='naresh' -False
Note: CHaining concepts is applicable or not for equality operators.
if atleast one comparision returns False then the result is False.
otherwise the resut is True

10==20==30==40 -False

10==10==10==10 -True

Logical Operators: and, or, not

we can apply for all types

for boolean Types Behaviour:


and-> if both arguments are true then only result is True
or-> if atleast one argument is true then only result is True
not-> complement

True and False ->False


True or False -> True
not False ->True

for non-boolean Types Behaviour:


0 means false
non-zero means True
empty string is always treated as False - ''

X and Y: IF X evaluates to false return x otherwise return y

10 and 20 -20
0 and 20 -0
10 and 0 -0
if first argument is zero then result is zero otherwise result is y

X or Y:
if x evaluates to true result is x otherwise result is y

10 or 20 -10
0 or 20 -20

not x:
if x evaluates to False result is true otherwise result is false

not 10 -False
not 0 -True

eg:
'naresh' and 'nicecompuetrs' =’nicecomputers’
"" and "naresh" =
"naresh" and "" =
"naresh" or "" =
"" or "naresh" =
not "" =
not "naresh" =

Bitwise Operators: & , |, ~ , ^ , << , >>

& => bitwise and


if both bits are 1 then only result is 1 other wise result is 0.

| => bitwise or
if atleast one bit is 1 then only result is 1 other wise result is 0.

^ => bitwise exclusive or


if both bits are different then only result is 1 other wise result is 0.

~ => bitwise not


bitwise complement operator

shift operators:
-------------------
<< => bitwise left shift
>> => bitwise right shift

we can apply these operators bitwise


these operators are applicable only for int and boolean types
by mistake if we are trying to apply for any other type then we will get error

print(10 and 20) ->20


print(10 or 20) ->10
print(not True) -> False

practice exercise:

print(10 & 20) ->


print(10 |20) ->
print(10 ^ 20) ->
print(~10) ->

boolean

print(True & False) ->False


print(True | False) ->True
print(True ^ False)->True
print(~True) ->-2
print(True<<2) ->4
print(True>>2) ->0
--------------------------------------------------------------------------
6)Assignment Operators: =,+=,-=,*=,/=,%=,//=,**=
we can use assignment operators to assign value to the variables.
simple assignment operator
eg:
x=20
we can combine assignment operator with some other operator to form
compound assingment operator
eg: a=a+10-> a+=10
a=a-10-> a-=10
a=a*10-> a*=10
a=a/10-> a/=10
a=a%10-> a%=10
a=a//10-> a//=10
a=a**10-> a**=10 if
a=a&10-> a&=10
a=a|10-> a|=10
a=a^10-> a^=10
a=a>>10-> a>>=10

eg:
x=10
x+=20 #x=x+20
print(x)

Ternary Operators Or Conditional Operators:

Syntax:
x= firstvalue if condition else secondvalue

eg:1
a,b=10,20

x=30 if a<b else 40


#30

eg:2

a,b=20,10
big= 40 if a>b else 30
print(big)

eg: read two numbers from the keyboard and print minimum value

#read two numbers from the keyboard and print minimum value
a=int(input("Enter First no:"))
b=int(input("Enter second no:"))
min=a if a<b else b
print("Minimum value=",min)

# program for minimum of 3 numbers


a=int(input("Enter First no:"))
b=int(input("Enter second no:"))
c=int(input("Enter Third No:"))

min=a if a<b and a<c else b if b<c else c


Special Operators:2 types

1.identity operators:

is
is not

is operator:
r1 is r2 it returns True if both r1 and r2 are pointing to the same object
r1 is not r2 it retuens True if both r1 and r2 are not pointing to same object

eg:
a=10
b=10
print(a is b)
True

a="naresh"
b="naresh"
print(id(a))
print(id(b))
print(a is b)
#true
print( a is not b)
#false

2.membership operators
in
not in

we can use membershift operators to check wheather the given object present
in the given collection.(it may be string,list,set,Tuple or dict)

in : returns True if the given object present in the specified collection


not in:returns True if the given object not present in the specified collection

eg:

s="hello learning python is ver easy!!!"


print('h'in s) => True
print('d' in s) => False
print('d' not in x) => True
print('python' in x) => True

eg:
list1=["sunny","bunny","chinny","pinny"]
print("sunny" in list1) =>True
print("tunny" on list1) => False
print("tunny" not in list1) => True
Operator Precedence:
If multiple operators present then which operator
will be evaluted first is decided by operator precedence

print(3+10*2)->23
print((3+10)*2)->26
BRADMAS

THE FOLLOWING LIST DESCRIBES OPERATOR PRECEDENCE IN PYTHON:


() ->PARENTHESIS
** ->Exponential Operator
~,- ->Bitwise operator,minus operator
*,/,%,//->Multiplication,forward slash,percentage,floor division
+,- -> addition,subtraction
<<,>> ->left shift and right shift
& ->Bitwise and
^ ->Bitewise x-or
| -> bitwise or
>,>=,<,<=,==,!= ->relational operators
is,isnot ->Identity Operators
in,not in ->membership operators
not ->Logical not
and ->logical and
or -> logical or

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

=>3/2*4+3+(10/5)**3-2
=>3/2*4+3+2**3-2
=>3/2*4+3+8-2
=>1.5*4+3+8-2
=>6.0+3+8-2
=>17-2
=>15.0

Mathematical Functions (math module)


A module is collection of functions, variables, classes etc.
math is a module that contains several functions to perform mathematical operations
If we want to use any module in python, first we have to import that module
import math
once we import a module then we can call any function of that module
import math
print(math.sqrt(16))
print(math.pi)

we can create alias name by using keyword. import math as m


once we create alias name , by using that we can access functions and variables
of that module

import math as m
print(m.sqrt(16))
print(m.pi)

we can import a particular member of a module explicitly as follows

from math import sqrt,pi


print(sqrt(16))
print(pi)

Important functions of math module:-

ceil(x)
floor(x)
pow(x,y)
factorial(x)
trunc(x)
gcd(x,y)
sin(x)
cos(x)
tan(x)...etc

Import Variables of math Module:


pi 3.14159
e->2.71
inf-> infinity
nan-> not a number

write a pyhon program to find Area of circle

form math import pi


r=16
print("Area of circle is:",pi*r**2)

area of the circle: 804

INPUT AND OUTPUT STATEMENTS:-


Reading dynamic input from the keyboard:

In python 2 the following 2 functions are available to read dynamic input


from the keyboard
1)raw_input()
2)input()

1) raw_input():
This function always read the data from the keyboard in the form of string format.
we have to convert the string type to our required type by using the corresponding
type casting methods.

eg: x=raw_input("ENter First Number");

print(type(x)) -> it will always print str type only for any input type

2) input():
input() function can be used to read data directly in our required format.
we are not required to perform type casting.

x=input("Enter value:")
type(x)

10->int
"naresh"-> str
10.5-> float
True-> bool

Note:
But in python 3 we have only input() method and raw_input() method
is not available.
python 3 input() method behaviour exactly same as raw_inpu() method of python 2.
i.e every input value is treated as str type only.
raw_input() function of python 2 is renamed as input() method in python 3.

type(input("ENter first no:"))

q) write a program to read 2 numbers from the keyboard and print sum

x=int(input("Enter First no:"))


y=int(input("Enter second no:"))
print("sum=",x+y)

o/p:
Enter first no:100
Enter second no:200
sum=300

q)single line sum:


print("sum=",int(input("Enter First no:"))+int(input("Enter Second no:")))

Q) write a program to read Employee Data from the Keyboard and print that
data

eno=int(input("Enter Employee no:"))


ename=input("Enter Employee Name:")
esal=float(input("Enter Employee Salary:"))
eaddr=input("ENnter Employee Address:")
married=bool(input("Employee Married? [True|Flase]:"))

print("Please confirm information")


print("Employee No:",eno)
print("Employee Name:",ename)
print("Employee Salary:",esal)
print("Employee Address:",eaddr)
print("Employee Married?:",married)

How to read multiple values from the keyboard in a single line:

a,b=[int(x) for x in input("Enter any 2 no:").split()]


print("sum=",a+b)

eg-2
a,b,c,d=[int(x) for x in input("Enter any 4 no:").split()]
print("sum=",a+b+c+d)

Q) write a program to read 3 float numbers from the keyboard


with , saperator and print their sum?

a,b,c=[float(x) for x in input("enter 3 float numbers:").split(',')]


print("the sum:",a+b+c)

-------------------------------------------------------------------------
eval():
eval function take a String and evalute the result

eg:
x=eval("10+20+30")
print(x)

eval() can evaluate the input to list,tuple,set....etc.based thr provide input

Eg:
l=eval(input("Enter list:")
print(type(l))
print(l)

Command line arguments:


----------------------
argv is not array it is a list. it is available sys module.
The arguments which are passing at the time of execution are called
commandline arguments.

eg: d:\python>py test.py 10 20 30

within the python program this commandline arguments are available in argv.
which is present in sys module
test.py 10 20 30

Note: argv[0] represent Name of program. but not first commandline argument
argv[1] represent first commandline argument

program:write a program to display command line arguments?

from sys import argv


print("The number of commandline Arguments:",len(argv))
print("the list of command line arguments:",argv)
print("command line arguments one by one:")
for x in argv:
print(x)

-------------------
from sys import argv

sum=0
args=argv[1:]
for x in args:
n=int(x)
sum=sum+n
print("total sum=",sum)

Note1:
Usually space is seperator between commandline arguments.
if our commandline arguments its self contains space then we should
enclose within double quotes

from sys import argv


print(argv[1])

E:\DIVYA>py test.py naga naresh


naga

E:\DIVYA>py test.py "naga naresh"


naga naresh

Note2:
within the python program command line arguments are available
in the string form. based on our requirement, we can convert into
corresponding type by using type casting method.

from sys import argv


print(argv[1]+argv[2]))

E:\DIVYA>py test.py 10 20
1020

from sys import argv


print(int(argv[1])+int(argv[2])))
E:\DIVYA>py test.py 10 20
30

Note3:
if we are trying to access command line arguments with out of range index
then we will get Error

from sys import argv


print(argv[100])

IndexError: list index out of range

Output Statements:

we can print() function to display output

form-1: print() without any argument


just it prints new line character

eg:
print("Nice Computers")
print()
print("Hello world")

form-2:

print(String):
print("Hello world")

we can use escape sequence characters also \n \t

print("Hello \n world")
print("Hello \t world")

we can use repetetion operator (*) in the string


print(10 *"Hello")
print("Hello"*10)

we can use repetetion operator (+) in the string


print("Nice"+"Computers")
print("nice","computers")

form3:
print() with variable number of arguments

a,b,c=10,20,30
print("the values are:",a,b,c)

output is: the values are: 10 20 30


by default output values are seperated by space. if we want we can specify seperatror
by using "sep" attribute.

a,b,c=10,20,30
print(a,b,c,sep=',')

a,b,c=10,20,30
print(a,b,c,sep=',')
print(a,b,c,sep=':')
print(a,b,c,sep='@')

form4:
print() with end attribute

print("Hello")
print("Nice")
print("soft")

eg:
print("Hello",end=' ')
print("Nice",end=' ')
print("soft")

Note: the default value for end attribute is \n , which is nothing but
new line character

form:5
print(object) statement
we can pass any objects(like list,tuple,set etc) as argument to the print()
statement

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

form:6
print(String,Variable list)

we can use print() statement with String and any number of arguments

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

output:
Hello Naresh Your age is 32
Your are teaching java and python
Form:7
print(Formating string)
1) %i ->int
2) %d ->int
3) %f ->float
4) %s ->String type
Syntax: print("Formating string" %(variable list))
a=10
b=20
c=30
print("a value is %i" %a)
print("b value is %d and c value is %d" %(b,c))

eg:2
s="naresh"
list=[10,20,30,40]
print("Hello %s....the list of items are %s" %(s,list))
Hello naresh....the list of items are [10, 20, 30, 40]

form:8
print() with replacement operator {}

name="naresh"
salary=10000
gf="Python"
print("hello {x} your salary is {y} and your friend {z} is waiting" .format(x=name,y=salary,z=gf)

Flow Controls:
--------------
flow controls describes the order in which statements will be executed at runtime

1)conditional control satements:

1) if
syntax:

if condition :statement

or

if condition:
statement1
statement2
statement3

2)if-else:

if condition:
statement
else:
statement

3)if-elif-else:

if condition1:
statement
elif condition2:
statement
elif condtion3:
statement3
----
-----
else:
default statement

1)if condition: if condition is true then statement will be executed

if condition:
statement1
statement2
statement3

name=input("ENter Name:")
if name=="naresh":
print("Hello naresh good morning")
print("How r u!!!")

2)if-else:

if condition:
statement
else:
statement

note:if condition is true action1 will be executed otherwize action2 will


be executed

eg:1

name=input("Enter name:")
if name=="naresh":
print("Hello naresh Good morning")
else:
print("Orey good morning")
print("How r u")
3)if-elif-else:

if condition1:
statement
elif condition2:
statement
elif condtion3:
statement3
----
-----
else:
default statement

EG:
brand=input("Enter your favourite Brand:")
if brand=="RC":
print("It is Children brand")
elif brand=="KF":
print("It is not much kick")
elif brand=="FO":
print("Buy one get one offer")
else:
print("Other Brands are not required")

EG:4

#Write a program to find biggest of 2 no from the command prompt

n1=int(input("Enter first Number:"))


n2=int(input("Enter Second Number:"))

if n1==n2:
print("both are equal")
elif n1>n2:
print("Biggest no is:",n1)
else:
print("Biggest no is:",n2)

eg:
#Write a program to find Smallest of 2 no from the command prompt

n1=int(input("Enter first Number:"))


n2=int(input("Enter Second Number:"))

if n1==n2:
print("both are equal")
elif n1<n2:
print("smallest no is:",n1)
else:
print("smallest no is:",n2)
eg:
#Write a program to find biggest of 3 no from the command prompt

n1=int(input("Enter first Number:"))


n2=int(input("Enter Second Number:"))
n3=int(input("Enter Third Number:"))

if n1==n2 and n1==n3:


print("all are equal")
elif n1>n2 and n1>n3:
print("biggest no is:",n1)
elif n2>n3:
print("biggest no is:",n2)
else:
print("Biggest no is:",n3)

write a program to check whether the given Number is in between


1 to 100?

n=int(input("Enter number"))
if n>=1 and n<=100:
print("The number",n,"is in between 1 to 100")
else:
print("the number",n,"is not in between 1 to 100")

#write a program to take a single digit number from the keyboard


#and print is value in English word

n=int(input("Enter a digit from 0 to 9:"))


if n==0:
print("zero")
elif n==1:
print("One")
elif n==2:
print("Two")
elif n==3:
print("Three")
elif n==4:
print("Four")
elif n==5:
print("Five")
elif n==6:
print("Six")
elif n==7:
print("Seven")
elif n==8:
print("Eight")
elif n==9:
print("Nine")
else:
print("plz enter a number from 0 to 9 only")
II ITERATIVE STATEMENTS:

if we want to execute a group of statements multiple times then we should go


for iterative statements

python supoorts 2 types of Iterative statements


1) for loop
2) while loop

1) for loop:
if we want to execute some action for every element present in the some sequence
(it may be string or collection) then we should for
for loop

syntax:
for x in sequence:
body

where sequence can be string or any collection(list or tuple or set etc)


Body will be executed for every element present in the sequence

eg:1
for x in range(10):
print(x)

o/p:0 1 2 3 4 5 6 7 8 9

eg:2
s="naga naresh"
for x in s:
print(x)
o/p:
n
a
g
a

n
a
r
e
s
h

Eg:3
To Print characters present in string index wize

s=input("Enter a string:")
i=0
for x in s:
print("the characters present at ",i,"index is:",x)
i=i+1

eg:3
to print hello 10 times

for x in range(10):
print("Hello")

eg:4
to display numbers from 0 to 10

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

eg:5
# to display odd numbers from 0 to 20
for x in range(21):
if x%2==1:
print(x)
eg:6
# to display even numbers from 0 to 20
for x in range(21):
if x%2==0:
print(x)

eg:7
# to display numbers from 10 to 1 in descending order
for x in range(10,0,-1):
print(x)

eg:8
#to print sum of numbers present inside list

list=eval(input("ENter a list"))
sum=0
for x in list:
sum=sum+x
print("The sum=",sum)

while loop:
-----------
If we want to execute a group of statements iteratively until some condition false,
then we should go forwhile loop

Syntax:
while condition:
body

eg:
to print numbers from 1 to 10 by using while loop
x=1
while x<=10:
print(x)
x+=1

eg:
#to display the sum of first n numbers
n=int(input("Enter n Value:"))
sum=0
i=1
while i<=n:
x=int(input("ENTER A NO:"))
sum=sum+x
i=i+1
print("the sum=",sum)

eg:Write a program to prompt user to enter some name until entering Naresh

name=""
while name!="Naresh":
name=input("ENter Name:")
print("Thanks for confirmation")

Infinite loops:
---------------
i=0
while True:
i=i+1
print("Hello",i)

Nested Loops:
Some times we can take a loop inside another loop , which are known as nested loops

for i in range(4):
for j in range(4):
print(i,"....",j)
o/p:

0 .... 0
0 .... 1
0 .... 2
0 .... 3
1 .... 0
1 .... 1
1 .... 2
1 .... 3
2 .... 0
2 .... 1
2 .... 2
2 .... 3
3 .... 0
3 .... 1
3 .... 2
3 .... 3

write a program to display *'s in Pyramid style


also known as Equilent Traiangle

*
* *
* * *
* * * *
* * * * *

n=int(input("Enter number of rows:"))


for i in range(1,n+1):
print(" "*(n-i),end="")
print("* "*i)

III TRANSFER STATEMENTS:


------------------------
1)break
2)continue

loop without break(else)

eg:1
cart=[10,20,30,40,50]
for item in cart:
if item>=500:
print("We cannot process this order")
break
print(item)
else:
print("congrats...all items processed successfully")

eg:2
cart=[10,20,700,40,50]
for item in cart:
if item>=500:
print("We cannot process this order")
break
print(item)
else:
print("congrats...all items processed successfully")

3)pass statement:
-----------------
pass is a keyword in python.

In our programming syntactically if block is required


which won't do anything then we can define that
empty block with pass keyword

if x<=10:
pass

pass:
it is a empty statement
it is null statement
it won't do any thing

Eg:
if True:
syntaxError: unexpexted EOF while parsing

if True:pass -> valid

def m1():
syntaxError: unexpexted EOF while parsing

def m1():pass

use case of pass:


-----------------
sometimes in the parent class we have to declare a function with empty body
and child class responsible to provide proper implementation.such type of
empty body we can define by using pass keuword.

eg:

class rama:
def sum(self):
pass

r=rama()
r.sum()

eg:1
class rama:
def f1():
pass

class sita(rama):
def f1()
print("hello")

eg:
for i in range(100):
if i%9==0:
print(i)
else:pass
eg:
for i in range(100):
if i%9==0:
print(i)
else:pass

del statement:
--------------
del is a keyword in python

After using a variable, it is highly recommended to delete that variable


if it is no longer required, so that the corrspondong object is
eligible for garbage collector

x=10
print(x)
del x

name error: name x is not define

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

s="naresh"
print(s)
del s
del s[0]

Difference between del and None:


--------------------------------
pass
del
None

In the case del,the variables will be removed and


we cannot access that variable(unbine operation)
s="Naresh"
del s
print(s) -> name error: name is not define

But in the case of None Assignment the variable won't be removed but the
corresponding object is eligible for garbage collection (rebind operation)
.Hence after assigning with None value ,we can access that variable.

s="Naresh"
s=None
print(s)-None
------------------------------------------------------------------
String Data structures:
The most commonly used object in any project and in any programing language
is string only.
Hence we should aware complete information about string data type.

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

syntax:
s="Naresh"
s='Naresh'

Note: In most of other languages like c,c++,java, asingle character with in


the single quotes is treated as char data type value.But in python we are
not having char data type.Hence it is treated as String only.

eg:
ch='a'
type(ch)
class 'string'

How to define multiline String Literals?


----------------------------------------
We can define multipline string literals by using triple single or double quotes

eg:
s='''nice
computers
education'''

we can also use triple quotes to use single quotes or double quotes as symbol
inside string literal

s='This is 'single quote symbol' =invalid


s='This is \'single quote symbol'=valid
s="This is 'single quote symbol" =valid
s='This is "double quote symbol' =valid

s='The "python Notes" by 'Naresh' is very helpful' =invalid


s="The "python Notes" by 'Naresh' is very helpful" =invalid
s='The \"python Notes\" by \'Naresh\' is very helpful' =valid
s='''The "python Notes" by 'Naresh' is very helpful''' =valid

How to access Characters of a string:


-------------------------------------
we can access characters of a string by using the following ways:

1) By using index
2) by using slice operator

1) accessing charaters by using Index:

python both supports +ve and -ve index.


+ve index means left to right (forward direction)
-ve index means right to left (backward direction)

s='naresh'

s='naresh'
s[0]
'n'
s[4]
's'
s[-1]
'h'
s[10]
error: String index out of range error

Note: if we are trying to access characters of a string with out range index
then we sill get error saying: index error

q) write a program to accept some string from the keyboard and display
its characters by index wise (both positive and negative index)

s=input("Enter some string")


i=0
for x in s:
print("the characters present at positive index {} and negative index {} is {}"
.format(i,i-len(s),x))
i=i+1

Enter some string:naresh


the characters present at positive index 0 and negative index -6 is n
the characters present at positive index 1 and negative index -5 is a
the characters present at positive index 2 and negative index -4 is r
the characters present at positive index 3 and negative index -3 is e
the characters present at positive index 4 and negative index -2 is s
the characters present at positive index 5 and negative index -1 is h

2) Accessing Characters by using Slice Operator:


syntax: s[begining index:end index:step]

begin Index: from where we have to consider slice(sub sgtring)


end index: we have to terminate the slice(substring) at endindex-1
step: incremented value

Note:
=>If we are not specifing begin index then it will consider from begining
of the string.
=>if we are not specifying end index then it will consider up to end of the string
=>the default value for step is 1

s="Learning Python is very very easy!!!"


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

Behaviour Of Slice:

1)s[begin:end:step]
2) step value either positive (+ve) or negative(-ve)
3) if positive 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 to end+1

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

In forward direction:
default values for begin:0
default value for end: length of string
default value forstep:+1

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

Note: either forward and backward direction,we can take both +ve and -ve values
for begin and end index

Slice Opearator Case Study:


---------------------------
s='abcdefghij'
s[1:6:2]
'bdf'
s[::1]
'abcdefghij'
s[::-1]
'jihgfedcba'
s[3:7:-1]
''
s[7:4:-1]
'hgf'
s[0:10000:1]
'abcdefghij'
s[-4:1:-1]
'gfedc'
s[-4:1:-2]
'gec'
s[5:0:1]
''
s[9:0:0]
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
s[9:0:0]
ValueError: slice step cannot be zero
s[0:-10:-1]
''
s[0:-11:-1]
'a'
s[0:0:1]
''
s[0:9:-2]
''
s[-5:-9:-2]
'fd'
s[10:-1:-1]
''
s[10000:2:-1]
'jihgfed'

Note: Slice operator never raises index error

Mathematical Operators for strings:


We can apply the following mathematical operators for strings

1)+ operator for concantenation


2) * operator for repetition
print("nice"+"naresh")
print("nice"*5)

Note:
=>to use + operator for strings, compulsory both arguments should be strings
=>to use * operator for strings, compulsory one argument should be string and
another arguent should be int

len() in-built function:


-----------------------
we can use len() function to find the no of character present in the given string
eg:
s="Naresh"
print(len(s))
o/p:6

q)write a program to access each character of string in forward and


backward direction by using while loop

s="Learning Python is very easy !!!"


n=len(s)
i=0
print("forward direction:")
while i<n:
print(s[i],end='')
i+=1 #i=i+1

print("\nbackward direction:")
i=-1
while i>=-n:
print(s[i],end='')
i-=1 #i=i-1

Alternate ways:
eg:1
s="Learning Python is very easy !!!"
print("forward direction:")
for i in s:
print(i,end='')

eg:2
s="Learning Python is very easy !!!"
print("forward direction:")
for i in s[::]:
print(i,end='')

eg:3
s="Learning Python is very easy !!!"
print("backward direction:")
for i in s[::-1]:
print(i,end='')

checking Memberships:
---------------------
checking membership operators: in ,not in

we can check wheatherthe character or string is the member of another string or not
by using in and not in operators

s="naresh'
print('r' in s) -true
print('z' in s) -false
print('z' not in s)-true

eg:

s=input("Enter some string:")


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

comparision of strings: < > <= >=


we can use comparision operators(<,>,<=,>=) and equality operators(==,!=)
for strings.
Comparision will be performed based on alphabetical order.

eg:

s1=input("ENter first String:")


s2=input("ENter second String:")
if s1==s2:
print("Both strings are equal")
elif s1<s2:
print("First string is less than second string")
else:
print("First string is greater than second string")

Removing spaces from the string:


--------------------------------
we can use following 3 methods
1)rstrip()-> to remove spaces at right handside
2)lstrip()-> to remove spaces at lefthand side
3) strip()-> to remove spaces on both sides

eg:
city=input("Enter your city name:")
scity=city.strip()
if scity=='Hyderabad':
print("Hello Hyderabadi...Adab")
elif scity=='Chennai':
print("Hello Madrasi....Vanakkam")
elif scity=="Bangalore":
print("Hello Kannadiya...subhodhaya")
else:
print("your entered city is invalid")

Finding Substrings:
-------------------
we can use following 4 methods

for forward direction:


1)find()
s.find(substring)

for backward direction:


1)rfind()
2)rindex()

find():
-------
s.find(subsgring)

return index of first occurrence of the given string. if


it is not vailable the we will get -1

s="Learning Python is very easy"


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

note: by default find() method can search total string.we can also specify
the boundaries to search

s.find(substring,begin,end)
it will always search from begin index to end-1 index

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

2.index()
-------
index() method is exactly same as find() method except that if
the specified substring is not available then we will get value error

s=input("Enter main string:")


subs=input("ENTER SUBSTRING:")
try:
n=s.index(subs)
except ValueError:
print("Substring not found")
else:
print("substring found")

#Program to diaplay all positions of substring in a given main string

s=input("Enter Main String:")


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

output:
Enter Main String:abbababababcdefg
Enter sub string:a
Found at position 0
Found at position 3
Found at position 5
Found at position 7
Found at position 9

Counting substring in given String:


-----------------------------------
We can find the number of occurences of substring present in the given string
by using count() method.
1) s.count(substring)-> it will search through out the string.
2) s.count(substring,begin,end)-> it will search from begin index to end-1 index

s="abcabcabcabcadda"
print(s.count('a'))#6
print(s.count('ab'))#4
print(s.count('a',3,7))#2

Replacing a String with another String:


---------------------------------------
s.replace(oldstring,newstring)
inside s, every occurence of old string will be replaced with new string.

eg:1
s="Learning python is very difficult"
s1=s.replace("difficult","easy")
print(s1)

output:Learning python is very easy

eg:2 all occurrences will be replaced


s="ababababababab"
s1=s.replace("a","b")
print(s1)

o/p:bbbbbbbbbbbbbb

String objects are immutable then how we change the content by using replace() Method:
--------------------------------------------------------------------------------------
==> Once we create string object,we can not change the content.
This non changeable behaviour is nothing but Immutability.
If we are trying to change the content by using
any method,then with those changes a new objects will be created and changes
won't be happened in existing object.
Hence with replace() method also a new object got created but existing object
won't be changed.

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

output:
abad is available at:4568672
bbbb is available at:4568704

In the above example, original object is available and we can use


new object which was created because of replace() method.

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

Eg:1
s="Nice Computer Education"
l=s.split()
for x in l:
print(x)
output:
Nice
Computer
Education

Eg:2
s="22-02-2019"
l=s.split('-')
for x in l:
print(x)

output:
22
02
2019

Joining of Strings:
-------------------
We can join a Group of Strings(List OR Tuple) wrt the given Seperator

s=seperator.join(group of strings)

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

output:sunny-bunny-chinny

Eg:2
l=['Hyderabad', 'singapore','london','dubai']
s=':'.join(l)
print(s)

output: Hyderabad:singapore:london:dubai

Changing case of a String:


--------------------------
We can change case of a String by using the following 5 methods.

1)upper()->To convert the all characters into uppercase eg:NARESH


2)lower()->to convert the all characters into lowercase EG:naresh
3)swapcase()-> to convert the all lowercase into uppercase and all uppercase
characters into lowercase.
4)title()->To convert the all character to title case.i.e
first character is every word should be uppercase
and all remaining characters are should be in lowercase. eg: Nice Computers
5)capitalize()->Only first character will be converted into uppercase and all
remaining characters can be converted to lowercase.

Eg:1
s="learning Python is very Easy"
print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.caitalize())

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

Checking Starting and Ending part of the String:


------------------------------------------------
Python contains the following methods for this purpose
1)s.startswith(substring)
2)s.endswith(substring)
s='learning python is very easy'
print(s.startswith('learning'))
print(s.endswith('learning'))
print(s.endswith('easy'))

output:
-------
True
False
True

To check the type of characters present in a string:


----------------------------------------------------
Python contains the following methods for this purpose.

1)isalnum():Returns True if all characters are alphanumaric(atoz,ATOZ, 0to 9)


2)isalpha():Returns True if all characters are only alphabet symbols(atoz,AtoZ)
3)isdigit():Returns True is all characters are digits only(0-9)
4)islower():Returns True if all characters are only lowercase alphabet symbols
5)isupper():Returns True if all characters are only uppercase alphabet symbols
6)istitle():Returns True if string is in title case
7)isspace():Returns True if string contains only spaces.

Eg:
print('Naresh786'.isalnum())->True
print('naresh786'.isalpha())->False
print('naresh'.isalpha())->True
print('naresh'.isdigit())->False
print('786786'.isdigit())->True
print('abc'.islower())->True
print('Abc'.islower())->False
print('abc123'.islower())->True
print('ABC'.isupper())->True
print('Learning Python is very easy'.istitle())->False
print('Learnign Python Is Very Easy'.istitle())->True
print(' '.isspace())->True

Demo Program:
-------------
s=input("Enter any character:")
if s.isalnum():
print("Alpha Numaric Charatcter")
if s.isalpha():
print("Alphabet character")
if s.islower():
print("Lowercase Alphabet Charatcter")
else:
print("UPPER CASE ALPHABET CHARACTER")
else:
print("It is a digit")
elif s.isspace():
print("It is a space character")
else:
print("Non space special character")

c:\1>py test.py
Enter any character:7
Alpha Numaric Charatcter
It is a digit

c:\1>py test.py
Enter any character:a
Alpha Numaric Charatcter
Alphabet character
Lowercase Alphabet Charatcter

c:\1>py test.py
Enter any character:$
Non space special character

c:\1>py test.py
Enter any character:A
Alpha Numaric Charatcter
Alphabet character
UPPER CASE ALPHABET CHARACTER

-------------------------------------------
Formating the strings:
We can format the strings with variable values by using replacement operator{}
and format() method.

name='naresh'
salary=10000
age=28
print("{}'s salary is {} and his age {}".format(name,salary,age))
print("{0}'s salary is{1} and his age{2}".format(name,salary,age))
print("{x}'s salary is{y} and his age{z}".format(z=age,y=salary,x=name))

output:
naresh's salary is 10000 and his age 28
naresh's salary is10000 and his age28
naresh's salary is10000 and his age28

IMPORTANT PROGRAMS REGARDING STRING CONCEPTS:

1)Write a program To reverse the given string:


Input:naresh
output:hseran

1st way:
--------
s=input("Enter some string")
print(s[::-1])
2nd way:
--------
s=input("Enter some string")
print(''.join(reversed(s)))
3rd way:
--------
s=input("Enter some string:")
i=len(s)-1
target="
while i>=0:
target=target+s[i]
i=i-1
print(target)

2)write a program to reverse order of words:

Input:Learning Pythonis very Easy


output:Easy Very is Python Learning

s=input("Enter some string:")


l=s.split()
l1=[]
i=len(l)-1
while i>=0:
l1.append(l[i])
i=i-1
output=''.join(l1)
print(output)

output:
-------
Input:Learning Pythonis very Easy
output:Easy Very is Python Learning

3) write a program to reverse internal content of each word:

Input:Nice Computer Education


output:eciN retupmoC noitacudE

s=input("Enter some String:")


l=s.split()
l1=[]
i=0
while i<len(l):
l1.append(l[i][::-1])
i=i+1
output=' '.join(l1)
print(output)

4)write a program to print charatcers at odd position and even position


for the given string?

1st way:
--------
s=input("Enter Some String:")
print("Charatcers at even position:",s[0::2])
print("Characters at odd position:",s[1::2])
2nd way:
--------
s=input("Enter some string:")computers
i=0
print("Character at even position:")
whiel i<len(s):
print(s[i],end=',')
i=i+2
print()
print("Characters at odd Position:")
i=1
while i<len(s):
print(s[i],end=',')
i=i+2

5)Program to merge characters of 2 strings into a single string by taking


characters alternatively

Input: s1="ravi"
s2="Teja"
output: rtaevjia

s1=input("Enter First String:") ravi


s2=input("Enter SeconD String:") teja
output=''
i,j=0,0
while i<len(s1) or j<len(s2)
if i<len(s1):
output=output+s1[i]
i+=1
if j<len(s2):
output=output+s2[j]
j+=1
print(output)

6)
write a program to sort the characters of the string and First alphabet
symbols followed by numaric values:

Input:B4A1D3
output:ABD134
s=input("Enter First String:")
s1=s2=output=''
for x in s:
if x.isalpha():
s1=s1+x
else:
s2=s2+x
for x in sorted(s1):
output=output+x
for x in sorted(s2):
output=output+x
print(output)

7)a program for the following requirement


Input:a4b3c2
Output:aaaabbbcc

s=input("Enter First String:")


output=''
for x in s:
if x.isalpha():
output=output+x
previous=x
else:
output=output+previous*(int(x)-1)
print(output)

Note:chr(unicode)->the corresponding character


ord(character)-> the corresponding unicode value
A=65
a=97

8)write a program to perform following activity


INput:a4k3b2
output:aeknbd

s=input("Enter some string:")


output=''
for x in s:
if x.isalpha():
output=output+x
previous=x
else:
output=output+chr(ord(previous)+int(x))
print(output)

9)write a program to remove duplicates characters from the given input string:

Input:ABCDABBCDABBBCCCDDEEEF
output:ABCDEF

s=input("Enter some String:")


l=[]
for x in s:
if x not in l:
l.append(x)
output=".join(l)
print(output)

10)
write a program to find the number of occurrences of each character present in the given
string:
Input:ABCABCABBCDE
output:A-3,B-4,C-3,D-1,E-1

s=input("Enter some string:")


d={}
for x in s:
if x in d.keys():
d[x]=d[x]+1
else:
d[x]=1
for k,v in d.items():
print("{}={}Times".format(k,v))

11)
write a program to perform the following task:

input:'one two three four five six seven'


output:'one owt three ruof five xis seven'

s=input("Enter some string:")


l=s.split()
l1=[]
i=0
while i<len(l):
if i%2==0:
l1.append(l[i])
else:
l1.append(l[i][::-1]
i=i+1
output=''.join(l1)
print('original string:',s)
print('output string:',output)

Formatting the strings:


------------------------
We can format the strings with variable values by using replacement operator {}
and format() method The main objective of format() method
to format string into meaningful output form.

Case-1:Basic formatting for default,positional and keyboard arguments.


------

Formating the strings:


We can format the strings with variable values by using replacement operator{}
and format() method.

name='naresh'
salary=10000
age=28
print("{}'s salary is {} and his age {}".format(name,salary,age))
print("{0}'s salary is{1} and his age{2}".format(name,salary,age))
print("{x}'s salary is{y} and his age{z}".format(z=age,y=salary,x=name))

output:
naresh's salary is 10000 and his age 28
naresh's salary is10000 and his age28
naresh's salary is10000 and his age28

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

Eg:1
print("The integer Number is:{}".format(123))
print("The integer Number is:{:d}".format(123))
print("The integer Number is:{:5d}".format(123))
print("The integer Number is:{:05d}".format(123))

Output:
The integer Number is:123
The integer Number is:123
The integer Number is: 123
The integer Number is:00123

Eg:2
print("The float number is:{}".format(123.4567))
print("The float number is:{:f}".format(123.4567))
print("The float number is:{:8.3f}".format(123.4567))
print("The float number is:{:08.3f}".format(123.4567))
print("The float number is:{:08.3f}".format(123.45))
print("The float number is:{:083f}".format(786786123.45))

output:

The Float Number is:123.4567


The Float Number is:123.456700
The Float Number is: 123.457
The Float Number is:0123.457
The Float Number is:0123.450
The Float Number is:00000000000000000000000000000000000000000000
00000000000000000000000786786123.450000

NOTE:
1.{:08.3f}
2.Total positions should be minimum 8
3.After decimal point exactly 3 digits are allowed.If it less then 0s will be placed in the last
positions
4.If total number<8 positions then 0 will be placed MSBs
5.if total number>8 positions then all integer digits will be considered.
6.The extra digit we can take only 0.

Note:for number default alignment is Right Alignment(>)

Eg:3
print Decimal value in binary, octal and hexadecimal form

print("Binary Form :{0:b}".format(153))


print("octal form :{0:o}".format(153))
print("Hexa decimal Form:{0:x}".format(154))
print("Hexa decimal Form:{0:X}".format(154))

output:
Binary Form:10011001
Octal Form:231
Hexa decimal Form:9a
HexaDeciaml Form:9A

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

Note:
1){:5d} it takes an integer argument and assigns a minimum width of 5.
2){:8.3f} it takes a float argument and assigns a minimum width of 8 including"."and after
decimal point exactly 3 digits are allowed with round operation if required
3){:05d} the blank spaces can be filled with 0.In this place only 0 allowed.

Case:3
Number Formating for signed numbers.

1.While displaying positive numbers,If we want to include + then we have to write


{:+d} and {:+f}

2.Using plus for -ve numbers there is no use and for -ve number -sign will come
automatically.

print("int value with sign:{:+d}".format(123))


print("int value with sign:{:+d}".format(-123))
print("int value with sign:{:+f}".format(123.456))
print("int value with sign:{:+f}".format(-123.456))

Output:
Int value with:+123
Int value with sign:-123
Float value with sign:+123.456000
Float value with sign:-123.456000

Case:4 Number Formatting with Alignment

1) <,>,^ and = are used for alignment


2) < --> Left Alignment to the remaining space
3) ^ --> Center Alignment to the remaining space
4) > --> Right Alignment to the remaining space
5) = --> Forces the signed (+)(-) to the left most position

Note:Default alignment for numbers is Right Alignment

Eg:
print("{:5d}".format(12))
print("{:<5d}".format(12))
print("{:<05d}".format(12))
print("{:>5d}".format(12))
print("{:>05d}".format(12))
print("{:^5d}".format(12))
print("{:=5d}".format(-12))
print("{:^10.3f}".format(12.23456))
print("{:=8.3f}".format(-12.23456))

Output:
12
12
12000
12
12
00012
12
-12
12.235
-12.235

Case:5 String Formating with format() method.


similar to numbers, we can format string values also with format() method.
s.format(string)

print("{:5d}".format(12))
print("{:5}".format("rat"))
print("{:>5}".format("rat"))
print("{:<5}".format("rat"))
print("{:^5}".format("rat"))
print("{:*^5}".format("rat")) #instead of * we can use any character(like +,$,a etc)

Output:
12
rat
rat
rat
rat
*rat*

Note: For numbers default alignment is right where as for string default alignment is left

Case:6
Truncating String with format() method
print("{:.3}".format("nicesoftware"))
print("{:5.3}".format("nicesoftware"))
print("{:>5.3}".format("nicesoftware"))
print("{:^5.3}".format("nicesoftware"))
print("{:*^5.3}".format("nicesoftware"))

output:
nic
nic
nic
nic
*nic*

Case7:Formatting dictionary members using format()

person={'age':48,'name':'durga'}
print("{p[name]}'s age is:{p[age]}".format(p=person))

Output:
durga's age is:48
Note: p is alias name of dictionary
person dictionary we are passing as keyboard argument

more convinient way is to use **person

person={'age':28,'name':'naresh'}
print("{name}'s age is :{age}".format(**person))

Output:
Naresh age is:28

Case:8
Formatting class members using format()
class person:
age=28
name="naresh"
print("{p.name}' age is :{p.age}".format(p=person()))

Output:naresh's age is:28

class Person:
def__init__(self,name,age):
self.name=name
self.age=age
print("{p.name}'s age is:{p.age}".format(p=Person('naresh',28)))
print("{p.name}'s age is:{p.age}".format(p=Person('Ravi',50)))

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

Case:9
Dynamic Formatting using format()
string="{:{fill}{align}{width}}"
print(string.format('cat',fill='*',align='^',width=5))
print(string.format('cat',fill='*',align='^',width=6))
print(string.format('cat',fill='*',align='<',width=6))
print(string.format('cat',fill='*',align='>',width=6))

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

Case:10
--------
Dynamic Float format template

num="{:align}{width}.{precision}f}"
print(num.format(123.236,align='<',width=8,precision=2))
print(num.format(123.236,align='>',width=8,precision=2))

Output:
123.24
123.24

Case:11
-------
Formating Date Values

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

output: it's now:19/03/2019 12:36:26

Case:12 Formatting complex numbers

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

Output:Real Part:1.0 and Imaginary Part :2.0

LIST DATA STRUCTURES:


---------------------

If we want to represent a group of individual objects as a single entity where insertion


order preserved and duplicates are allowed,then we should go for List.
Insertion order preserved.
duplicate objects are allowed.
heterogeneous objects are allowed.
List is dynamic because based on our requirement we can increase the size and decrease
the size.
In List the elements will be placed with in square brackets and with comma seperator.
we can differentiate duplicate elements by using index and we can preserve insertion order
by using index,Hence
index will play very important role.
Python supports both positive and negative indexex,+ve index means from left to right where
as negative index means right to left.
[10,"A","B",20,30,10]

-6 -5 -4 -3 -2 -1
10 A B 20 30 10
0 1 2 3 4 5

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

CREATION OF LIST OBJECTS:

1)We can create empty list objects as follows.....


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

[]
<class 'list'>

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

3)with dynamic input:


list=eval(input("Enter List:"))
print(list)
print(type(list))

c:\1>py test.java
Enter List:[10,20,30,40]
[10,20,30,40]
<class,'list'>

4)with List Function:


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

c:\1>py test.py
[0,2,4,6,8]
<class 'list'>

Eg:1
s="naresh"
l=list(s)
print(l)
c:1>py test.py
['n','a','r','e','s','h']

5)With Split Functions

s="Learning Python is very very easy"


l=s.split()
print(l)
print(type(l))

c:1>py test.py
['Learning','python','is','very','very','Easy']

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

ACCESSSING ELEMENTS OF LIST:


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

1)by using index:


-----------------
List follows zero based index.ie index of first element is zero.'
List support both +ve and -ve indexes
+ve index meant for Left to Right.
-ve Index meant for Right to Left.
list=[10,20,30,40]

-4 -3 -2 -1
10 20 30 40
0 1 2 3

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

2)by using slice operator:


--------------------------
Syntax: list2=list1[start:stop:step]

start->It indicates the Index where slice has to start default value is 0.
stop-> It indicates the Index where slice has to End Default Value is max allowed Index of
List ie Length of the List
Step->increment value
Default Value is 1

n=[1,2,3,4,5,6,7,8,9,10]
print(n[2:7:2])
print(n[4::2])
print(n[3:7])
print(n[8:2:-2])
print(n[4:100])
output:
c:1>py test.py
[3,5,7]
[5,7,9]
[4,5,6,7]
[9,7,5]
[5,6,7,8,9,10]

List vs Mutability:
-------------------
Once we creates a List object,We can modify its content.Hence List objects are mutable.
n=[10,20,30,40]
print(n)
n[1]=777
print(n)

c:1>py test.py
[10,20,3,40]
[10,777,30,40]

Traversing the Elements of List:


--------------------------------

1) By using while loop:


-----------------------
n=[0,1,2,3,4,5,6,7,8,9,10]
i=0
while i<len(n):
print(n[i])
i=i+1
c:1> py test.py
0
1
2
3
4
5
6
7
8
9
10

2)By using for loop:


--------------------
n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
print(n1)
c:1>
0
1
2
3
4
5
6
7
8
9
10
3)To display only Even Numbers:
-------------------------------
n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
if n1%2==0:
print(n1)

c:1>py test.py
0
2
4
6
8
10

4)To display Elements by index wise:


------------------------------------
l=["A","B","C"]
x=len(l)
for i in range(x):
print(l[i],"is available at positive index:",i,"and at negative index:",i-x)

c:1>py test.py
A is available at positive index:0 and at negative index:-3
B is available at positive index:0 and at negative index:-2
C is available at positive index:0 and at negative index:-1

Importent Functions Of List:


----------------------------

I. TO GET Information about List:

1)len():Returns the number of elements present in the list.


eg:
n=[10,20,30,40]
print(len(n))->4

2)count():It returns the number of occurences of specified item in the list

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

o/p:.append
c:1>py test.py
1
4
2
0

3)index():Returns the index of first occurence of the specified item.


n=[1,2,2,2,2,3,3]
print(n.index(1))->0
print(n.index(2))->1
print(n.index(3))->5
print(n.index(4))->Value Error :4 is not list

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

II.MANUPLATING ELEMENTS OF LIST:


--------------------------------
1)append() Function:
We can use append() function to add item at the end of the list.

list=[]
list.append("A")
list.append("B")
list.append("C")
print(list)

c:\1>py test.py
['A','B','C']

Eg:To add all elements to list up to 100 which are divisible by 10


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

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

2)insert() Function:
To insert item at specified index position

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

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

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

c:\1>py test.py
[999,1,2,3,4,5]
[999,1,,2,3,4,5,777]

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

Difference between append() and index()


-----------------------------------------
append()
insert()
In list when we add any element it will In list we can insert any element in
particular index
come in last i.e. it will be last element. number

3) extend() Function:
---------------------
To add all items of one list to another list.
l1.extends(l2)
all items present in l2 will be added to l1

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

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

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

c:1>py test.py
["Chicken","Mutton","Fish","M","u","s","h","r","o","o","m"]

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

n=[10,20,10,30]
n.remove(10)
print(n)
c:1>py test.py
[20,10,30]

If the specified item not present in list then we will get ValueError.

n=[10,20,10,30]
n.remove(40)
print(n)

ValueError:list.remove(x):x not in list

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

5)pop() Function:
----------------
It removes and returns the last element of the list.
This is only function which manipulate list and returns some element.

n=[10,20,30,40]
print(n.pop())
print(n.pop())
print(n)

c:1>py test.py
40
30
[10,20]

If the list is empty then pop() function raises index error

n=[]
print(n.pop())->index error:pop from empty list

Note:
1)pop() is the only function which manipulates the list and returns some value
2)In general we can use append() and pop() functions to implement stack datastructure
by using list,which follows LIFO(Last in first out) order.

In general we can use pop() function to remove last element of the list. but we can use to
remove
elements based on index.

n.pop(index)->To remove and return element present at specified index.


n.pop()->To remove and return last element of the list

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

DIFFERENCE B/W REMOVE() AND POP()


remove() pop()
We can use to remove special element We can use to remove last element
from the list from the list
It can return any value. It return removed element
If special element not available then If List is empty then we get Error
we get Value Error

Note:List Objects are dynamic.i.e. based on our requirement we can increase and decrease
the size.

append(),insert(),extend()->for increasing the size /growable nature


remove(),pop()-> for decreasing the size / shrinking nature

III) Ordering Elements of List:


-------------------------------

1)reverse():
------------
We can use to reverse() order of elements of list.

n=[10,20,30,40]
n.reverse()
print(n)

c:1>pt test.py
[40,30,20,10]

2)sort():
---------
In list by default insertion order is preserved.If we want to sort the elements of list
according to default natural sorting order then we should go for sort() method.

for numbers->Default Natural sorting Order is Ascending Order.


for Strings->Default Natural sorting order is Alphabetical Order

n=[20,5,15,10,0]
n.sort()
print(n)->[0,5,10,15,20]

s=["Dog","Banana","Cat","Apple"]
s.sort()
print(s)->['Apple','Banana','Cat','Dog']

Note:To use sort() function,compulsory list should contain only homogeneous elements.
Otherwise we will get TypeError.

n=[20,10,"A","B"]
n.sort()
print(n)
Type Error:'<' not supported between instance of 'str' and 'int'.

Note:In Python 2 if list contains both numbers and Strings then sort() functions first sort
numbers followed by strings.
n=[20,"B",10,"A"]
n.sort()
print(n)#[10,20,'A','B']

But in Python 3 it is invalid.

TO Sort in Reverse of Default Natural Sorting Order:


------------------------------------------------------------
We can sort accoerding to reverse of default natural sorting order
by using reverse=True argument.

n=[40,10,30,20]
n.sort()
print(n)->[10,20,30,40]
n.sort(reverse=True)
print(n)->[40,30,20,10]
n.sort(reverse=False)
print(n)->[10,20,30,40]

Aliasing and Cloning of List Objects:


--------------------------------------
The process of giving another reference variable to the existing list
is called aliasing.

x=[10,20,30,40]
y=x
print(id(x))
print(id(y))

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

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

To overcome this problem we should go for cloning.


The process of creating exacttly duplicate independent object is called cloning.

We can implement cloning by using slice operator or by using copy() function.

1)By using Slice Operator:


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

2)By using copy() Function:


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

Q) Difference between = Operator and copy() Function


-----------------------------------------------------
= Operator meant for aliasing
copy() Function meant for cloning

Using Mathematical Operators for List Objects:


-----------------------------------------------
We can use + and * operators for List objects.

1)Concatenation Operator (+):


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

Note:To use + operator compulsory both arguments should be list objects,


otherwise we will get TypeError.

Eg:
c=a+40->Type error: can only concatenate list(not "int") to list
c=a+[40]->valid

2)Repetition Operator(*):
-------------------------
We can use repetition operator * to repeat elements of list specified number of times.

x=[10,20,30]
y=x*3
print(y)->[10,20,30,10,20,30,10,20,30]

Comparing List Objects:


-----------------------
We can use comparision operators for list objects.

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

Note:Whenever we are using comparison operators (==,!=) for List object then the
following should be considered.
1)The Number of Elements
2)The Order of Elements
3)The Content of Elements(Case Sensitive)
Note:When ever we are using relational Operators(<,<=,>,>=) between List Object,
only 1st Element comparison will be performed.

x=[50,20,30]
y=[40,50,60,100,200]
print(x>y)->True
print(x>=y)->True
print(x<y)->False
print(x<=y)->False

Eg:
x=["Dog","Cat","Rat"]
y=["Rat","Cat","Dog"]
print(x>y)->False
print(x>=y)->False
print(x<y)->True
print(x<=y)->True

Membership Operators:
---------------------
We can check wheather element is a member of the list or not by using membership
operators.

in Operator
not in Operator

n=[10,20,30,40]
print(10 in n)
print(10 not in n)
print(50 in n)
print(50 not in n)

output:
-------
True
False
False
True

clear() Function:
-----------------
We can use clear() function to remove all elements of List.

n=[10,20,30,40]
print(n)
n.clear()
print(n)

output:
c:\>py test.py
[10,20,30,40]
[]
Nested Lists:
-------------
Sometimes we can take one list inside another list.Such type of lists are called
needed lists.

n=[10,20,[30,40]]
print(n)
print(n[0])
print(n[2])
print(n[2][0])
print(n[2][1])

Output:
c:1> py test.py
[10,20,[30,40]]
10
[30,40]
30
40

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

Nested List as Matrix:


----------------------
In Python we can repesent matrix by using nested lists.

n=[[10,20,30],[40,50,60],[70,80,90]]
print(n)
print("Elements by Rows wise:")
for r in n:
print(r)
print("Elements by Matrix style:")
for i in range(len(n)):
for j in range(len(n[i])):
print(n[i][j],end=' ')
print()

output:
c:1>py test.py
[[10,20,30],[40,50,60],[70,80,90]]

Elements by Row wise:


[10,20,30]
[40,50,60]
[70,80,90]

Elements by Matrix style:


10 20 30
40 50 60
70 80 90
List Comprehensions:
---------------------
It is very easy and compact way of creating list objects from any iterable objects
(Like List,Tuple,Dictionary,Range etc) based on some condition.

Syntax: list=[expression for item in list if condition]

s=[x*x for x in range(1,11) ]


print(s)
v=[2**x for x in range(1,6)]
print(v)
m=[x for x in s if x%2==0]
print(m)

c:\1>py test.py
[1,4,9,16,25,36,49,64,81,100]
[2,4,8,16,32]
[4,16,36,64,100]

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

output: ['B','N','V','C']

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

common elements present in num1 and num2


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

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

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

EG:
WRITE A PROGRAM TO DISPLAY UNIQUE VOWELS PRESENT IN THE GIVEN WORD?

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

c:1>py test.py

Enter the word to search for vowels:nicecomputereducation


['i', 'e', 'o', 'u', 'a']
The number of different vowels present in nicecomputereducation is 5

List out all Functions of List and write a program to use these Functions.

TUPLE DATA STRUCTURES:


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

t=10,20,30,40
print(t)
print(type(t))

output:
(10,20,30,40)
<class 'tuple'>
t=()
print(type(t))->tuple

Note:We have to take special care about single valued tuple.compulsary the value should
ends with comma,
otherwise it is treated as tuple.

eg:1
t=(10)
print(t)
print(type(t))

outut
10
<class'int'>
eg:2
t=(10,)
print(t)
print(type(t))

output:
(10,)
<class 'tuple'>

Q) Which of the following are valid Tuple?


t=()
t=10,20,30,40
t=10
t=10,
t=(10)
t=(10,)
t=(10,20,30,40)

Tuple Creation:
------------------
1)t=()
Creation of empty Tuple

2)t=(10,)
t=10,
Creation of Single valued Tuple,Parenthisis are optional,should ends with comma

3)
t=10,20,30
t=(10,20,30)
Creation of multi values Tuples & Parenthesis are Optional.

4)By using Tuple Functions:

list=[10,20,30]
t=tuple(list)
print(t)
t=tuple(range(10,20,2))
print(t)

Accessing Elements of Tuple:


----------------------------
We can access by index or by slice Operator

1)By using index:


-----------------
t=(10,20,30,40,50,60)
print(t[0])->10
print(t[-1])->60
print(t[100])->index Error:tuple index out of range.
2)By using slice Operator:
--------------------------
t=(10,20,30,40,50,60)
print(t[2:5])
print(t[2:100])
print(t[::2])

output:
(30,40,50)
(30,40,50,60)
(10,30,50)

Tuple vs Immutability:
----------------------
Once we creates Tuple, we cannot change its content.
Hence tuple objects are immutable.

Eg:
t=(10,20,30,40)
t[1]=70->Type Error:'tuple' object does not support item assignment

Mathematical Operators for Tuple:


---------------------------------
We can apply + and * operators for tuple

1)Concatenation Operator (+):


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

2)Multiplication Operator OR Repetition Operator(*)

t1=(10,20,30)
t2=t1*3
print(t2)->(10,20,30,10,20,30,10,20,30)

Important Functions of Tuple:


-----------------------------
1))len()
To return number of elements present in the Tuple.

Eg:t=(10,20,30,40)
print(len(t))->4

2)count()
To return number of occurrences of given element in the tuple

Eg:t=(10,20,10,10,20)
print(t.count(10))->3

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

4)sorted()
To sort elements based on default natural sorting order.

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

output:
-------
(10,20,30,40)
(40,10,30,20)

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


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

5)min() And max() Functions:


-----------------------------
These functions return min and max values according to defualt natural sorting order.

t=(40,10,30,20)
print(min(t))->10
print(max(t))->40

6)cmp():
--------
It compares the elements of both tuples.
if both tuples are equal then return 0.
if the first tuple is less than second tuple then it returns -1
if the first tuple is greater than second tuple then it returns +1.

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

Note: cmp() function is available only in python2 but not in python3

Tuple packing and Unpacking:


----------------------------

Eg:
a=10
b=20
c=30
d=40
t=a,b,c,d
print(t)->(10,20,30,40)

Here a,b,c,d are packed into a Tuple t.This is nothing but Tuple packing.
Tuple unpacking is the reverse process of Tuple packing.
We can unpack a Tuple and assign its values to different variables.

t=(10,20,30,40)
a,b,c,d=t
print("a=",a,"b=",b,"c=",c,"d=",d)
Output:a=10 b=20 c=30 d=40

Note:At the time of tuple unpacking the number of variables and number of values
should be same,otherwise we will get ValueError.

Eg:
t=(10,20,30,40)
a,b,c=t->Value Error:too many values to unpack(expected 30)

Tuple Comprehension:
--------------------
Tuple Comprehension is not supported by Python.
t=(x**2 for x in range(1,6))
Here we are not getting tuple object and we are getting generator object.

t=(x**2 for x in range(1,6))


print(type(t))
for x in t:
print(x)

c:1>py test.py
<class 'generator'>
1
4
9
16
25

Q)Write a program to take a Tuple of Numbers from the keyboard and Print
its Sum and Average?

t=eval(input("Enter Tuple of Number:"))


l=len(t)
sum=0
for x in t:
sum=sum+x
print("The sum=",sum)
print("The Average=",sum/l)

c:\1>py test.java
Enter Tuple of Numbers:(10,20,30,40)
The Sum=100
The Average=25.0

c:1>py test.py
Enter Tuple of Numbers:(100,200,300)
The Sum=600
The Average=200.0

Difference between List and Tuple:


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

List Tuple
1)List is a Group of comma separeated Tuple is a Group of comma seperated
values within Square Brackets and Values with in Parenthisis and
square Brackets are mandatory. Parenthisis 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 Tuple Objects are Immutable i.e once
create List Object we can perform any we create 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 If the content is fixed and never changes
changes then we should go for List. then we should go for Tuple.

4)List Objects can not used as Keys for Tuple Objects can be used as
Keys for
Dictionary because Keys should be Dictionary because Keys should
be
Hashable and Immutable. Hashable and Immutable.

---------------------------------------------------------------------------------------------------------------

SET DATA STRUTURES:


-------------------
1)If we want to represent a group of unique values as a single entity then
we should go for set.
2)duplicates are not allowed.
3)insertion order is not preserved.But we can sort the elements.
4)indexing and slicing not allowed for the set.
5)hetrogeneous elements are allowed.
6)set objects are mutable i.e,once we creates set object we can perform any changes in that
object based on our requirement.
7)we can represent set elemets within curly braces and with comma seperation.
8)we can apply mathematical operations like union,intersection,difference etc on set objects.

Creation of Set Objects:


-------------------------
s={10,20,30,40}
print(s)
print(type(s))

Output
------
{40,10,20,30}
<class 'set'>

we can create set objects by using set() function s=set(any sequence)

Eg1:
---
l=[10,20,30,40,10,20,10]
s=set(l)
print(s)#{40,10,20,30}

Eg2:
---
s=set(range(5))
print(s)#{0,1,2,3,4}

Note:
-----
while creating empty set we have to take special care.
compulsory we should use set() function.
s={} ->it is treated as dictionary but not empty set.

s={}
print(s)
print(type(s))

Output
-------
{}
<class,'dict'>

Eg:
---
s=set()
print(s)
print(type(s))

Output
------
set()
<class,'set'>

Important Functions of Set:


----------------------------
1)add(x):
---------
Adds item x to the set.
s={10,20,30}
s.add(40);
print(s) #{40,10,20,30}

2)update(x,y,z):
-----------------
To add multiple items to the set.
Arguments are not individual elements and these are iterable objects like List,Range etc.
All elements present in the given iterable objects will be added to set.

s={10,20,30}
L=[40,50,60,10]
s.update(L,range(5))
print(s)

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

What is the difference between add() and update() functions in set?


-------------------------------------------------------------------
1) we can use add() to add individual item to the set, where as we can use update()
function to add multiple items to set .
2) add()function can take only one argument where as update() function can take
any number of arguments but all arguments should be iterable objects

Which of the following are valid for set s?


-------------------------------------------
s.add(10)
s.add(10,20,30)->TypeError:add()takes exactly one argument(3 given)
s.update(10)->TypeError:'int'object is not iterable
s.update(range(1,10,2),range(0,10,2))

3)copy():
---------
1) returns copy of the set.
2) it is cloned object.
s={10,20,30}
s1=s.copy()
print(s1)

4)pop():
--------
it removes and returns some random element from the set.
s={40,10,30,20}
print(s)
print(s.pop())
print(s)

Output
------
{40,10,20,30}
40
{10,20,30}

5)remove(x):
------------
1) It removes specified element from the set.
2) If the specified element not present in the set then we will get keyError.
s={40,10,30,20}
s.remove(30)
print(s) {40,10,20}
s.remove(50) keyerror-50

6)discard(x):
-------------
1) It removes the specified element from the set.
2) If the specified element not present in the set then we won't get any error.
s={10,20,30}
s.discard(10)
print{<>(s) 20,30}
s.discard(50)
print(<>(s) 20,30}

Q)what is the difference between remove() and discard() functions in set?


Q)explain differences between pop(),remove() and discard() functions in set?

7)clear():
----------
To remove all elements from the set.
s={10,20,30}
print(s)
s.clear()
print(s)

Output:
-------
{10,20,30}
set()

Mathematical Operations on the Set:


-----------------------------------
1)union():
----------
x.union(y)->we can use this function to return all elements present in both sets
x.union(y)OR x|y.
x={10,20,30,40}
y={30,40,50,60}
print(x.union(y))->{10,20,30,40,50,60}
print(x|y)->{10,20,30,40,50,60}

2)intersection():
------------------
x.intersection(y)OR x&y.
Returns common elements present in both x and y.
x={10,20,30,40}
y={30,40,50,60}
print(x.intersection(y))->{40,30}
print(x&y)->{40,30}

3)difference():
---------------
x.difference(y) OR x-y.
returns the elements present in x but not in y.
x={10,20,30,40}
y={30,40,50,60}
print(x.difference(y))->10,20
print(x-y)->{10,20}
print(y-x)->{50,60}

4)symmetric_difference():
-------------------------
x.symmetric_difference(y) Or x^y.
Returns elements present in either x OR y but not in both.
x={10,20,30,40}
y={30,40,50,60}
print(x.symmetric_difference(y))->{10,50,20,60}
print(x^y)->{10,50,20,60}

Membership Operators:(in,not in)


--------------------------------
s=set("durga")
print(s)
print('d' in s)
print('z' in s)

Output:
-------
{'u','g','r','d','a'}
True
False

Set Comprehension:
------------------
set comprehension is possible.

s={x*x for x in range(5) }


print(s)->{0,1,4,9,16}

Set Objects won't support indexing and slicing:


-----------------------------------------------
s={10,20,30,40}
print(s[0])->TypeError:'set'object does not support indexing
print(s[1:3])->TypeError:'set'object is not subscriptable

Write a program to eliminate duplicates present in the list?


------------------------------------------------------------
Approach-1 Approach-2
1) l=eval(input('enter list values:")) 1) l=eval(input('enter list of values:"))
2) s=set(l) 2) l1=[]
3) print(s) 3) for x in l:
4) if x not in l1:
D:\Python_classes>py test.py 5) l1.append(x)
Enter List of values:[10,20,30,10,20,40] 6) print(l1)
{40,10,20,30}
D:\Python_classes>py test.py
enter list of values:[10,20,30,10,20,40]
[10,20,30,40]

Q)Write a program to print different vowels present in the given word?


w=input("enter word to search for vowels:")
s=set(w)
v={'a','e','i','o','u'}
d=s.intersection(v)
print("The different vowel present in",w,"are",d)

D:\Python_classes>py test.py
Enter word to search for vowels:durga
The different vowel present in durga are{'u','a'}

DICTIONARY DATA STRUCTURE:


--------------------------
We can use List,Tuple and Set to represent a group of individual object 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----domainname

Duplicate keys are not allowed but values can be duplicated.


Hetrogeneous objetcs are allowed for both key and values.
Insertion order is not preserved.
Dictionaries are mutable
Dictionaries are dynamic
indexing and slicing concepts are not applicable.

Note:In c++ and java Dictionaries are known as "Map" where as in Perl and Ruby It is
Known as "Hash"
How to create Dictionary?
-------------------------
d={} or d-dict()
We are creating empty dictionary.We can add entries as follows.
d[100]="durga"
d[200]="ravi"
d[300]="shiva"
print(d)->{100:'durga',200:'ravi',300:'shiva'}

If we know data in advance then we can create disctionary as follows

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

How to Access Data from the dictionary?


-----------------------------------------
We can access the data by using keys.

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

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


print(d[400])->key error

we can represent this by checking whether is already available or not by using has_key()
function or by using in oprator.
d.has_key(400)-> Returns 1 if key is available otherwise returns 0
But has_key()function is available only in python 2 but not in python 3. Hence compulsory
we have to use in operator.
if 400 in d:
print(d[400])

q)write a program to enter name and percantage marks in a Dictionary and display
information on the screen
---------------------------------------------------------------------------------------------------------------------------
-------
rec={}
n=int(input("Enter number of students:"))
i=1
while i<=n:
name =input("Enter student name:")
marks=input("Enter % of marks of student:")
rec[name]=marks
i=i+1
print("Name of student",name,"% of marks",marks)

for x in rec:
print("\t",x,"\t",rec[x])
D:\python_classes>py test.py
Enter number of students:3
Enter student name :durga
Enter % of marks of student:60%
Enter student name : ravi
Enter % of marks of student:70%
Enter student name : shiva
Enter % of marks of student :80%
Name of student % of marks
--------------- -----------
Durga 60%
ravi 70%
shiva 80%

How to Update Dictionaries


---------------------------------
d[key]=value
if the key is not available then a new entry will be added to the dictionary with the specified
key-value pair
if the key is already available then old value will be replaced with new value.
d={100:"durga",200:"ravi",300:"shiva"}
print(d)
d[400]="pavan"
print(d)
d[100]="sunny"
print(d)
output
{100:'durga',200:'ravi',300:'shiva'}
{100:'durga',200:'ravi',300:'shiva',400:'pavan'}
{100:'sunny',200:'ravi',300:'shiva',400:'pavan'}

How to delete elements from dictionary?


1)del d[key]
------------
it deletes entry associated with the specified key.
if the key is not available then we will get keyerror.
d={100:"durga",200:"ravi",300:"shiva"}
print(d)
del d[100]
print(d)
del d[400]
output
{100:'durga',200:'ravi',300:'shiva'}
{200:'ravi',300:'shiva'}
keyerror:400

2)d.clear()
---------
To remove all entries from the dictionary.
d={100:"durga",200:"ravi",300:"shiva"}
print(d)
d.clear()
print(d)

output:
{100:'durga',200:'ravi',300:'shiva'}
{}

3)del d:
-------
to delete total dictionary. Now we cannot access d.
d= {100:"durga",200:'ravi',300:"shiva"}
print(d)
del d
print(d)
output:
-------
{100:'durga',200:'ravi',300:'shiva'}
nameerror: name 'd' is not defined

Important functions of dictionary:


----------------------------------
1)dict():
to create a dictionary

d=dict()-> it creates dictionary


d=dict({100:"durga",200:"ravi"})-> it creaters dictionary with specified elements
d=dict([(100,"durga"),(200,"shiva"),(300,"ravi")])
-> it creates dictionary with the given list of tuple elements
2)len():
returns the number of items in the dictionary.

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

4)get():
To get the value associated with the key
d.get(key)
if the key is available then returns the corresponding value otherwise returns None.it wont
raise any error.
d.get (key,defaultvalue)
if the key is availble then returns the corresponding value otherwise returns default value.
d={100:"durga",200:"ravi",300:"shiva"}
print(d[100])-> durga
print(d[400])->keyerror:400
print(d.get(100))->durga
print(d.get(400))->none
print(d.get(100,'Guest'))->durga
print(d.get(400,'Guest'))->Guest

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

d={100:"durga",200:"ravi",300:"shiva"}
print(d.pop(100))
print(d)
print(d.pop(400))

output
------
durga
{200:'ravi',300:'shiva'}
KeyError:400

6)popitem():
-------------
It removes an arbitrary item(key-value)from the dictionary and returns it.

d={100:"durga",200:"ravi",300:"shiva"}
print(d)
print(d.popitem())
print(d)

output
------
{100:'durga',200:'ravi',300:'shiva'}
(300,'shiva')
{100:'durga',200:'ravi'}
if the dictionary is empty then we will get KeyError
d={}
print(d.popitem())==>KeyError:'popitem():dictionary is empty'

7)keys():
----------
it returns all keys associated with dictionary.

d={100:"durga",200:"ravi",300:"shiva"}
print(d.keys())
for k in d.keys():
print(k)

output
------
dict_keys([100,200,300])
100
200
300

8)values():
-----------
It returns all values associated with the dictionary.

d={100:"durga",200:"ravi",300:"shiva"}
print(d.values())
for v in d.values():
print(v)

output
------
dict_values(['durga','ravi','shiva'])
durga
ravi
shiva

9)items():
----------
It returns list of tuples representing key-value pairs.
[(k,v),(k,v),(k,v)]
d={100:"durga",200:"ravi",300:"shiva"}
for k,v in d.items():
print(k,"--",v)

output
-------
100--durga
200--ravi
300--shiva

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

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

d={100:"durga",200:"ravi",300:"shiva"}
print(d.setdefault(400,"pavan"))
print(d)
print(d.setdefault(100,"sachin"))
print(d)

output
-------
pavan
{100:'durga',200:'ravi',300:'shiva',400:'pavan'}
durga
{100:'durga',200:'ravi',300:'shiva',400:'pavan'}

12)update():
-------------
d.update(x)
All items present in the dictionary x will be added to dictionary d
Q) write a program to take dictionary from the keyboard and print the sum of values?
-------------------------------------------------------------------------------------
d=eval(input("Enter dictionary:"))
s=sum(d.values())
print("sum=",s)

output
------
D:\python_classws>py test.py
Enter dictionary:{'A':100,'B':200,'c':300}
sum=600

Q)write a program to find number of occurences of each letter present in the given string?
-------------------------------------------------------------------------------------------
word=input("enter any word:")
d={}
for x in word:
d[x]=d.get(x,0)+1
for k,v in d.items():
print(k,"occurred",v,"times")

output
------
D:\python_classws>py test.py
Enter any word:mississippi
m occurred 1 times
i occurred 4 times
s occurred 4 times
p occurred 2 times

Q)write a program to find number of occurrences of each vowel present in the given string?
-------------------------------------------------------------------------------------------
word=input("Enter any word:")
vowels={'a','e','i','o','u'}
d={}
for x in word:
for x in vowels:
d[x]=d.get(x,0)+1
for k,v in sorted(d.items()):
print(k,"occurred",v,"times")

output
-------
D:\python_classws>py test.py
Enter any word:doganimaldoganimal
a occurred 4 times
i occurred 2 times
o occurred 2 times

Q)write a program to accept student name and marks from the keyboard and creates a
dictionary.also display student marks by taking
---------------------------------------------------------------------------------------------------------------------------
---------
student name as input?
-----------------------

n=int(input("Enter the number of students:"))


d={}
for i in range(n):
name=input("Enter student Name:")
marks=input("Enter student Marks:")
d[name]=marks
while True:
name=input("Enter student Name to get marks:")
marks=d.get(name,-1)
if marks==-1:
print("student not found")
else:
print("the marks of",name,"are",marks)
option=input("Do you want to find another student marks[Yes|No]")
if option=="No":
break
print("Thanks for using our application")

output
------

D:\python_classws>py test.py
Enter the number of students:5

Enter Student Name:sunny


Enter Student Marks:90

Enter Student Name:banny


Enter Student Marks:80

Enter Student Name:chinny


Enter Student Marks:70

Enter Student Name:pinny


Enter Student Marks:60

Enter Student Name:


vinny
Enter Student Marks:50

Enter Student Name to get Marks:sunny


The Marks of sunny are 90

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

Enter Student Name to get Marks:durga


Student not found
Do you want to find another student marks[Yes|no]No
Thanks for using our application

Dictionary Comprehension:
--------------------------
Comprehension concept application for dictionaries also.

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


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

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

----------------------------------------------------------------------------------------------------------

FUNCTIONS
----------
-If a group of statements is repeatedly required then
it is not recommended to write these statements everytime seperately.
we have to define these statements as a single unit and we can call that unit
any number of times based on our requirement without rewriting.
This unit is nothing but function
-The main advantage of functions is code reusability.

Note:In other language functions are known as methods,procedures,subroutines etc

Python supports 2 types of functions


1)Built in functions
2)User Defined Functions

1)Built in functions
----------------------
The functions which are coming along with python software automatically,
are called built in functions or pre defined functions.

Eg:
----
id()
type()
input()
eval()
etc..

2)User Defined Functions:


--------------------------
The functions which are developed by programmer explicitly according
to business requiremets, are called user defined functions.

Syntax to create User defined Functions:


----------------------------------------
def function_name(parameters):
"""doc string"""
---
----
return value

note:
-----
while creating functions we can use 2 keywords
1)def(mandatory)
2)return(optional)

Eg 1:
-----
write a function to print hello

test.py
-------
1)def wish():
2) print("hello Good Morning")
3) wish()
4) wish()
5) wish()

Parameters
-----------
parameters are inputs to the function.if a function contains parameters,
then at the time of calling,compulsory we should provide
values otherwise, we will get error.

Eg:
---
write a function to take name of the student as input and print wish message by name.
1) def wish(name):
2) print("hello",name,"Good Morning")
3) wish("durga")
4) wish("Ravi")

D:/Python_classses>py test.py
Hello Durga Good morning
Hello Ravi Good Morning

Eg:write a function to take number as input and print its square value
--

1) def squarelt(number):
2) print("The Square of",number,"is",number*number)
3) squarelt(4)
4) squarelt(5)

D:/Python_classses>py test.py
The Square of 4 is 16
The Square of 5 is 25

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

Q)write a function to accept 2 numbers as input and return sum


----------------------------------------------------------------
1)def add(x,y):
2) return x+y
3) result=add(10,20)
4) print("The sum is",result)
5) print("The sum is",add(100,200))

D:/Python_classses>py test.py
The sum is 30
The sum is 300

If we are not writing return statement then default return value is None.
1) def f1():
2) print("Hello")
3) f1()
4) print(f1())

output
-------
Hello
Hello
None

Q) write a function to check whether the given number is even or odd?


----------------------------------------------------------------------

1)def even_odd(num):
2) if num%2==0:
3) print(num,"is Even Number")
4) else:
5) print(num,"is odd number")
6) even_odd(10)
7) even_odd(15)

output
-------
D:/Python_classses>py test.py
10 is even number
15 is odd number

Q) write a function to find factorial of given number?


-------------------------------------------------------
def fact(num):
if num==0:
result=1
else:
result=num*fact(num-1)
return result

x=int(input("Enter a no:"))
print("factorial of",x," =",fact(x))

Output
-------
D:/Python_classses>py test.py
The Factorial of 1 is : 1
The Factorial of 2 is : 2
The Factorial of 3 is : 6
The Factorial of 4 is : 24

Returning Multiple Values from a Function:


-------------------------------------------
In other languages like c,c++ and java,function can return atmost one value.But in Python,a
function can return any number of values.

Eg 1:
------
1) def sum_sub(a,b):
2) sum=a+b
3) sub=a-b
4) return sum,sub
5) x,y=sum_sub(100,50)
6) print("The sum is :",x)
7) print("The substraction is:",y)

Output
------
The sum is: 150
The substraction is :50

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

Output:
-------
The Results are
150
50
5000
2.0

Types of arguments
-------------------
def f1(a,b)
------
------
------
f1(10,20)

a,b are formal arguments where as 10,20 are acutal arguments.

There are 4 types are actual arguments are allowed in python.


1) Positional Arguments
2) Keyword Arguments
3) Default Arguments
4) variable Length Arguments

1) Positional Arguments
-----------------------
-> These are the arguments passed to function in correct positional order.
def sub(a,b)
print(a-b)

sub(100,200)
sub(200,100)
-> The number of arguments and postion of arguments must be matched.if we change the
order then result may be changed.
-> If we change the number of arguments then we will get error.

2)Keyword Arguments:
--------------------
we can pass argument values by keyword i.e, by parameter name.

1) def wish(name,msg):
2) print("hello",name,mgs)
3) wish(name="Durga",mgs="Good Morning")
4) wish(mgs="Good Morning",name="Durga")

Output
------
Hello Durga Good Morning
Hello Durga Good Morning
Here the order of arguments is not important but number of arguments must be matched.

Note:
----
We can use both positional and keyword arguments simultaneously.But first we have to take
positional arguments and then keyword arguments,otherwise we will get syntax error.

1) def wish(name,msg):
2) print("Hello",name,mgs)
3) wish("Durga","GoodMorning")->valid
4) wish("Durga",msg="GoodMorning")->valid
5) wish(name="Durga","GoodMorning")->invalid
6) SyntaxError:positional argument follows keyword argument

3)Default Arguments:
---------------------
sometimes we can provide default values for our positional arguments.

1) def wish(name="Guest"):
2) print("Hello",name,"Good Morning")
3) wish("Durga")
4) wish()

Output
-------
Hello Durga Good Morning
Hello Guest Good Morning
If we are not passing any name then only default value will be considered

***Note:
--------
After default arguments we should not take non default arguments.

1) def wish(name="Guest",msg="Good Morning"):->valid


2) def wish(name,msg="Good Morning"):->valid
3) def wish(name="Guest",msg):->Invalid

SyntaxError:non-default argument follows default argument

4)variable Length Arguments:


----------------------------

-sometimes we can pass variable number of arguments to our function,such type of


arguments are called variable length arguments.
-We can declare a variable length argument with *symbol as follows
-def f1(*n):
-we can call this function by passing any number of arguments including zero number.
-Internally all these values represented in the form of tuple.

1) def sum(*n):
2) total=0
3) for n1 in n:
4) total=total+n1
5) print("The Sum=",total)
6)
7) sum()
8) sum(10)
9) sum(10,20)
10) sum(10,20,30,40)

Output
-------
The sum=0
The sum=10
The sum=30
The sum=100

Note:
-----
we can mix variable length arguments with positional arguments.

1) def f1(n1,*s):
2) print(n1)
3) for s1 in s:
4) print(s1)
5)
6) f1(10)
7) f1(10,20,30,40)
8) f1(10,"A",30,"B")

Output
-------
10
10
20
30
40
10
A
30
B

Note:
----
After variable length argument,if we are taking any other arguments then we should provide
values as keyword arguments.
1) def f1(*s,n1):
2) for s1 in s:
3) print(s1)
4) print(n1)
5)
6) f1("A","B",n1=10)

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

Note:
----
We can declare key word variable length arguments also.
*For thia we have to use**.
*def f1(**n):
*we can call this function by passing any number of keyword arguments.internally these
keyword arguments will be stored inside a dictionary

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

Output
------
n1 = 10
n2 = 20
n3 = 30
rno = 100
name = Durga
marks = 70
subject = Java

Case Study:
-----------

def f(arg1,arg2,arg3=4,arg4=8):
print(arg1,arg2,arg3,arg4)
1) f(3,2)-> 3 2 4 8

2) f(10,20,30,40)-> 10,20,30,40

3) f(25,50,arg4=100)->25 50 4 100

4) f(arg4=2,arg1=3,arg2=4) -> 3 4 4 2

5) f()-> Invalid
TypeError: f() missing 2 required positional arguments:'arg1' and 'arg2'

6) f(arg3=10,arg4=20,30,40)-> Invalid
SyntaxError: positional argument follows keyword argument
[After Keyword arguments we should not take positional arguments]

7) f(4,5,arg2=6)->Invalid
TypeError:f()got an multiple values for argument 'arg2'

8) f(4,5 arg3=5,arg5=6)->Invalid
TypeError:f() got an unexpected keyword argument 'arg5'

Note:
-----
Function vs module vs Library
1) A group of lines with some name is called a function
2) A group of functions saved to a file, is called module
3) A group of modules is nothing but library

Library
------------------------------
module1 module2
-------- --------
function 1 function 1
function 2 function 2
function 3 function 3

function

---------
---------
---------
---------
---------
---------
---------
---------

Types of Variables
-------------------
python supports 2 types of variables.
1) Global Variables
2) local Variables

1) Global Variables
--------------------
- The variables which are declared outside of function are called global variables.
- These variables can be accessed in all functions of that module.

1) a=10 #global variable


2) def f1():
3) print(a)
4)
5) def f2():
6) print(a)
7)
8) f1()
9) f2()

Output
------
10
10

2)Local Variables:
------------------
* The variables which are declared inside a function are called local variables.
* Local variables are available only for the function in which we declared it.i.e from outside of
function we cannot access.

1) def f1():
2) a=10
3) print(a) #valid
4)
5) def f2():
6) print(a) #invalid
7)
8) f1()
9) f2()

NameError: name'a' is not defined

Global keyword:
---------------
we can use global keyword for the following 2 purposes:
1) To declare global variable inside function
2) To make global variable available to the function so that we can perfom required
modifications

1) a=10
2) def f1():
3) a=777
4) print(a)
5)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()
11)

Output
-------
777
10

1) a=10
2) def f1():
3) global a
4) a=777
5) print(a)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()

Output
------
777
777

1) def f1():
2) a=10
3) print(a)
4)
5) def f2():
6) print(a)
7)
8) f1()
9) f2()

Output:
-------
NameError:name'a' is not defined
1) def f1():
2) global a
3) a=10
4) print(a)
5)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()

Output:
-------
10
10

Note:
----
If global variable and local variable having the same name then we can access global
variable inside a function as follows

1) a=10->Global variable
2) def f1():
3) a=777->Local Variable
4) print(a)
5) print(globals()['a'])
6) f1()

Output
-------
777
10

Recursive functions
-------------------
A function that calls itself is known as Recursive Function.
Eg:
---
factorial(3)= 3*factorial(2)
= 3*2*factorial(1)
= 3*2*1*factorial(0)
= 3*2*1*1
=6
factorial(n)= n*factorial(n-1)

The main advantage of recursive functions are:


1) we can reduce length of the code and improves readability.
2) we can solve complex problems very easily.

Q) Write a Python Function to find factorial of given Number with Recursion


----------------------------------------------------------------------------

1) def factorial(n):
2) if n==0:
3) result=1
4) else:
5) result=n*factorial(n-1)
6) return result
7) print("Factorial of 4 is:",factorial(4))
8) print("Factorial of 5 is:",factorial(5))

Output
------
Factorial of 4 is: 24
Factorial of 5 is : 120

Anonymous Functions:
--------------------
-Sometimes we can declare a function without any name,such type of nameless functions
are called anonymous functions or lambda functions.
-The main purpose of anonymous function is just for instant use(i,e for one time usage)

Normal Function:
----------------
We can define by using def keyword.
def squarelt(n):
return n*n

Lambda Function:
----------------
we can define by using lambda keyword lambda n:n*n

Syntax of lambda Function:


--------------------------
lambda argument_list:expression

Note:
-----
By using lambda Functions we can write very concise code so that readability of the program
will be improved.

Q)Write a Program to create a lambda function to find Square of given number?


-------------------------------------------------------------------------------
1) s=lambda n:n*n
2) print("The Square of 4 is:",s(4))
3) print("The Square of 5 is:",s(5))

Output
-------
The square of 4 is:16
The square of 5 is:25

Q) Lambda Function to find Sum of 2 given Numbers


-------------------------------------------------
1) s= lambda a,b:a+b
2) print("The Sum of 10,20 is:",s(10,20))
3) print("The Sum of 100,200 is:",s(100,200))

Output
-----
The Sum of 10,20 is: 30
The Sum of 100,200 is: 300

Q) Lambda Function to find biggest of given Values


--------------------------------------------------
1) s=lambda a,b:a if a>b else b
2) print("The Biggest of 10,20 is:",s(10,20))
3) print("The Bigggest of 100,200 is:",s(100,200))

Output
------
The Biggest of 10,20 is:20
The Biggest of 100,200 is:200

Note:
-----
Lambda Function internally returns expression value and we are not required to write return
statement explicitly.

Note:
-----
Sometimes we can pass function as argument to another function.In such cases lambda
functions are best choice.

We can use lambda functions very commonly with filter(),map() and reduce() functions,
because these functions expect function as argument.

Filter() Function:
------------------
We can use filter() function to filter values from the given sequence based on some
comdition.

filter(function,sequence)

Where Function Argument is responsible to perform conditional check sequence can be List
OR Tuple OR String.

Q) Program to filter only Even Numbers from the List by using filter() Function?
---------------------------------------------------------------------------------

Without Lambda Function:


-----------------------
1) def is Even(x):
2) if x%2==0:
3) return True
4) else:
5) return False
6) l=[0,5,10,15,20,25,30]
7) l1=list(filter(isEven,l))
8) print(l1) #[0,10,20,30]

With Lambda Function:


---------------------
1) l=[0,5,10,15,20,25,30]
2) l1=list(filter(lambda x:x%2==0,l))
3) print(l1) #[0,10,20,30]
4) l2=list(filter(lambda x:x%2!=0,l))
5) print(l2) #[5,15,25]

map()Function:
--------------
-> For every element present in the given sequence,apply some functionality and generate
new element with the required modification.For this requirement we should go for map()
function.

-> Eg:For every element present in the list perform double and generate new list of doubles.

Syntax:
-------
map(function,sequence)

-> The function can be applied on each element of sequence and generates new sequence.

Without Lambda
--------------------
1) l=[1,2,3,4,5]
2) def doublelt(x):
3) return 2*x
4) l1=list(map(doublelt,l))
5) print(l1) #[2,4,6,8,10]
With Lambda
------------
1) l=[1,2,3,4,5]
2) l1=list(map(lambda x:2*x,l))
3) print(l1) #[2,4,6,8,10]

Eg 2:
-----
To find square of given numbers

1) l=[1,2,3,4,5]
2) l1==list(map(lambda x:x*x,l))
3) print(l1) #[1,4,9,16,25]

We can apply map() function on multiple lists also.But make sure all list should have same
length.

Syntax:
-------
map(lambda x,y:x*y,l1,l2))
x is from l1 and y is from l2

1) l1=[1,2,3,4]
2) l2=[2,3,4,5]
3) l3=list(map(lambda x,y:x*y,l1,l2))
4) print(l3) #[2,6,12,20]

reduce()Function:
-----------------
- reduce()function reduces sequences of elements into a single element by applying the
specified function.
- reduce(function,sequence)
- reduce() function present in functools module and hence we should write import statement.

1) from functools import*


2) l=[10,20,30,40,50]
3) result=reduce(lambda x,y:x+y,l)
4) print(result) #150

Eg:
---
1) result=reduce(lambda x,y:x*y,l)
2) print(result) #12000000

Eg:
---
1) from functools import*
2) result=reduce(lambda x,y:x+y,range(1,101))
3) print(result) #5050

Everything is an Object:
------------------------
- In Python every thing is treated as object.
- Even functions also internally treated as objects only.

1) def f1():
2) print("Hello")
3) print(f1)
4) print(id(f1))

Output:
-------
<function f1 at 0x00419618>
4298264

Function Aliasing:
------------------
For the existing function we can give another name,which is nothing but function aliasing.

1) def wish(name):
2) print("Good Morning:",name)
3)
4) greeting=wish
5) print(id(wish))
6) print(id(greeting))
7)
8) greeting('Durga')
9) wish('Durga')

Output:
------
4429336
4429336
Good Morning:Durga
Good Morning:Durga

Note:
----
- In the above example only one functional is available but we can call that function by using
either wish name or greeting name.
- If we delete one name still we can access that function by using alias name.

1) def wish(name):
2) print("Good Morning:",name)
3)
4) greeting=wish
5)
6) greeting('Durga')
7) wish('Durga')
8)
9) del wish
10) #wish('Durga')->NameError: name'wish'is not defined
11) greeting('pavan')
Output:
-------
Good Morning:Durga
Good Morning:Durga
Good Morning:pavan

Nested Functions:
---------------------
We can declare a function inside another function,such type of functions are called Nested
functions.

def f1():
def inner(a,b):
print("The sum=",a+b)
print("The Average=",(a+b)/2)
print()
inner(10,20)
inner(20,30)
inner(40,50)
inner(100,200)
f1()

eg:2
-----

1) def outer():
2) print("outer function started")
3) def inner():
4) print("inner function execution")
5) print("outer function calling inner function")
6) inner()
7) outer()
8) #inner()->NameError:name'inner' is not defined

Output:
-------
outer function started
outer function calling inner function
inner function execution

In the above example inner() function is local to outer() function and hence it is not possible
to call directly from outside of outer()function.

Note:
-----
A function can return another function.

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
inner function execution
inner function execution

Q)What is the difference 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)

Decorators:
------------
Bride===>Beautiparlour...==>Heroine

Input Function==>Decorator Function==>Outputfunction with extended functionality


Decorators help to make our code shorter and more pythonic(more shorter)

new Functionality 10000lines....but existing function is already there 9900.


so must use existing function in new function.

def decor(func):
def inner(name):
if name=='sunny':
print("Hello sunny bad moring..")
else:
func(name)
return inner
@decor
def wish(name):
print("Hello",name,"Good Morning")

wish("Naresh")
wish("Ravi")
wish("Sunny")

eg:2
def decor(func):
def inner(name):
if name=='sunny':
print("Hello sunny bad moring..")
else:
func(name)
return inner

def wish(name):
print("Hello",name,"Good Morning")
decorfunction=decor(wish)
wish("Sunny")
decorfunction("Sunny")

wish("NARESH")
decorfunction("NARESH")

EG:3
def smartdivision(func):
def inner(a,b):
if b==0:
print("Hello stupid..How can divide with zero")

else:
return func(a,b)
return inner

@smartdivision
def division(a,b):
retun a/b

print(division(10,2))
print(division(10,5))
print(division(10,0))

---------------------------------------------------------------------------------------------------------------------------
----------

MODULES
-------
- A group of functions, variables and classes saved to a file, which is nothing but module.
- Every python file(.py) acts as a module.

durgamath.py
-------------

1) x=888
2)
3) def add(a,b):
4) print("The Sum:",a+b)
5)
6) def product(a,b):
7) print("The product:",a*b)

durgamath module contains one variable and 2 functions.


- If we want to use members of module in our program then we should import that module.
import modulename
- We can access members by using module name.
modulename.variable
modulename.function()

test.py:
--------
1) import durgamath
2) print(durgamath.x)
3) durgamath.add(10,20)
4) durgamath.product(10,20)

Output
------
888
The Sum: 30
The Product:200

Note:
----
Whenever we are using a module in our program,for that module compiled file will be
generated and stored in the hard disk permanently.

Renaming a module at the time of import


----------------------------------------
(Module Aliasing):
------------------
- Eg: import durgamath as m
- Here durgamath is original module name and m is alias name.
- We can access members by using alias name m

test.py:
-------
1) import durgamath as m
2) print(m.x)
3) m.add(10,20)
4) m.product(10,20)
from...import:
--------------
We can import particular members of module by using from...import.
The main advantage of this is we can access members directly without using module name.

1) from durgamath import x,add


2) print(x)
3) add(10,20)
4) product(10,20)-> NameError:name'product'is not defined

We can import all members of a module as follows from durgamath import*

test.py:
--------
1) from durgamath import*
2) print(x)
3) add(10,20)
4) product(10,20)

Various Possibilities of import:


--------------------------------
1) import modulename
2) import module1,module2,module3
3) import module1 as m
4) import module1 as m1,module2 as m2,module3
5) import module import member
6) from module import member1,member2,member3
7) from module import member1 as x
8) from module import*

Member Aliasing:
----------------
1) from durgamath import x as y, add as sum
2) print(y)
3) sum(10,20)

Once we defined as alias name,we should use alias name only and we should not use
original name

1) from durgamath import x as y


2) print(x)-> NameError:name'x' is not defined

Reloading a Module:
-------------------
By default module will be loaded only once eventhough we are importing multiple times.

module1.py:
----------
print("This is from module1")

test.py
--------
1) import module1
2) import module1
3) import module1
4) import module1
5) print("This is test module")

Output
------
This is from module1
This is test module

- In the above program test module will be loaded only once eventhough we are importing
multiple times.

- The problem in this approach is after loading a module if it is updated outside then updated
version of module1 is not available to our program.

- We can solve this problem by reloading module explicitly based on our requirement.
- We can reload by using reload() function of imp module.

1) import imp
2) imp.reload(module1)

test.py:
--------
1) import module1
2) import module1
3) from imp import reload
4) reload(module1)
5) reload(module1)
6) reload(module1)
7) print("This is test module")

In the above program module1 will be loaded 4 times in that 1 time by default and 3 times
explicity. In this case output is

1) This is from module1


2) This is from module1
3) This is from module1
4) This is from module1
5) This is test module

The main advantage of explicit module reloading is we can ensure that updated version is
always available to our program.

Another example:

module1.py:
----------
1.print("This is from module1")

test.py:
-------
import time
from imp import reload
import module1
print("profram enter into sleeping state")
time.sleep(30)
reload(module1)
print("program entering into again sleeping state")
reload(module1)
print("this is the last line")

Finding Members of Module by using dir()Function:


-------------------------------------------------
Python provides inbuilt function dir() to list out all members of current module or a specified
module.

dir()->To list out all members of current module


dir(moduleName)->To list out all members of specified module

Eg 1:test.py
------------
1) x=10
2) y=20
3) def f1()
4) print("hello")
5) print(dir()) #To print all members of specified module

Eg 1:test.py
------------
1) x=10
2) y=20
3) def f1():
4) print("Hello")
5) print(dir()) #To print all members of current module

Output
------
['_annotations_','_builtins_','_cached_','_doc_','file_','_loader_','_name_','package_','_spec_','
f1','x','y']

Eg 2:
----
To display members of particular module

durgamath.py:
--------------
1) x=888
2)
3) def add(a,b)
4) print("The sum:",a+b)
5)
6) def product(a,b):
7) print("The product:",a*b)

test.py:
--------
1) import durgamath
2) print(dir(durgamath))

output
-------
['_builtins_','_cached_','_doc_','_file_','_loader_','_name_','_package_','_spec_','add','product'
,'x']

Note:
-----
For every module at the time of execution python interpreter will add some special
properties automatically for internal use.

Eg:
---
_builtins_,_cached_,_doc_,_file_,_loader_,_name_,_package_,_spec_

Based on our requirement we can access these properties also in our program.

Eg:
---
test.py

1)print(_builtins_)
2)print(_cached_)
3)print(_doc_)
4)print(_file_)
5)print(_loader_)
6)print(_name_)
7)print(_package_)
8)print(_spec_)

Output
-------
<module'builtins'(built-in)>
None
None

test.py
-------

1)<_frozen_importlib_external.SourceFileLoader object at 0x00572170>


2) _main_
3) None
4) None

The Special Variable_name_:


---------------------------
- For every Python program,a special variable_name_will be added internally.
- This variable stores information regarding whether the program is executed as an individual
program or as a module.
- If the program executed as an individual program then the value of this variable is _main_
- If the program executed as a module from some other program then the value of this
variable is the name of module where it is defined.
- Hence by using this_name_variable we can identify whether the program executed directly
or as a module.

Demo program:
-------------

module1.py:
-----------
1) def f1():
2) if_name_=='_main_':
3) print("The code executed as a program")
4) else:
5) print("The code executed as a module from some other program")
6) f1()

test.py:
--------
1) import module1
2) module1.f1()

D:\Python_classes>py module1.py
The code executed as a program

D:\Python_classes>py test.py
The code executed as a module from some other program
The code executed as a module from some other program

Working with math Module:


-------------------------
- Python provides inbuilt module math.
- This module defines several functions which can be used for mathematical operations.
- The main important functions are
1) sqrt(x)
2) ceil(x)
3) floor(x)
4) fabs(x)
5) log(x)
6) sin(x)
7) tan(x)
8) ....

1) from math import*


2) print(sqrt(4))
3) print(ceil(10.1))
4) print(floor(10.1))
5) print(fabs(-10.6))
6) print(fabs(10.6))

Output
-------
2.0
11
10
10.6
10.6

Note:
-----
We can find help for any module by using help() function

Eg:
---
import math
help(math)

Working with random module:


---------------------------
- This module defines several functions to generate random numbers.
- We can use these functions while developing games, in cryptography and to generate
random numbers on fly for authentication.

1) random()Function:
--------------------
This function always generate some float value between 0 and 1( not inclusive)
0<x<1
1) from random import*
2) for i in range(10):
3) print(random())

Output
------
0.4572685609302056
0.6584325233197768
0.15444034016553587
0.18351427005232201
0.1330257265904884
0.9291139798071045
0.6586741197891783
0.8901649834019002
0.25540891083913053
0.7290504335962871

2) randint() Function:
---------------------
To generate random integer betweeen two given numbers(inclusive)

1) from random import*


2) for i in range(10):
3) print(randint(1,100)) # generate random int value between 1 and 100(inclusive)
Output
------
51
44
39
70
49
74
52
10
40
8

3)uniform()Function:
---------------------
It returns random float values between 2 given numbers(not inclusive)

1) from random import*


2) for i in range(10):
3) print(uniform(1,10))

Output:
-------
9.578477968323773
7.7350642246780374
2.0572938669434535
1.0902143578722594
8.41020155782424
2.940478753853089
9.726156649079659
2.222538546560088
9.940249578591855
4.218384799153155

random()-> in between 0 and 1 (not inclusive)


randint(x,y) -> in between x and y (inclusive)
uniform(x,y) -> in between x and y (not inclusive)

4) randrange([start],stop,[step])
---------------------------------
- Returns a random number from range
- start <=x<stop
- start argument is optional and default value is 0
- step argument is optional and default value is 1

- randrange(10)-> generates a number from 0 to 9


- randrange(1,11)-> generates a number from 1 to 10
- randrange(1,11,2)-> generates a number from 1,3,5,7,9

1) from random import*


2) for i in range(10):
3) print(randrange(10))
Output:
-------
9
4
0
2
9
4
8
9
5
9

1) from random import*


2) for i in range(10):
3) print(randrange(1,11))

Output:
-------
2
2
8
10
3
5
9
1
6
3

1) from random import*


2) for i in range(10):
3) print(randrange(1,11,2))

Output:
--------
1
3
9
5
7
1
1
1
7
3

5) choice() Function:
----------------------
- It wont't return random number.
- It will return a random object from the given list or tuple.
1) from random import*
2) list=["Sunny","Bunny","chinny","vinny","pinny"]
3) for i in range(10):
4) print(choice(list))

Output:
-------
Bunny
pinny
Bunny
Sunny
Bunny
pinny
pinny
vinny
Bunny
SunnyS

You might also like