Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python - Clouds It Guru

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 289

1

Introduction to Python
1. Under the leadership of “Andrew StuartTanenbaum” a Group of employees
developed Distributed operating system.
2. Group of employees used ABC Scripting Language to develop “Distributed
Operating”.
3. ‘ABC’ scripting language is very simple and easy to learn and work.
4. “Guido Van Rossum” is a member in that group, and he likes ABC Scripting
Language very well as it is very simple and easy.
5. In Christmas holidays, Guido van Rossum started developing a new language to
be simpler and easy compared to ABC scripting language and all other existing
language.
6. Finally, he developed a new language.
7. He likes “Monty Python’s Flying Circus” English daily serial very well.
8. So finally, Guido Van Rossumtaken the word ‘PYTHON’ from that serial and
kept for his language.
9. So finally, Guido Van Rossum developed PYTHON Scripting language at the
“National Research Institute” for Mathematics and Computer Science in
Netherlands in 1989 and it available to the public in 1991.
10. Python is now maintained by a core development team at the institute, although
Guido van Rossum still holds a vital role in directing itsprogress.
11. Python 1.0 was released in January 1994.
12. Python 2.0 was released in October 2000 and Python 2.7.11 is the last edition of
Python 2.
13. Meanwhile, Python 3.0 was released in December 2008.
14. Python is a “General-Purpose High Level Programming Language”.
15. Python is recommended as first programming language for beginners.
16. Guido Van Rossum has developed Python language by taking almost all
programming features from different languages.
17. The most of syntaxes in python have taken from C and ABC languages.
2

Scripting and Programming Language


Scripting Language:

1. Scripting Language based applications are run by interpreter.

2. Scripting Languages based applications are not required explicit compilation.

3. We can run there scripting language-based language directly.

4. Example of scripting languages are Shell Script, Python, Perl, Ruby, PowerShell…. these

all languages are run by interpreter, that’s why these all languages are called scripting

languages.

ProgrammingLanguage:

1. Programming language-based applications are run by compiler.

2. Programming language-based applications are required explicit compilation.

3. Programming language-based applications can’t rundirectlywithoutcompilation.

4. . Examples of Programming languages are C, C++, JAVA, .NET… these all-

programming languages are run by compiler. That’s why these all languages are

called Programming languages.

Note: Most of the people call Python is a scripting language because the way of

developing Python applications and executing Python applications are similar to

scripting languages.

Different Languages used to develop Python:

1. Procedural Oriented Language...C.

2. Object Oriented Programming Language……C++, JAVA.

3. Scripting Languages...Shell Script, Perl.

4. Modular Programming Language...Modula


3

Featured Of Python

1. Python is simple, easy, and powerful language:

a. The syntax of is very simple and easy to remember so anybody can easily remember

the python syntax without having any programming basics.

b. Even non-technical persons also can learn or work with python language. So here

developers not required focusing on syntaxes,

c. It allows programmer to concentrate on the solution to the problem rather than the

language itself.

d. Reading a Python program feels almost like reading English, although very strict

English. This pseudo-code nature of Python is one of its greatest strengths.

e. This elegant syntax of Python language makes the developers to express their

business logic in very less lines of code. So, when developers write less code than

automatically application development time, application cost and also application

maintenance time also will be decreased.

f. That’s why Python is also called programmer-friendly language.

g. Python has few keywords, simple structure, and a clearly defined syntax. This allows

the student to pick up the language quickly.

2. Python is an Expressive Language:

a. Python language is more expressive. The sense of expressive is the code is easily

understable.

3. Python is Free, Open & Redistribution Language:

a. Python is an example of Floss(Free/Libre and Open-Source Software).

b. Floss is a community, which itself is based onthe conceptof sharing knowledge.

Flossare free for usage, modification, and redistribution.


4

Example of Floss are:

1. Linux

2. Ubuntu

3. LibreOffice

4. Mozilla Firefox

5. Mono

6. Apache Web Server

7. VLC Player

4. Python is an Interpretable Language:

a. Python is an interpreted language i.e.; interpreter executes the python code line by line

ata time. So, we don’t need to compile our program before executing it. This

makes debugging easy and thus suitable for beginner.

5.Python is an extensible Language:

a. Python can completely integrate with components of Java and .Net and also can

invoke libraries of C and C++. So, here python perform CROSS language operation.

b. If we need a critical piece of code to run very fast, you can code that part of your

program in C or C++ and then use them from our python program.

6. Python is very rich in Libraries:

a. The Python is very rich in libraries. They help us to do various things involving regular

expressions, documentation generation, unit testing, threading, databases, web browsers,

CGI(Common Gateway Interface), ftp(File TransferProtocol), email, XML, WAV files,

cryptography, GUI(graphical user interfaces) using Tk(Toolkit), and also other system-

dependent stuff. Remember, all this is always available wherever Python is installed.
5

b. This is called the "batteries included" philosophy of Python.

7.Python is Oriented Programming Language:

a. Pythonsupports procedure-oriented programming as well as object-oriented

programming. In procedure-oriented language.

b. The program is built around procedures or functions which are nothing but

reusable pieces of programs. In object-oriented language.

c. The program is built around objects which combine data and functionality. Python is

very powerful in way of doing object-oriented programming, especially, when

compared to languages like C++ or Java.

8. Python is a Portable Language:

a. Due to its Open-source nature, Python has been ported to many flat forms.

b. All our Python programs will work on any platform without requiring any changes at

all. So, Python is also called Cross Platform language. c. We can use Python on

Linux, Windows, Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, BeOS, OS/390,

z/OS, Palm OS (also called Garnet OS), QNX, VMS, Psion, Acorn RISC OS,

VxWorks, PlayStation, Sharp Zaurus, Windows CE and PocketPC!

9. High-level Language:

a. When you write programs in Python, you never need to bother about the low-level details

such as managing the memory used by your program, etc.

b. The memory allocates dynamically when we run the application.

Some other features of Python Language:

1. Interactive Language
6

2. Beginners Language

3. Easy – to – learn

4. Easy – to – maintain

5. Easy to – work

6. Supports all major commercial database

7. Supports GUI application

8. Scalable

9. Support multiple database

10. Support indentation

Installing Python:

Step 1: Goto www.python.org and download latest version of python, like below

Step2: Goto downloads folder and select downloaded python and run and install

Step3: Set variable path like bellow.

My computerpropertiesAdvanced system settingsenvironment variables Under

user variables, create new variable with name PATHlikebelow.

PATH=C:\Users\Narayana\AppData\Local\Programs\Python\Python36-32\Scripts\,

C:\Users\Narayana\AppData\Local\Programs\Python\Python36-32\.

What can we do by using python?

By using python, we can develop

1. GUI Applications

2. Data Analysis Applications


7

3. Gaming Applications

4. Scripting Applications

5. Task Applications

6. Network Applications

7. Animation Applications

8. Test Cases Applications

Simply python can be used to make games, do data analysis, control robot, hardware, create

GUIs or eve to create website.

Advantage &Disadvantage of Python

Advantages:

 Open source – Free and can edit source code

 Dynamically typed – No need to specify the type of variable before/afterusing it.

 Interpreted language – Opposite to compiled language.

 Objected oriented language

 Scripting language

 Indentation – Whitespaces, No need of braces.

 Scripting language

 Easy to learn like normal English.

 Developed using ‘C’ language.

 Interface to Other programming languages. – Can include code from C, Java, .Net

using Cython, Cython and IronPython interfaces respectively.

 Platform independent – Works on multi platforms.

 Less code compared to other languages.


8

 No strict typing on variables and containers.

 Used by Lot many MNCs and worlds topmost organizations like Google, NASA,

MST, and Gaming apps etc.

 Huge library.

 Multi-Threading and Multi-processing.

Disadvantages:

 Slowcompared to other programming languages like C, C++, or java.

 Threading not fully implemented.

 All strings are not Unicode by default.

 Indentation – If mix tab and space.

 Not using for mobile Applications.

Some other points aboutPython:-

 Python is a general-purpose language.

 It has wide range of applications from web development, scientific and mathematical

computing todesktop Graphical User Interfaces (Pygame, Panda 3D).

 The syntax of the language is clean, and length of the code is relatively short. It’s fun

to work in python because it allows you to think about the problem rather than

focusing on the system.

Why should use learn Python?


9

There are four reason to learn python,

1. Very Simple Syntax:-

Python programming is very fun; it is very to understand and write the python code.

The syntax feels very natural.

E.g.:-

a=10

b=20

sum=a+b

print(sum)

so here if you even don’t have any programming knowledge before, we can easily guess

that this program is adding two numbers and print result.

2. Not overlystrict:-

 You don’t need to define the type of variable in python. Also, it’s not necessary to

odd semicolon at the end of the statement.

 Python enforces you to follow good practice these small things can make learning

much easier for beginner.

3. Expressiveness of the language:-

 Pythons allow to you write programs having greater functionality with fewer lines of

code.

 If we write 1000 lines of code by using any programming language, the same

functionality can be achieved in python with just 20% to 30% code of that

programming language. This is just one example; you will be amazed how much you

can do with python once you learn the basics.


10

4. Great Community and support:-

Pythonhas a large supporting community. These are numerous active forums online

which can be handy if you are stuck.

Some of them are:

a. Learn Python

b. Google Forum

c. Python Questions-stack overflow

How python datatypes compare to other languages:-

 Statically typed language:-

A language in which types are fixed at compile time. Most statically typed languages

enforce this by requiring you to declare all variables with their datatypes before using

them. Java and C are statically type language.

 Dynamically typed language:-

A language in which types are discovered at execution time; the opposite of statically

typed. VBScript and python are dynamically typed because they figure out what type

a variable is when you first assign it a value.

 Strong type language:-

A language in which types are always enforced. Java and python are strongly typed.

If you have an integer, you can’t treat it like a string without explicitly converting it

 Weakly type language:-


11

A language in which type may be ignored, the opposite of strongly typed: VBScript weakly

typed.

In VBScript, you can concatenate the string ‘12’ and integer 3 to get the string ‘123’ then

treat that as the integer 123, all without any explicit conversion.

So, python is both dynamically typed (because it doesn’t use explicit datatype declarations)

and strongly typed (because once a variable has a datatype, it actually matters).

Python Application or program development:-

Python is considered an interpreted language because python programs are executed by an

interpreter.

There are two ways to use the interpreter,

1. Interactive Mode

2. Script Mode

1. Interactive mode:- command line shell, we type Python programs, and the

interpreter prints the result:

>>> 10+20

30

 The chevron, >>>, is the prompt, that is used by interpreter to indicate that it is ready.

So that’s why when we enter 10+20 and click enter then immediately interpreter

return 30.

 This interactive mode is not used to develop any business applications. It is just used

to test the features of Python.

 In script mode, we write python program in a file and use the interpreter to execute

the content of that file. The extension of this file is .py.


12

 Here we can write our Python program in any of the editors or IDE’s.

 Different editors used for Python program are Notepad, Notepad++, EditPlus, nano,

edit, IDL...

 Different IDEs used for Python program are PyCharm, Eric, Eclipse,

PyScripter,Netbeans…

2.ScriptMode:-This script mode is used to develop business applications.

E.g.:

Open Python FileNew File,

Write your Python program herein the new file and save the file with an extension .py.

Like,

A=10

B=5

print(AB)

print(A+B)

save this file with FristProgram.py

open the file FirstProgram.py, click on run tab and then run module or press F5. Now we

can see the output in python shell.

Python Identifiers
13

 A Python identifier is a name used to identify a variable, function, class, module, or

other object. An identifier starts with a letter A to Z or a to z or an underscore (_)

followed by zero or more letters, underscores, and digits (0 to 9).

 Python doesn’t allow punctuation characters such as @, $, and % within identifiers.

 Python is a case sensitive programming language.

 Thus, Application and application are two different identifiers in Python.

 Any identifier starting with two leading underscores indicates a strong private

identifier.

1. An identifier should not start with digit, but it can contain digits, like,

>>> 12ab=100

>>> ab12=100Syntax Error: Invalid syntax

An identifier can contain underscores(single, double, and also triple)

>>> _total=10

>>> to_tal=20

>>> total_=30

>>> _to_tal_=40

>>> __total='Python'

>>> total__='Narayana'

>>> to__tal='Nani'

>>> ___total= 'Santoshi’

>>> ___to__tal_=100
14

An identifier must not contain special characters (expect underscore)

>>> @total=100 Syntax error: invalid error

>> to@tal=200 Syntax error: invalid syntax

>>> to@tal=200Syntax error: can’t assign to operator

>>> to$tal=20 Syntax error: invalid syntax

>>> total!=10 Name error: name total’ is not defined

>>>!total=10 Syntax error: invalid syntax

>>> total*=10 Name error: name total’ is not defined

>>>& to_tal=200 Syntax error: invalid syntax

>>> * total=20 Syntax error: started assignment target must

be in a list or tuple

>>> total % = 200 Name error: name total’ is not defined

Identifiers are case-sensitive so, python language is a case sensitive language.

>>> a=100

>>> A=200

>>> print(a) 100

>>> print(A) 200

>>> var='python'

>>> print(var)NameError: name 'Var' is not defined

Keywords or reserved words can’t be used as identifiers.


15

>>> if= 100 Syntax error: invalid syntax

>>> return= python’ Syntax error: invalid syntax

>>> def = dev’ Syntax error: invalid syntax

>>> del = 200 Syntax error: invalid syntax

Keywords

The keywords in python are having some predefined functionality. These keywords may

beused as constant or variable or any other identifiers.

and exec not


assert finally, or
break for pass
class from print
continue global raise
def if return
del import by
Elif in while
else is with
except lambda yield

>>> Import keyword

>>> keyword.kwlist

[ ['False', 'None', 'True', 'and', 'as', 'assert', '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']]

Python totally contains 32 keywords out of 33


16

Only True, False and None are capitalized.

Indentation

1. One of the most distinctive features of python is its use of indentation to mark blocks

of code.

2. Generally, we use curly braces in C, C++, and Java languages but in python curly

braces are not allowed to indicate block of code for class, function definition or flow

control. Blocks of code are denoted by indentation.

3. Instead of curly brace {},indentation is used to represent a block.

In_a_parents:

In_a_child:

In_a_ground_child

Im_another_child:

Im_another_grand_child:

Block 1
Block 2

Block 3

Block2, Continuation
Block1, continuation

The number of spaces in the indentation is variable, but all statement within the block must

be indented the same amount both blocks in this example are fine:

if true:

Print (“This condition is True”)

Else:
17

Print (“This condition is False”)

However, the second block in this e.g.,will generate or error because first print in the else part

is not following indentation:

Example:

a=10

b=20

if a>b:
print('Hi')
print(a)
print('you got a, right?')
if a==b:
print(a)
print(b)
print('both are equal')
if a<5:
print(a)
print (value of a is less than 5’)

else:

print (a,and’, b, are’ not equal)

print ( different value’)

else:

print (hello’)

print (b)

print (bye…’)

print (Thank you….’!)

output: -

hello
18

20
Bye….

Thank you….!

Multi-line Statement

 Statement in python typically end with a newline. Python does, however, allow the

use of the line continuation character (\) to denote that the line should continue.

For e.g.

total = item one+

item = two+

item = three

 Statement contained within the [ ],{},() brackets do not need use the line continuation

character.

For e.g.:

days [ Monday’,Tuesday’,Wednesday’,Thursday’,Friday’, ‘Saturday’]

Quotations in python

 Pythonaccepts single(‘), double (“) and triple (“or’”) quotes to denote sharing literals,

as long as the same type of quote starts and endsa string.

 Generally, triple quotes are used to write the string across, triple quotes are used to

write the string across multiple lines.

For Example,

All the following are legal


19

Word = ‘word’

Sentence = “This is a sentence”

Paragraph = “”””This is a paragraph. It is made up of multiple lines and

sentences“”””,

 Comments in Python

 Comments are use in programming to describe the purpose of the code. This helps

you as well as other programmers to understand the intend of the code.

 Comments are completely ignored by compilers & interpreters.

 As hash sign (#) that is not inside a string’sliteral begins a comment. All character

after the # and up to the physical lines and are part of the comments and the python

interpreter ignore them.

#! / user/ bin / python

# First comment

print “Hello, python!”, second comment “This will produce following result:”

Hello, python!

A comment may be on the same line after a statement or expression:

Name = “palatal” # declaring variable name you can comment multiple lines

as follows.

# Python is easy.

# Python is simple too

# Python is powerful too

# These are all comment

Some of the basic functions: -

Python supports so many functions. Some of those are print(), type(), id()
20

Print (): - This function displays the output on the screen.

Type (): - This function checks the data types of specific variable.

Id (): - This function finds address of variable.

Python- Variable

 Variables are nothing but reserved memory locations to store values. This means that

when you create a variable you reserve some space in memory.

 Based on the data type of a variable, the interpreter allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data
types to variables, you can store integers, decimals, or characters in these variables.
 We use these variable names to make program code read than like English. If we
didn’t use good names for things in our software, we would get last when we based to
read our code again.

Assigning values to Variable

We can assign single value to single variable or multiple variables at a time. And
also, we can assign single value to multiple variables.

Assign single value to single variable:-

The opened to the left of the = operator is the variable and the open and to the right of the =
operator is the value stored in the variable.

E.g.

>>> m = 10 10

>>> print (m) <class int’>

>>> type (m) 1624729872

>>>{d (m) }

>>> n = 20.4

>>> print (n) 20.4


21

>>> type (n) <class float’>

>>> id (n) 48638592

>>> r = ‘Narayana’

>>> print (r) Narayana

>>> type (r) <class ‘str’>

>>> id (r) 54591690

Assigning multiple value to multiple variable: -

>>> x=y=z= 10

>>> print(x)

>>>print(y)

>>>print(z)

Some examples of variables: -

E.g.

My_name= ‘Simran’

My_age = 28 # not a lie

My_height= # 74 inches

My_weight = 75 # kg

My_eyes = ‘Blue’

My_teeth = ‘white’

My_hair= ‘black’

Print(“ Let’s talk about % s.”% my_name)

Print(“she is %d year old. “%my_age )

Print(“she is %d inches tall.”%my_height)

Print(“she is %d kgs heavy.”%my_weight)

Print(“actually that is not too heavy”)


22

Print(“she got %s eyes and %s hair.”%(my_eyes, my_hair))

Print(“her teeth are usually %s depending on the coffee.”% my- teeth)

# This line is tricky , try to get it exactly right.

Print(“hi this is %s , if I add %d ,and %d I get %d.”%(my_name , my_age,


my_height, my_weight , my_age + my_height + my_weight)

Output:-

Let’s talk about Simran.

She is 74 inches tall.

She is 75 kgs heavy.

Actually, that’s not too heavy.

She is got blue eyes and black hair.

Her teeth are usually while depending on the coffee

This is Simran , if I add 28, 74 , and 75 I got 177.

E.g.:2 :--

Cars = 100

Space_in_a_car =4.0

Drivers = 100

Passengers = 90

Car_not_driver = cars_drivers

Car_driver = drivers

Carpool_capicity = cars_driver* space_in_a_car

Average_passengers_per_car = passenger/car_driver

Print(“there are”, cars, “cars available”)

Print(“there are only “, drivers, “drivers available)

Print(“there will be,” cars_not_driver ,” empty cars today”)


23

Print(“we lane tramport,” carpool_capicity, ”people today”)

Print(“we have”, passenger,” to carpool today”)

Print(“ we need to put about”, average_passengers_per_car,”in each car”)

Output :-

There are 100 cars available

There are only 30 drivers available

There will be 70 empty cars today

We can transport 120.0 people today.

We have 90 to carpool to today.

We need to put about 3.0 in each car.

E.g., 3 :-

Print(“mary had a little lamb”)

Print(“it’s fleece was white as %s” ‘snow’)

Print(“and everywhere that mary went”)

Print(“*10”) what’d that do?

End 1= “c”

End 2= “h”

End 3= “e”

End 4= “e”

End 5= “s”

End 6= “e”

End 7= “B”

End 8= “U”

End 9= “R”
24

End 10= “G”

End 11= “E”

End 12= “R”

#Watch that comma at the end try removing it to see what happen.

Print(end1 +end2 + end3 + end4 + end5 + end6,)

Print(end7 + end8 + end9 + end10 + end11 +end12)

Output :-

Mary had a little lamb

Its fleece was white as snow

Any everywhere that mary went

…………..

Cheese

Burger.

E.g., 4 :-

Days = “MonTue Wed Thu Fri SatSun”

Months = “Jan\n Feb\n Mar\n Apr\n May\n Jun\n Jul\n Aug”

Print(“here are the days: ”,days)

Print(“here are the months: “,months)

Output :-

Here are the days: MonThuWed Thu Fri Sat Sun

Here are the months :

Jan

Feb

Mar

Apr
25

May

Jun

Jul

Aug

Escape sequences :-

This is the list of all the escape sequences python supports. You may not use many of these,
but mem once their formats and what they do anyway . also try them out in some string to
see it you can make them work.

Escape what its docs

\\ backslash(\)

\’ single quote(‘)

\” double quote(“)

\aASCII bell(BTL)

\bASCII backspace(BS)

\fASCIIform feed (FF)

\nASCII linefeed (LF)

\N {name} character named name in the Unicode database (Unicode


only)

\rASCII carriage return(CR)

\t ASCII horizontal tab (TAB)

\uxxxx character with 16-bit hex value xxxx (Unicode only)

\Uxxxxxxx character with 32-bit hex value Uxxxxxxx


(Unicode only)

\v ASCIIvertical tab (VT)


26

\ooo character with octal value 00

\xhh character with hex value hh

First Python Program


However, python is one of the easiest languages to learn, and creating “Hello, python
Developer!” program is as simple as writing print (“Hello, python developer!”). So, we are
going to write a different program.

Program add two numbers.

>>> # Add two numbers

>>> x=10

>>> y= 20

>>> sum = x+y

>>> print(sum)

How this program executes?

Line 1: # Add two numbers.

Any line starting with # in python programming is a comment.

Line 2:x= 10

Here, x is a variable you can store a value in a variable. Here, 10 is stored in this variable.

Line 3:y=20

Similarly, 20 stored in y variable.

Line 4:sum = x+y

The variable x and y are added using + operator the result of addition is then stored in
another variable sum.
27

Line 5:print(sum)

The print () function prints the o/p to the screen. In our case, it prints 30 on the screen.

Reading Data from keyboard

1. Input to the program can come in various ways, for example, from a database , from
another computer from mouse clicks and movements from the internet.
2. Generally, in most cases the input comes from the keyboard. For this purpose ,
python provides the function input().
3. The input of the user will be returned as a string without any changes.
4. If this input has to be transformed into data type needed by the algorithm, we can u
either casting (typecasting) functions (or) eval().

E.g.

Direct input from user(default datatype is string): -

>>>n= input(‘Enter number:’) Enter number : 10

>>> print(n) 10

>>> type(n) <class ‘str’>

Converting type data by using casting function: -

>>>n= int(input(‘Enter number:’)) Enter number : 10

>>> print(n) 10

>>> type(n) <class ‘int’>

Converting type of data by using eval function: -

>>>n= (input(‘Enter number:’) Enter number : 10

>>> print(n) 10

>>> type(n) <class ‘int’>

E.g. Interactive mode: -

>>> name = input (‘what is your name:’)


28

What is your name : Narayana

>>> loc. = input (‘what is your location:’)

what is your location: Guntur

>>> print(“““Hello ””” + Name +, How are you How your + loc.””)

Hello, Narayana,how are you How is your Guntur.

E.g. Script Mode: -

Open file and write the following code & save the file.

name = input (‘‘what is your name:’’)

loc. = input (‘‘what is your location:’’)

print(‘Hello’ + Name ,+ How are you How your + loc.’)

If we run file, we can see the following in the python screen: -

what is your name: Narayana

what is your location: Guntur

Hello, Narayana,how are you How is your Guntur.

Different b/w python 2 and python 3: -

→In python 2 has two various of input functions, input () and raw_input () function treats
thereceive data as string if it is included in quotes, “or” otherwise the data is treated as
number.

→In python 3 raw_input() function is deprecated. Further, the receive data is always treated
as string.

In python 2: -

>>> x= input (“Enter any values”)

‘Enter any value= 10’

>>> x # entered data is treated as string

‘10’

>>> z= input (“Enter any value:”)


29

‘Enter any value= 100’

>>> x # entered data is treated as number

‘100’

>>> z= raw_input (“Enter any value:”)

‘Enter any value= 10’

>>> x # entered data is treated as string even without

‘10’

>>> x= raw_input (“Enter any value:”)

‘Enter any value= 10’

>>> x # entered data is treated as string including

‘10’ ““ 10””

In python 3: -

>>> x= input (“Enter any values”)

‘Enter any value= 10’

>>> x

‘10’

>>> x = input (“Enter any value:”)

‘Enter any value= 10’ # entered data is treated as string with or without

>>> x

“ “10” ”

>>> x= raw_input (“Enter any value:”) # will result name error

Trackback (most recent call last):

File “” , line 1, in

x= raw_input (“Enter any value:”)


30

Name error: name ‘raw_input’ is not defined.

Input and Output Statement


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 that string type to our required type by using the
corresponding

type casting method.

E.g. : -

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.

E.g.: -

x = input(‘‘Enter value’’)

10 ===> int

“Durga” ===> str.

10.5 ===> float


31

true ===> bool.

Note: -But, in python 3 we have only input() method and raw_input() a method is not
available python 3 input() function behaviour exactly same as raw_input method of python 2
i.e., every input() function of python 2 is renamed as input() in python 3.

E.g.

1. >>> type (input(“Enter value”))


2. Enter value : 10
3. <class ‘str’>
4.
5. Enter value : 10.5
6. <class ‘str’>
7.
8. Enter value : True
9. <class ‘str’>

Q. Write a program to read 2 numbers from the keyboard & print sum.

1. x= int(x)input(“Enter first number:”)


2. y= int(y) input(“Enter first number:”))
3. i = int(x)
4. j = int(y)
5. print(“The sum:”,i+j)

Output: -

Enter first number: 100

Enter second number: 200

The sum: 300

………..…….…………………………………..

1. x =int(input(“Enter first number:”))


2. y= int(input(“Enter second number:”)))
3. print(“The sum:”,x+y)

……………………………………………….
32

Print(“The sum:”,int(input(“Enter first number:”)) + int(input(“Enter second


number:”))

Q. Write a program to read employee data from the keyboard and print that data.

1. Eno =int(input(“Enter employee no.:”))


2. Ename =int(input(“Enter employee name:”))
3. Esal =int(input(“Enter employee salary:”))
4. Eaddress =int(input(“Enter employee address:”))
5. Married= both(input(“Employee married?”)) [True/False]
6. Print(“please confirm information”)
7. Print(“Employee no.:”, eno)
8. Print(“Employee name:”, ename)
9. Print(“Employee salary:”, esal)
10. Print(“Employee address:”, eaddr)
11. Print(“Employee married?” married)
12.
13. D:\python_classes>py test.py
14. Employee No: 100
15. Employee Name: Sunny
16. Employee Salary: 1000
17. Employee Address: Mumbai
18. Employee Married? [True/False]: True
19. please confirm information
20. Employee No: 100
21. Employee Name: Sunny
22. Employee Salary: 1000
23. Employee Address: Mumbai
24. Employee Married? : True

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

1. a, b =[int(x) for x in input(“Enter two numbers”)split()]


2. print(“product is: ”, a*b)
3. f
4. D:\ python_classes>Py test.py
33

5. Enter two number: 10 20


6. Product is: 200

Note: -

split() function can take space as separator by default. But we can pass anything as

separator.

Q. Write a program to read 3 float number from the keyboard with, separator and

Print their sum.

1. a, b, c = [float() for x in input(“Enter three float numbers:”).split(‘,’)]


2. print(“The sum is: a+b+c”)
3. d
4. D:\python_classes> py type.py
5. Enter three float number: 10.5, 20.6, 20.1
6. The sum:51.

eval(): -eval function take a string and evaluate the result.

E.g.: -

x= eval(“10=20=30”)

Print

O/p: -60

E.g.: -

x= eval(input(“Enter expression”))

Enter Expression: 10+2*3/4

O/p: -11.5

eval() can evaluate the input to list, tuple, set based the provided input.

E.g.

1. l= eval(input(“Enter list”))

2. print(type(U))
34

3. print(l)

Command Line Arguments


 rage is not array. It is a list. It is available sys module.
 The argument which are passing at the time of execution are called

command line argument.

E.g.: -

D:\python_classes pytest.py 10 20 30

Command Line Argument

Within the python program this command line argument are available

in argv. which is present in sys module

test.py 10 20 30

Note: -argv[0] represents name of program. But not first command

line argument.

Argv[1] represent first command line argument.

Program: - To check type of argv from sys.

Import argv

Print(type(argv))

D:\python_classes\ py_test.py

Write a program to display command line argument.

1. from sys impot argv


2. print(“The number of command line arguments:”,len(argv))
3. print(“The list of command line arguments:”,argv)
4. print(“command line arguments one by one)
5. for x in argv
6. Print(x)
35

7.
8. D:\python_classes> py test.py 10 20 30
9. The number of command line arguments: 4
10. The list of command line arguments: [test.py, ‘10’, ‘20’, ‘30’]
11. command line arguments one by one:
12. test.py
13. 10
14. 20
15. 30

1. from sys import argv


2. sum=0
3. args= argv[16]
4. for x in args
5. n= int(x)
6. sum= sum+n
7. print(“The sum:”,sum)
8.
9. D:\python_classes> py test.py 10 20 30 40
10. The sum 100

Note1: -Usually, space is separator between command line arguments.If our command line
argument itself contains space that should within double quotes(but not single quotes)

E.g.: -

1. From sys import argv


2. Print(argv[1])
3. E
4. D:\ python_classes>py test.py
5. Python
6. D:\ python_classes> py test.py ‘python Narayana’
7.
8. Python
9.
36

10. D:\ python_classes> py test.py ‘‘python Narayana’’


11. Python Narayana

Note 2: -Within the python program command line argument are availablein the string form.
Based on our requirement, we can convertinto correspondingtype by using type casting
methods.

E.g.: -

1. from sys import argv


2. print(argv[1]+argv[2])
3. print(int(argv[1]+argv[2]))
4. f
5. D:\ python_classes> py test.py 10 20

6. 10 20
7. 30

Note 3: -If we are buying to access command line arguments with out-of-range index

then we will get error.

E.g.:-

1. from sys import argv


2. Print(argv[1])
3.
4. D:\ python_classes> py test.py 10 20
5. Index error: list index out of range

Note 4: -In python there are argument module to phase command line argument &

display some help messages whenever end enter wrong input.

E.g.: -

Input()

Raw_input()

Command line arguments


37

Output Statement
We can use print () function to display output .

Form 1: -print() without any argument just it print new line character.

Form 2: -

1. Print(string)
2. Print(“Hello world”)
3. We can use escape character only
4. Print(“Hello \n world”)
5. Print(“Hello \t world”)
6. We can use repetition operator (*) in the string
7. Print(10*“Hello”)
8. Print(“Hello”*10)
9. We can use + operator also
10. Print(“Hello”+“world”)

Note: -

 If both arguments are string type then + operator acts as concatenation operator.
 If one argument is string type & second is any other type like int then we will get
error.
 If both arguments, number type then + operator acts as arithmeticaddition operator.

E.g.: -

1. Print(“Hello”+“world”)
2. Print(“Hello”,“world”)
3. D
4. Hello world
5. Hello world

Form 3: -print() with variable number of arguments.

E.g.: -

1. a,b,c= 10, 20,30


2. print(“The values are:”,a,b,c)
38

3.
4. output the values are 10 20 30

By default, output values are separators by space. If we want we can specify separator by
using “sep” attributes.

1. a,b,c = 10, 20, 30


2. print(a, b, c, sep =,’)
3. print(a, b, c, sep =:’)
4. d
5. D:\ python_classes> py test.py
6. 10, 20, 30
7. 10:20:30

Form 4: -print() with end attributes.

1. Print(“Hello”)
2. Print(“Python”)
3. Print(“Narayana”)

O/p :-

1. Hello
2. Python
3. Narayana

If we want O/p in the same line with space.

1. Print(“Hello”, end‘’)
2. Print(“Python”)
3. Print(“Narayana”)

O/p: -Hello Python Narayana

Note: -The default values for end attribute is \n, which is nothing but new line character.
39

Form 5: -print(object) statement:

We can pass any object(like, list ,tuple, set etc) as argument to the print () statement.

E.g. : -

1. l = [10, 20, 30, 40]


2. t =(10, 20, 30, 40)
3. print(l)
4. print(t)

Form 6: - print(string, variable list):

We can use print () statement with string and any number of arguments.

E.g.: -

1. s= “Narayana”
2. a= 28
3. s1= “Python”
4. s2= “Django”
5. print(“Hello”, s “your age”, a )
6. print(“you are teaching”, s1 “and” s2)

O/p: -

Hello Narayana, your age is 28

You are teaching python and Django

Form 7: -Print(formatted string):

%c===> int

%d ===> float

%f ===> string type

E.g.: -

1. s= “Narayana”
2. list= [10, 20, 30, 40]
3. print(“Hello %s….the list of items are %s”, %(s,list))
4.
40

O/p: -

Hello Narayana ….the list of items are [10, 20, 30,40]

Form 8:-print() with replacement operator.

1. Name= “Durga”
2. Salary= 10,000
3. Gf= “sunny”
4. Print(“hello{o}salary is{1} and your friend{2}is waiting.”)
5. format(name, salary, gf)

O/p: -

Hello, Durga, your salary is 10,000 and your friend Sunny is waiting.

Data Types in Python


1. Data types are some of the keywords in any programming languages.
2. Data types are used to define what type of data that we are passing to the
specific variable.
3. Generally, variables will not store the values without having data types in other
languages.
4. But in Python language, variables allow values without specifying data types
also, because Python allocates the data types dynamically at run time when
python application is running.
5. In Python language, data types are decided by interpreter based on the value
that is given to variable by user.
6. Programmers should not specify the data type of variable when developing the
program, if we specify explicitly then interpreter will throw error.

Python supports two types of data types,

1. Basic data types or fundamental data types

2. Composite data types or collections data types

1. Basic data types or fundamental data types: -

Python supports different types of basic data types,


41

1. Int

2. FloatData Types

3. Complex

4. Bool

5. strFundamental or basic Data structure

Int, float, complex str, list, tuple,

Bool, str set, dict.

Int data type:-

If we assign integer value to any variable then interpreter decides that variable as int type
variable,

E.g.:

>>> a=10.

>>> print(a) 10

>>> type(a) <class ‘int’>

>>> id(a)1625909520

Float Data type: -

If we assign float value to any variable then interpreter decides that variable as Float Type
variable.

E.g.:

>>> b=10.5

>>> print(b) 10.5

>>> type(b) <class ‘float’>

>>> id(b)47460096

String Data Type: -

If we assign string value to any variable then interpreter decides that variable as String type
variable.
42

E.g.:

>>> c='Narayana'

>>> print(c) Narayana

>>> type(c) <class ‘str’>

>>> id(c)52367056

Bool Data type: -

If we assign either True or False to any variable then interpreter decides that variable as Bool
type variable.

E.g.:

>>> d=True

>>> print(d) True

>>> type(d) <class ‘bool’>

>>> id(d)1625727600

Complex Data type: -

If we assign complex number to any variable then interpreter makes that variable as
Complex type variable.

E.g.:

>>> e=3+4j

>>> print(e) (3+4j)

>>> type(e) <class ‘complex’>

>>> id(e)47539552

Type Conversion Functions

We can convert datatype in two different ways:

1. type casting functions

2. eval function
43

1.Type casting functions: -

These type conversion functions are used to convert string type data into required types

1.int(): -This int() function is used to convert into int data type.

E.g.:Get two integers from the user and perform addition on those user values.

Way-1: -

>>> a=input("Enter First Number:") Enter First Number: 10

>>> b=input("Enter Second Number:") Enter Second Number: 20

>>> print (a) 10

>>> print (b) 20

>>> type(a) <class ‘str’>

>>> type(b) <class ‘str’>

>>> id(a) 52351712

>>> id(b)6925376

>>> c=a+b #adding two str variables

>>> print(c) 1020

>>> type(c) <class ‘str’>

>>> id(c)52351136

>>> x=int(a) #converting str ‘a’ into int ‘x’

>>> y=int(b) #converting str ‘b’ into int ‘y’

>>> print(x) 10

>>> print(y) 20

>>> type(x)<class ‘int’>

>>> type(y) <class ‘int’>

>>> id(x) 1625909520


44

>>> id(y)1625909680

>>> z=x+y #adding two int variables

>>> print(z) 30

>>> type(z) <class ‘int’>

>>> id(z)1625909840

Way-2: (shorter way): -

>>> a=int(input("Enter First Number: ")) Enter First Number: 10

>>> b=int(input("Enter Second Number: ")) Enter Second Number: 20

>>> print(a) 10

>>> print(b) 20

>>> type(a) <class ‘int’>

>>> type(b)<class ‘int’>

Way-3:(shortest way): -

>>> print("The sum is " + str(int(input("Enter First Number: ")) + int(input("Enter Second
Number: "))))

>>> Enter First Number: 10

>>> Enter Second Number: 20

>>> The sum is 30

2.Float(): -

This float() conversion function is used to convert other types into float type.

Way-1:

>>> a=input("Enter First Number: ") Enter First Number: 10.5


45

>>> b=input("Enter Second Number") Enter Second Number20.5

>>> print (a) 10.5

>>> print(b) 20.5

>>> type(a) <class ‘float’>

>>> type(b) <class ‘float’>

>>> id(a) 52354240

>>> id(b)52354144

>>> c=a+b

>>> print(c) 10.520.5

>>> type(c)<class ‘str’>

>>> id(c)52367096

>>> x=float(a)

>>> y=float(b)

>>> print(x) 10.5

>>> print(y) 20.5

>>> type(x) <class ‘float’>

>>> type(y) <class ‘float’>

>>> id(x) 47459712

>>> id(y)47459712

>>> z=x+y

>>> print(z) 31.0

>>> type(z) <class ‘float’>


46

>>> id(z)46410368

Way-2:(shorter way): -

>>> a=float(input("Enter First Number:")) Enter First Number: 10.5

>>> b=float(input("Enter Second Number")) Enter Second Number2.3

>>> print(a) 10.5

>>> print(b) 2.3

>>> type(a) <class ‘float’>

>>> type(b)<class ‘float’>

>>> c=a+b

>>> print(c) 12.8

>>> type(c)<class ‘float’>

Way-3:(shortest way): -

>>>print(float(input("Enter First Number:")))+print(float(input("Enter Second Number:")))

>>>Enter First Number: 10.5

>>>Enter Second Number: 2.3

>>> 31.0

3.Complex(): -

This complex() conversion function is used to convert string type data into Complex type.
Way-1:

>>> a=input("Enter Number: ") Enter Number: 2+3j

>>> print(a) 2+3j

>>> type(a) <class ‘complex’>

>>> id(a) 52351712

>>> x=complex(a)
47

>>> print(x) (2+3j)

>>> type(x) <class ‘complex’>

>>> id(x)47539768

Way-2: -

>>> print(complex(input("Enter Number: ")))

>>> Enter Number: 4+6j

>>> (4+6j) 4.
4.Bool(): -

This bool() conversion function is used to convert string type data into Boolean type.

Way-1: -

>>> a=input("Enter either True or False:") Enter either True or False: True: - True

>>> print(a) True

>>> type(a) <class ‘str’>

>>> id(a)52354272

>>> x=bool(a)

>>> print(x) True

>>> type(x) <class ‘bool’>

>>> id(x)1625727600

Way-2: -

>>> print(bool(input("Enter Either True or False: ")))

>>>Enter Either True or False: True

>>> True
48

Eval Function
This function is also used to convert the data into required type. But generally, this function
converts the type of the variable based on the value.

Converting int value:

>>> a=eval(input('enter value for a: '))

enter value for a: 10

>>> print(a) 10

>>> type(a)<class ‘int’>

Converting float value: -

>>> b=eval(input('enter value for b: '))

enter value for b: 10.6

>>> print(b) 10.6

>>> type(b)

Converting string value: -

>>> c=eval(input("enter value for c: "))

enter value for c: 'Narayana'

>>> print(c) Narayana

>>> type(c)<class ‘str’>

Converting complex value: -

>>> d=eval(input('enter value for d: '))

enter value for d: 2+5j

>>> print(d)(2+5j)
49

>>> type(d)<class ‘complex’>

Converting bool value: -

>>> e=eval(input('enter value for e:'))

enter value for e:True


>>> print(e)True

>>> type(e)<class ‘bool’>

Assignment-1
1. Who is the father of Python?

Ans:

2. What is the language used to develop Distributed Operating System?

Ans:

3. Why did Guido Van Rossum keep the name ‘PYTHON’ to his language?

Ans:

4. When was the Python developed?

Ans:

5. When did Python available to public?

Ans:

6.What is a Python?

Ans:

7. What are the main features of Python?

Ans:
50

8. What are the differences between programming and scripting languages?

Ans:

9. Is Python programming language or scripting language? Why?

Ans:

10. What are the different types of languages used to develop the Python language? Ans:

11. Is Python portable language or not? If yes then why?

Ans:

12. If we use Python language to develop a project, will it take less time or more time to
develop the project compared to other compiler languages? If no then why?

Ans:

13. Is Python free source or needs to purchase?

Ans:

14. What are the different top companies using Python?

Ans:

15. Why Python is also called CROSS Plat Form language?

Ans:

16. What are the different types of OSs where we can run python?

Ans:

17. Why Python is also called interpretable language?


51

Ans:

18. Why debugging of Python program is very easy for developer?

Ans:

19. Give me any four reasons to learn/work on Python?

Ans:

20. Do developers need to focus more on Python Syntax? If no then Why?

Ans:

21. Do we need to think about memory management while application is developing?


Ans:

22. When memory will be allocated to variables in python language?

Ans:

23. What are the different types of modes to develop python application?

Ans:

24. What are the differences between interactive mode and script mode?

Ans:

25. What is the name of >>> symbol in python?

Ans:

26. What is indentation in python?

Ans:

27. What is a variable and what is the purpose of variable in python?


52

Ans:

28. Who will decide the type of variable in Python language? Developer or interpreter?
Ans:

29. What are the different types of quotes supported in python?

Ans:

30. What is the purpose of comments in any programming language?

Ans:

31. Can we write our programming code after comment in the same physical line? If no,
why? Ans:

32. Can we write comment after our programming code in same physical line?

Ans:

33. How to write comment in multiple lines?

Ans:

34. What is identifier in python? Can a single identifier contain combination of upper
case, lower case, underscore, and number?

Ans:

35. Is python case-sensitive language or not? If yes, give one example?

Ans:

36. Interpreter decides the type of variable in python then how can a programmer know
the type of variable?

Ans:
53

37. How to see the value in the variable? And also, the address of variable in python?
Ans:

38. How to assign multiple heterogeneous values to multiple variables? Give one
example?

Ans:

39. How to assign single value to multiple variables?

Ans:

40. How to give input to the program from keyboard?

Ans:

41. What is the default data type of input()’s value?

Ans:

42. Can we convert string type data to our required data type? Different ways?

Ans:

43. What are the different types of type conversion functions?

Ans:

44. What is eval()?

Ans:

45. What is the difference between type conversion functions and eval()?

Ans:

46. How to read values from user? Give one example?


54

Ans:

47. What is the purpose of data type in any language?

Ans:

48. Can variable allow the value without specifying its type in python language?

Ans:

49. Can a programmer specify type of variable explicitly while developing application?
Ans:

50. On what basis, interpreter decides the type of variable in python language?

Ans:

Composite Datatype Collection or Data Structures


Python supports different type of data structure.
1. String
2. List
3. Tuple
4. Set
5. Dictionary

String Data Structure

1. A sequence of characters is called String.


2. Python supports str data type to represent string type data.
3. String objects are immutable objects that mean we can’t modify the existing string
object.
4. Insertion order is preserved in string objects.
5. A string allows multiple duplicate characters also.
6. Every character in the string object is represented with unique index.
7. Python supports both forward and backward indexes.
8. Forward index starts with 0 and negative index starts with -1.
55

9. Python string supports both concatenation and multiplication of string objects.


10. Strings can be created by enclosing characters inside a single quote or double quotes.
Even triple quotes can be used in Python but generally used to represent multiline
strings and docstrings.

E.g.:creating a string with single quote

>>> name='Narayana'

>>> print(name)

E.g.:creating a string with double quotes

>>> name="Narayana"

>>> print(name) Narayana

E.g.:creating a string with triple quotes

>>> name='''Narayana'''

>>> print(name) Narayana

(or)

>>> name="""Narayana"""

>>> print(name)Narayana

Using triple quotes for multiple line comments: -

name="""Hello, Welcome to

world of PYTHON

Working with PYTHON is very fun."""

print(name)

Hello, Welcome to

world of PYTHON

Working With PYTHON is very fun.

1.We can access individual characters using indexing and a range of characters using slicing.
56

2. Index starts from 0. If we try to access a character out of index range then interpreter will
raise an IndexError.

3. The index must be an integer. If we try to access the data with non-integer indexes values
then interpreter raises ‘Type Error’.

4. We can also give bool value as index values between interpreter treats True as 1 and
False as 0.

String Indexing : -It is nothing but fetching a specific character byusing its index number.

E.g.

01 2 3 4 5 6 7

N AR A Y A NA

-8 -7 -6 -5 -4 -3 -2 -1

E.g.:
>>> x='narayana'

>>> print(x) narayana

>>> type(x) <class ‘str’>

>>> id(x) 52418104

Forward index: -

>>> print (x[0]) n

>>> print (x[1]) a

>>> print (x[2]) r

>>> print (x[3]) a

>>> print (x[4]) y

>>> print (x[5]) a

>>> print (x[6]) n

>>> print (x[7]) a


57

Python allows negative indexing for its sequences. The index of -1 refers to the last item,

-2 to the second last item and so on.

Backward index: -

>>> print (x[-1]) a

>>> print (x[-2]) n

>>> print (x[-3]) a

>>> print (x[-4]) y

>>> print (x[-5]) a

>>> print (x[-6]) r

>>> print (x[-7])a

>>> print (x[-8]) n

If we modify the content of the existing object then the indexes also will be changed

E.g.:

>>> x=" narayana"

>>> print(x)

>>> type(x) <class ‘str’>

>>> id(x) 52419584

>>> print(x[0]) n#space is there here, because

>>> print(x[1]) a x contains space as

>>> print(x[2]) r first character.


58

>>> print(x[3]) a

>>> print(x[4]) y

>>> print(x[5]) a

>>> print(x[6]) n

>>> print(x[7]) a

>>> print(x[8])

>>> print(x[-1]) a

>>> print(x[-2]) n

>>> print(x[-3]) a

>>> print(x[-4]) y

>>> print(x[-5]) a

>>> print(x[-6]) r

>>> print(x[-7]) a

>>> print(x[-8]) n

>>> print(x[-9])#space is there here, because

x contains space asfirst

character

String slicing: -We can access a range of characters using slicing. The slicing operator is
colon (:)

E.g.:-

0 1 2 3 4 5 6 7

N A R A YA N A
59

-8 -7 -6 -5 -4 -3 -2 -1

>>> a='NARAYANA'

>>> print(a[0:1]) N

>>> print(a[0:2]) NA

>>> print(a[0:3]) NAR

>>> print(a[0:4]) NARA

>>> print(a[0:5]) NARAY

>>> print(a[0:6]) NARAYA

>>> print(a[0:7]) NARAYAN

>>> print(a[0:8]) NARAYANA

>>> print(a[2:8]) RANAYA

>>> print(a[2:4]) RA

>>> print(a[7:8])A
>>> print(a[-8:-6]) NA

>>> print(a[-8:-4]) NARA

>>> print(a[-8:-3]) NARAY

>>> print(a[-5:-4])A

String Concatenation: -

1. We can concatenate two or more strings into a single string is called concatenation.

2. The + operator is used in Python for concatenation.

E.g.: -

>>> string1='Python'

>>> string2='Developer'
60

>>> print('String1 + string2 :', string1+' '+string2)

String1 + string2 : Python Developer

String Multiplication: -

1. Python supports multiplying or repeating the given string into n number of times.

2. The * operator can be used to repeat the string for a given number of times.

E.g.: -

>>> string1='Python'

>>> print(string1 * 3)PythonPythonPython

String is immutable object because we cannot replace or alter the existing string object.

E.g.: -

>>> st='Python'
>>> print(st)python

>>> id(st) 42221792


>>> st=st+'s' # altering the string object
>>> print(st) Pythons

>>> id(st) 41200640


Id is changed to before modification and after modification of the string st. that’s why
string is an immutable object.

Here when we try to edit the existing string object(st in 42221792), then the new object (st
in 41200640) is created.

String packing: -Its nothing but packing all values of defined variables as a single string.

E.g.: -

>>> a='x'

>>> b='y'

>>> c='z'
61

>>> st=''.join([a,b,c])

>>> print(st) xyz

>>> type(st)<class ‘str’>

String unpacking: -

1. String unpacking allows extracting all characters of string into different variables
automatically.

2. The number of variables must be equal to number of characters in the string.

E.g.: -

>>> str1="Python"

>>> print(str1) Python

>>> type(str1)<class ‘str’>

>>> id(str1)23941472

>>> a,b,c,d,e,f=str1#string unpacking

>>> print(a)P

>>> type(a) <class ‘str’>

>>> print(b) y

>>> type(b)<class‘str’>

>>> print(c) t

>>> type(c)<class ‘str’>

>>> print(d) h
62

>>> type(d)<class ‘str’>

>>> print(e) o

>>> type(e)<class ‘str’>

>>> print(f)n

>>> type(f)<class ‘str’>

String Functions: -

1. Capitalize(): -This function converts first letter of first word in the given string into upper
case.

E.g.: -

>>> str1='python developer'

>>>str1.capitalize()'Python developer'

2. Title(): -This function converts first character of each word in the given string into upper
case.

E.g.: -

>>> str1='python developer'

>>> str1.title()'Python Developer'

3. Islower(): -This function checks whether the given string contains all lower-case letters or
not. If all are lower casethen it will return True else False.

E.g.: -

>>> str1='python developer'

>>> str1.islower()True
>>> str2="Python"

>>> str2.islower()False

4. isupper(): -This function checks whether the given string contains all upper-case letters or
not. If all are upper case then it will return True else False.
63

E.g.: -

>>> str1='python developer'

>>> str1.isupper() False

>>> str3='PYTHON'

>>> str3.isupper()True

5. lower(): -This function converts all lettersof given string into lower case.

E.g.: -

>>> str3='PYTHON'

>>> str3.lower() ‘python’

6. upper(): -This function converts all letters of given string into upper case.

E.g.: -

>>> str1='python developer'

>>> str1.upper()'PYTHON DEVELOPER'

7. len(): -This function counts the number of characters in the given string.

E.g.: -

>>> str1='python developer'

>>> len(str1)16

8. count() : -This function counts no.of occurrences of a specific character in the given
string.

E.g.: -

>>> str1='python developer'

>>> str1.count('o')2

9. find(): -This function finds the index position of specific character in the given string.
E.g.: -

>>> str1='python developer'

>>> str1.find('o') 4…. For first occurrence


64

>>> str1.find('o',5)12…. For second occurrence

10. split(): -This function splits the given strings into multiple strings.

Eg1: -

>>> str1='python developer'

>>> str1.split()['python', 'developer']

Note:The default delimiter is space.

>>> str2='python developer in TCS'

>>> str2.split()['python', 'developer', 'in', 'TCS']

>>> str3='python.developer.in.TCS'

>>> str3.split('.')['python', 'developer', 'in', 'TCS']

>>> str4='developer'

>>> str4.split('l')['deve', 'oper']

11. lstrip(): -This function removes specific special character to left side of given string.

E.g.: -

str1='!!!!!!Python Developer!!!!!!!'

>>> str1.lstrip('!')'Python Developer!!!!!!!'

12. rstrip(): -This function removes specific special character to the right side of given
string.

E.g.: -

str1='!!!!!!Python Developer!!!!!!!'

>>> str1.rstrip('!')'!!!!!!Python Developer'


13.strip(): -This function removes specific special character from both sides to the given
string.

E.g.: -

str1='!!!!!!Python Developer!!!!!!!'
65

>>> str1.strip('!')'Python Developer'


14.swapcase(): -This function swaps all lower-case letters into upper case and vice versa.
E.g.:-

>>> str1='PyThOn'

>>> str1.swapcase()'pYtHoN'

15.reversed(): -This function reverses the string.

E.g.: -

>>> str='Python'

>>> print(str)Python
>>> str=''.join(reversed(str))

>>> print(str)nohtyP

Two single quotes

15. replace(): -This function replaces an existing character(s) with new character(s).

E.g.: -

>>> str1='python learner'

>>> print(str1)python learner

>>> str2=str1.replace('learner','developer')

>>> print(str2) python developer

Note:- We can remove any character(s) with non-empty space.

>>> str1='Python'

>>> print(str1) Python

>>> type(str1)<class ‘str’>

>>> str2=str1.replace('thon','')

>>> print(str2) Py

>>> type(str2)<class ‘str’>


66

del command:-

We can’t delete a specific character or range of characters by using del command.

We can delete the entire string objects permanently by using del command.

E.g.,1: -

>>> str1="Python Narayana"#trying to remove specific character

>>> del str1[0] TypeError: 'str' object doesn't support item deletion

E.g.,2: -

>>> str1="Python Narayana" #trying to remove specific range of characters >>> del str[1:5]
TypeError: 'str' object does not support item deletion

E.g.,3: -

>>> str1="Python Narayana"

>>> print(str1) Python Narayana

>>> type(str1)<class‘str’>
>>> id(str1) 63806464

>>> del str1#deleting entire string str1 object


>>> print(str1)#after deleting

NameError:name 'str1' is not defined

Q.How to display the given string in ascending order?

>>> st="python"

>>> ''.join(sorted(st))'hnopty'
>>> st1="PyThON deVELoPer"#if string contains both upper and lower cases
>>> ''.join(sorted(st1))'ELNOPPTVdeehory'

Q. How to display the given string in descending order?

>>>st = ‘python’

>>>“.join (reserved(sorted((st)))) ‘ytonh’

Q.How to display the given string with two dots between each character?
67

>>> s1='python'

>>> s10='..'.join(s1)

>>> s10'p..y..t..h..o..n'

Q. How to display the given string with space b/w eachcharacter?

>>> st= 'Narayana'

>>> st= ' '.join(st)

>>> print(st)

Q. How to reverse a given string?

>>> st =‘hyderbad’

>>> st3 =‘.’ Join(reversed(st))

>>> st3 ‘dabredyh’

Q. How to get ‘durga’ from st= ‘Durgasoft’?

Way1: -

>>> st = ‘durga_soft’

>>> streplace ‘soft’, ‘’

‘durga’

Way2: -

>>> st = ‘durgasoft’

>>> a= st.split(‘s’)[0]

>>> print(a)

[‘durga’]

Way3: -

>>> st = ‘durga soft’

>>> st [o:5]

‘durga’
68

Using:: :-

>>> st= ‘python Narayana’

>>> st[::] ‘python narayana’

>>> st[0::] ‘python narayana’

>>> st[1::] ‘ython narayana’

>>> st[2::] ‘thon narayana’

>>> st[12::] ‘ana’

>>> st[13::] ‘na’

>>> st[15::] ‘’

>>> st[0::5] ‘pna’

>>> st[0::6] ‘pa’

>>> st[0::10] ‘pa’

>>> st[0::11] ‘py’

>>> st[0::16] ‘p’

>>> st[16::0] value error: slice step cannot be zero

>>> st[1::5] ‘yy’

>>> st[1::10] ‘yy’

>>> st[1::15] ‘y’

>>> st[2::1] ‘than narayana’

>>> st[2::7] ‘tr’

>>> st[2::8] ‘ta’

>>> st[3::1] ‘hon narayana’

>>> st[3::5] ‘han’

>>> st[3::6] ‘hr’

>>> st[3::10] ‘hn’


69

>>> st[4::1] ‘on narayana’

>>> st[4::3] ‘onan’

>>> st[4::4] ‘ooa’

>>> st[4::9] ‘on’

>>> st[5::3] ‘naya’

>>> st[5::5] ‘na’

>>> st[5::10] ‘n’

>>> st[6::5] ‘y’

>>> st[6::9] ‘’

>>> st[7::3] ‘nan’

>>> st[7::7] ‘na’

>>> st[8::1] ‘y’

>>> st[0:: -1] ‘p’

>>> st[1:: -1] ‘yp’

>>> st[4:: -1] ‘ohtyp’

>>> st[5:: -1] ‘nohtp’

>>> st[15:: -1] ‘anayaran nothyp’

>>> st[6:: -2] ‘otp’

>>> st[7::2]‘nnhy’

>>> st[9:: -2] ‘rnnhy’

>>> st[13:: -2] ‘nyrnnhy’

>>> st[-1:: 1] ‘-a’

>>> st[-2:: 2] ‘-n’

>>> st[-3:: 3] ‘-a’

>>> st[-4:: 1] ‘-yana’


70

>>> st[-4:: 5] ‘-y’

String Compressor: -

E.g.,1: -

Str1 = ‘b’

Str2 = ‘a’

if st1> st2:

print(st1,‘bigger than’, st2)

else if st2> st1:

print(st2,‘bigger than’, st1)

else :

print(‘both’,st1,‘and’,st2,‘are equal’)

Output: -

b is bigger than a.

Note: -In the above, we have set st1= ‘b’ and st2= ‘a’ when we see the alphabet ascending
order then

Hear, ‘b’ is bigger than ‘a’

E.g.,2: -

St1 = ‘a’

St2 = ‘b’

if st1> st2:

print(st1, is ‘bigger than’, st2)

else if st2> st1:

print(st2, is ‘bigger than’, st1)

else :
71

print(‘both’,st1,‘and’, st2,‘are equal’)

Output: -

b is bigger than a.

E.g.: -

st1= ‘python’

st2= ‘narayana’

if st1> st2:

print(st1, is ‘bigger than’, st2)

else if st2> st1:

print(st2, is ‘bigger than’, st1)

else :

print(‘both’,st1,‘and’, st2,‘are equal’)

Output: -

Python is bigger than narayana.

Note: -

‘p’ in the st1 is bigger than ‘n’ in the st2 string. So, st1 variable value is bigger than st2
variable value.

st1= ‘123’

st2= ‘a123’

if st1> st2:

print(st1, is ‘bigger than’, st2)

else if st2> st1:

print(st2, is ‘bigger than’, st1)

else :
72

print(‘both’,st1,‘and’, st2,‘are equal’)

Output: -

St1 is bigger than st2.

LIST Data structure

1. A list is a collection of elements. These elements may be homogeneous or heterogeneous.

2. A list also allows duplicate elements.

3. Insertionorder is preserved in list.

4. List elements are separated by commas and enclosed within square brackets ([]).

5. Every element in the list has its own unique index number.

6. List supports both forward indexingand backward indexing, forward index starts from 0
and backward index starts from -1.

7. We access either specific element by using indexing or set of elements by using slicing
from the List.

8. We can create list in different ways. Like by using list() function, by using squarebrackets
“[]” and also by using range() function.

9. List objects are mutable.

Creating List by using List()

1. This list() allows only one string value with set of characters.

2. If we give int type data in the list() function then interpreter will throw ‘TypeError’ error.

E.g.,1: -

>>>lst=list([1, 2, a])

>>> print(List)[1, 2, a]

>>> type(List)<class‘list’>
73

E.g.,2:-

>>>list1=list()#creating empty list []

>>> print(List1) [ ]

>>> type(List1)<class‘list’>

E.g.,3: -

>>> List1=list('python') #creating list with set of characters

>>> print(List1) ['p', 'y', 't', 'h', 'o', 'n']

>>> type(List1)<class‘str’>

Creating list by using square brackets “[ ]” :

E.g.,1: -

>>>list1=[ ] #creating empty list []

>>> print(list1) [ ]

>>> type(list1) <class‘list’>

E.g.,2: -
>>>list1=[1,2,3,4,5]#creating list with homogeneous elements

>>> print(list1)[1, 2, 3, 4, 5]

>>> type(list1)<class‘list’>

E.g.,3: -
>>>list1=[10,11,'Python',5.5,True,2+3j]#creating list with heterogeneous elements

>>> print(list1) [10, 11, 'Python', 5.5, True, (2+3j)]

>>> type(list1) <class‘list’>

Creating list by using range() function:

We can also use range function to create list. Syn: range(StartingIndexValue, LastValue-
1,RangeValue) Here, both Starting IndexValue and RangeValue are optional.

The default StartingIndexValue is 0.


74

The default RangeValue is 1.

E.g.,1: -

In python 2 version

>>>list1=list(range(10))

>>> print(list1) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> type(list1)<class‘list’>

E.g.,2: -

>>>list1=list(range(0,10))

>>> print(list1) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> type(list1)<class‘list’>

E.g.,3: -

>>>list1=list(range(2,8))

>>> print(list1) [2, 3, 4, 5, 6, 7]

>>> type(list1)<class‘list’>

E.g.,4: -

>>>list1=list(range(-4,4))

>>> print(list1) [-4, -3, -2, -1, 0, 1,2, 3, 4]

>>> type(list1)<class‘list’>

E.g.,5: -

>>> List1=list(range(0,10,2))

>>> print(list1) [0,2,4,6,8]

>>> type(list1) <class‘list’>

Creating a list with split() function:

>>> str1 =‘python is very easy and simple language’.

>>> lst = str1. Spilt


75

>>> print(lst) [ ‘python’,‘is’,‘very’,‘easy’,‘and’,‘simple’, ‘language’]

>>> type(list)<class‘str’>

Creating an empty list : -

By using []: -

>>> lst = [ ]

>>> print(lst) []

>>> type<class ‘str’>

By using list(): -

>>> lst1 = list()

>>>print(lst1) []

>>> type(lst1)<class‘lst’>

By using range(): -

>>> lst1 = range(0)

>>> lst1 []

>>> type(lst1) <class‘str’>

List Indexing: -

1. By using list indexing we can fetch specific element from the list, by using its index
number.

2. It supports both forward and backward indexing.

E.g.: -

>>> list1 = [ 10,20,30, ‘python’, True, 1.5+2+3j]

0 1 2 3 4 5 6

10 20 30 python True 1.5 2+3

-7 -6 -5 -4 -3 -2 -1
76

E.g.:-

print (list1[0]) 10

print (list1[1]) 20

print (list1[2]) 30

print (list1[3]) python

print (list1[4]) True

print (list1[5]) 1.5

print (list1[6]) (2+3j)

print (list1[-1]) (2+3j)

print (list1[-2]) 1.5

print (list1[-3]) True

print (list1[-4]) python

print (list1[-5]) 30

print (list1[-6]) 20

print (list1[-7]) 10

python 2 python 3

Q.1>>>lst =range(6)>>> lst = range(6)

>>> lst[ 0,1,2,3,4,5] >>> range (0,6)

Q.2 >>> lst=range(2,6) >>> lst = range(2,6)

>>> lst(2,3,4,5)>>> lst

Q.3 >>> lst = range(5,15,2)>>> range(2,6)

>>> lst [5,7,9,11,13] >>> lst = range(5,15,2)

Q. >>> lst = range(3,6)>>> lst

>>> lst [3,4,5]>>> range (5,15,2)


77

………………………………………………………………………………………………….

List Slicing: -

1. By using slicing we can fetch set of elements.

2. It also supports both forward and backward indexing.

3. colon(:) is the slicing operation.

E.g.: -

>>> lst1 = [10,20,30, ‘python’,‘True’, 1.5,2+3j]

0 1 2 3 4 5 6

10 20 30 python True 1.5 2+3

-7 -6 -5 -4 -3 -2 -1

>>> print(list1[062]) [10,20]

>>> print(list1[ 2:5]) [30,Python,True]

>>> print(list1[ 2:]) [30,Python,True,1.5,(2+3j)]

>>> print(list1[ 2:-1]) [30,Python,True,1.5]

>>> print(list1[ -4:5]) [Python,True]

>>> print(list1[ -4:]) [30,Python,True,1.5,(2+3j)]

>>> print(list1[-5:]) [30,Python,True,1.5,(2+3j)]

>>> print(list1[ 2:5]) [30,Python,True]

List is a mutable object that means we can alter (or) replace the existing list object.

>>> List1=[10,20,30,'Python',True,1.5,2+3j]

>>>print(List1)  [10, 20, 30, 'Python', True, 1.5, (2+3j)]

>>> id(List1) 52330784

>>> List1[0]=100 #modifying the content of list

>>> print(List1) [100, 20, 30, 'Python', True, 1.5, (2+3j)]

>>> id(List1) 52330784 


78

 Here, the address of list , list1 is not changed before and after modification that’s why list
is a mutable object.

 list is a “mutable object” because we can’t modify the existing list object.

>>> for lst = [10,20,30] lst=[10,20,30] lst=[10,20,30,40]

>>> lst = [10,20,30]


10,20,30
>>> id(lst) 989 ,40
989

Same address

>>> lst.append(40)

>>> lst [10,20,30,40]

>>> id(lst) 989

List Concatenation :

 python support concatenating two or more list into single list.

E.g.,1 :-

>>> List1=[10,'Python',5.5]

>>> List2=[20,30,'Narayana',3+4j]

>>> print(List1) [10, 'Python', 5.5]

>>> print(List2) [20, 30, 'Narayana', (3+4j)]

>>> type(List1) <class ‘list’>

>>> type(List2)<class ‘list’>


>>> List3=List1+List2

>>> print(List3)[10, 'Python', 5.5, 20, 30, 'Narayana', (3+4j)]

>>> type(List 3)<class ‘list’>


79

E.g.,2: -

>>> l1= [10,20]

>>> l2= [30,40]

>>> l3= [true, 2.5]

>>> l4= l1+l2+l3

>>>l4 [10,20,30,40]

>>> type(l4) <class ‘list’>

List Multiplication/ List Repetition:

Python supports multiplying the given list into N number of times.

E.g.:

>>> List1=[10,'Python',5.5]

>>> List5=List1*3

>>>print(list5) [10,‘python’,5.5,10,‘python’, 5.5]

List Functions:

1. len(): This function “counts no.of elements” in the list.

E.g.:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]

>>> len(List1) 8

2. Count():This function counts the no.of occurrences of specific element in the list.

E.g.:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]

>>> List1.count(10) 2

E.g.:

>>> lst=[1,2,3,True,False,1,0,False]

>>> lst.count(10)
80

>>> lst.count(True)

E.g.:

>>> lst=[1,2,3,True,False,1,0,False,1+9j,1.1]

>>> lst.count(0)3

>>> lst.count(False) 3

3. Index():This function finds the index value for specific element.

E.g.,1:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]

>>> List1.index(10) 0

E.g.,2:

>>> lst=[1,2,3,True,False,1,0,False,1+9j,1.1]

>>> lst.index(1,1) 3

E.g.,3:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]

>>> List1.index(10,1) 6

Index on nested list:

E.g.: -

>>> lst =[100, True, 1, 2, 3, 4, 5, 0, [8, 9], 10, 20, 4]

>>> lst[8].index(9) 1

>>> lst[8].index(8) 0

4. Append(): This function adds new element at the end of the existing list.

E.g.,1:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]

>>> List1.append(50)

>>> print(List1)= [10, 20, 'Python', 30, True, 'Narayana', 10, (3+4j), 50]
81

E.g.,2:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]

>>> List1.append(60)

>>> print(List1)= [10, 20, 'Python', 30, True, 'Narayana', 10, (3+4j), 60]

• We can also add multiple element in the list by using append method but those multiple
element work like nested list (or) sub-list in the existing list.

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]

>>> List1.append([0,1,2])

>>> print(List1) [10, 20, 'Python', 30, True, 'Narayana', 10, (3+4j), [0, 1, 2]

5. Extend(): This function adds multiple elements at the end of the existing list.

E.g.,1:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j

>>> List1.extend([70,80,90])

>>> print(List1) [10, 20, 'Python', 30, True, 'Narayana', 10, (3+4j)

E.g.,2:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j

>>> List1.insert(3, ‘Durga’)

>>> print(List1) [10, 20, 'Python', 30, True, 'Narayana', 10, (3+4j)

6. Insert(): We can also add multiple elements in the list at required place by using
insert method but those multiple elements work like nested list or sub list in the
existing list.

E.g.:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]

>>> List1.insert(0[1,2,3])

>>> print(List1) [10, 20, 100, 'Python', 30, True, 'Narayana', 10, (3+4j)]
82

7. Remove():

a.This function removes specific element in the existing list.

b. This function allows one argument and that should be element name.

E.g.,1:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]

>>> List1.remove(10)

>>> print(List1)[20, 'Python', 30, True, 'Narayana', 10, (3+4j)]

E.g., 2:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]

>>> List1.remove(True)

>>> print(List1) [10, 20, 'Python', 30, 'Narayana', 10, (3+4j)]

8. Pop():

a. This function removes specific element based on its index position.

b. This function allows only one argument and that should be index number of an element. 

E.g.,1:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]

>>> List1.pop(1) 20

>>> print(List1) [10, 'Python', 30, True, ‘Narayana', 10, (3+4j)]

E.g.,2:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]

>>> List1.pop(2) 'Python'

>>> print(List1) [10, 20, 30, True, 'Narayana', 10, (3+4j)]

9. Reverse(): This function reverses the existing list.

E.g.,1:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]
83

>>> List1.reverse()

>>> print(List1) [(3+4j), 10, 'Narayana', True, 30, 'Python', 20, 10]

10. Copy(): This function copies the existing list into new variable.

E.g.:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]

>>> x=List1.copy()

>>> print(List1) [10, 20, 'Python', 30, True, 'Narayana', 10, (3+4j)]

>>> print(x) [10, 20, 'Python', 30, True, 'Narayana', 10, (3+4j)]

11. Clear():This function clears or removes all elements of the entire list.

E.g.:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]
>>> List1.clear()

>>> print(List1) []

12. Max(): this functions finds the maximum value in the given list.

E.g.:

>>> List2=[10,20,30,40]

>>> max(List2) 40

13. Min(): This function finds the minimum value in the given list.

E.g.:

>>> List2=[10,20,30,40]

>>> min(List2)10
14. sort():This function sorts the elements.

E.g.:

>>> lst=[1,9,5,11,2]

>>>lst.sort()

>>>print(lst)[1, 2, 5, 9, 11]
84

>>> l1=[1,2,5,3,7,4,2,True]

>>> l1.sort()

>>> print(l1)[1, True, 2, 2, 3, 4, 5, 7]


Note:

By default, this function sorts in ascending order, we can also get in descending order by
setting True for reverse.

E.g.,1:

>>> lst=[1,9,5,11,2]

>>> lst.sort(reverse=True)

>>> print(lst)[11, 9, 5, 2, 1]

E.g., 2:

>>> l1=[1,2,5,3,7,4,2,True] 110


>>> l1.sort(reverse=True)

>>> print(l1)[7, 5, 4, 3, 2, 2, 1, True]

del command:

This command is used to remove any specific element in the list (or) to remove entire list
object permanently.

NameError : List is not defined.


Removing specific element by using del command

E.g.,1:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]

>>> del List1[0]

>>> print(List1) [20, 'Python', 30, True, 'Narayana', 10, (3+4j)]

E.g.,2:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]

>>> del List1[4]


85

>>> print(list1) [10,20, ‘python’, 30, ‘Narayana’10,(3+4j)]


Removing entire list object by using del command

E.g.:

>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]

>>> del List1 #deleting lst

>>> print(List1) #after deleting

NameError: name 'lst' is not defined.

Difference between remove() and pop(): -

remove() pop()

It removes the specific element from the  It also removes the specific element as
existing list. remove() function.

 It can’t remove multiple element.  It can’t remove multiple.

 It will return the removed value.

Different between clear and del command.

Clear() del command

 clear is a function used to clear or remove the  del is a command is used to remove any
element from the list or object but not complete. specific or entire object.

It will return empty list after clean.

 It will entirely remove or deleted the list


from database.
E.g. >>> lst =[ 10,20,30,40]
E.g.>>> lst=[10, 20, 30, 40]
>>> lst.clear()
>>>del lst
 It will not support string and tuple.
 It will not support for string , tuple.
86

Q. How to display the existing list in ascending order?

Ans: >>> lst =[10,11,12,15,20]

>>> lst sort ()

>>> lst [10,11,12,15,20]

* To display ascending order, we can use or sort() function.

Q. How to display the existing list in descending order?

Ans: >>> lst=[10,20,11,15,12]

>>> lst.sort (reverse= True)

>>> lst

Q. How to display the existing list in reverse order?

Ans: >>> lst= [10,15,11,20]

>>> lst. reverse()

>>> lst [20,11,15,10]

Q. How to take the clone/copy of existing first by using copy() function or assignment
operator to take the clone existing list into new list?

Ans: >>> lst=[10,20,30]

>>> lst= lst.copy()

>>> lst1 [10,20,30]

>>> lst2 [10,20,30]

>>> lst= [10,20,30]

>>> lst= lst

>>> lst = [10,20,30]

>>> lst = [10,20,30]

Q. How to reverse a list by using slicing operator?

Ans: >>> lst= [10,20,30,40,50]


87

>>>lst[:: -1] [50,40,30,20,10]

Q. How to get [20,50] from lst=[10,20,30,40,50]?

Ans: >>> lst= [10,20,30,40,50]

0 1 2 3 4

>>> lst [1::3] [20,50]

Hint: [20 1 index 1+3= 4 :: 50]

Nested List:

Python supports Nested lists also; it means a list contains another lists.

E.g.:

>>> List1=[10,'Python',5.5]

>>> List2=[20,30,'Narayana',3+4j]

>>> List3=[1,True,2,'Durga']

>>> print(List1)[10, 'Python', 5.5]


>>> print(List2)[20, 30, 'Narayana', (3+4j)]
>>> print(List3)[1, True, 2, 'Durga']
>>> NestList=[List1,List2,List3]#creating a list by using existing lists.
>>> print(NestList)[[10, 'Python', 5.5], [20, 30, 'Narayana', (3+4j)], [1,

True, 2, ‘Durga’]]
>>> type(NestList)<class‘list’>
>>> print(NestList[0])[10, 'Python', 5.5]
>>> print(NestList[1])[20, 30, 'Narayana', (3+4j)]
>>> print(NestList[2])[1, True, 2, 'Durga']
>>> print(NestList[0][0])10
>>> print(NestList[0][1])'Python'
>>> print(NestList[0][2])5.5
>>> print(NestList[1][0])20
88

>>> print(NestList[1][3])(3+4j)
>>> print(NestList[2][0])1
>>> print(NestList[2][1])True
>>> print(NestList[2][2])2
>>> print(NestList[2][3])'Durga'

Working with index method on nested list:

E.g.:

>>> List1=[10,'Python',5.5]

>>> List2=[20,30,'Narayana',3+4j]

>>> List3=[1,True,2,'Durga']

>>> NestList=[List1,List2,List3]

>>> print(NestList) [[10, 'Python', 5.5], [20, 30, 'Narayana', (3+4j)]

[1,True,2, ‘Durga’]]

0 1 2

[10, ‘python’, 5.5] [20,30, ‘Narayana’,(3+4j)] [1, True, 2, ‘Durga’]

0 1 2 0 1 2 3 0 1 2 3

>>> NestList.index([10,'Python',5.5])0
>>> NestList[0].index(10)0
>>> NestList[0].index('Python')1
>>> NestList[0].index(5.5)2
>>> NestList.index([20,30,'Narayana',(3+4j)])1
>>> NestList[1].index(20)0
>>> NestList[1].index(30)1
>>> NestList[1].index('Narayana')2
>>> NestList[1].index((3+4j))3
>>> NestList.index([1, True, 2, 'Durga'])2
>>> NestList[2].index(1) 0
>>> NestList[2].index(True)0
>>> NestList[2].index(True,1)1
89

>>> NestList[2].index(2)2
>>> NestList[2].index('Durga')3
Conversions:

Converting a String into List: -

E.g.:

>>> Str1='Python is very simple and easy language'

>>> print(Str1) Python is very simple and easy language

>>> type(Str1)<class‘str’>
>>> List1=Str1.split()

>>> print(List1) ['Python', 'is', 'very', 'simple', 'and', 'easy', 'language']

>>> type(List1) <class‘str’>

Converting a List to String: -

E.g.:

>>> List1=['Python', 'is', 'very', 'simple', 'and', 'easy', 'language']

>>> print(List1) ['Python', 'is', 'very', 'simple', 'and', 'easy', 'language']

>>> type(List1)<class‘str’>
>>> Str2=" ".join(List1)

>>> print(Str2) Python is very simple and easy language

>>> type(Str2)<class‘str’>

The main difference between String and List is mutation.

1. String is immutable whereas List is mutable.

2. Mutable objects can be altered whereas immutable objects can’t be altered.

E.g.:String

>>> Str1='Python'

>>> print(Str1) Python

>>> id(Str1) 43143520


90

>>> Str1[0]='S'#trying to replace ‘P’ with ‘S’ in ‘Python’ string


Error:TypeError: 'str' object does not support item assignment.

We can add new letter to the existing String Str1 but now it will create as a new String Str1
variable in the memory.

>>> Str1=Str1+'s'

>>> print(Str1) Python

>>> id(Str1) 53595200


E.g.: List

>>> Lst1=[10,20,30,40,'Guido',50]

>>> print(Lst1) [10, 20, 30, 40, 'Guido', 50]

>>> id(lst1) 53663224


>>> Lst1[4]='Rossum' #trying to replace ‘Guido’ with ‘Rossum’ in Lst1

>>> print(Lst1) [10, 20, 30, 40, 'Rossum', 50]

>>> id(Lst1)53663224

List Packing:

A list can be created by using a group of variables, it is called list packing.

>>> a=10

>>> b=20

>>> c=True

>>> d='Py'

>>> list1=[a,b,c,d]

>>> print(list1) [10, 20, True, 'Py']

>>> type(list1)<class‘list’>

List Unpacking:

1. List unpacking allows to extract all list elements automatically into different variables.
91

2. The number of variables must be equal to number of elements in the list.

>>> lst=[10,20,'Python',True]

>>> print(lst)[10, 20, 'Python', True]


>>> type(lst)<class‘list’>
>>> a,b,c,d=lst#list unpacking

>>> print(a) 10

>>> type(a)<class‘int’>

>>> print(b) 20

>>> type(b) <class‘int’>

>>> print(c) ‘Python’

>>> type(c)<class‘str’>

>>> print(d) True

>>> type(d)<class‘bool’>
Q. How to generate a list as per user requirements?

Ans. start_val=int(input('Enter start value: '))

end_val=int(input('Enter end value: '))

step_size=int(input('Enter increment value: '))

UserList=range(start_val,end_val,step_size)

print(UserList)

output in Python2 output in Python3

Enter startvalue: 10Enter start value: 10

Enter end value: 21 Enter end value: 21

Enter increment value: 2 Enter increment value: 2


92

 [10, 12, 14, 16, 18, 20] range(10, 21, 2)

Adding different lists: -

We can add elements of different lists by using lambda and map functions

s=[1,20,3]

s1=[1,2,3]

print(list(map(lambda x,y:x+y,s,s1)))

s=[1,20,3]

s1=[1,2,3,8]

print([xy for x,y in zip(s,s1)])

s=[1,20,3,6,8]

s1=[1,2,3,8]

print([x+y for x,y in zip(s,s1)])

output: -

[2, 22, 6]

[2, 22, 6]

[2, 22, 6, 14]

List comprehension:

It provides an easy way to create list objects from any iterable objects based on some
conditions.

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

Q. How to display squares for all elements in the given list?

Ans.: >>> lst=[1,2,5,4,3]

>>> lst1=[x*x for x in lst]

>>> print(lst1) [1, 4, 25, 16, 9]


93

>>> type(lst1)<class‘list’>
Q. How to display squares for all even elements in the given list?

Ans.: >>> lst=[1,2,5,4,3]


>>> lst2=[x*x for x in lst if x%2==0]

>>> print(lst2) [4, 16]

>>> type(lst2)<class‘list’>
Q. How to display all unmatching elements from list1, those elements must not be in list2?
Ans.: >>> lst1=[1,2,3,4,5]

>>> lst2=[1,2,3,6,7]

>>> lst3=[i for i in lst1 if i not in lst2]

>>> lst3 [4,5]

>>> type(lst3) <class‘list’>

E.g.:

name=['narayana','sai','krishna','veni']

>>> list1=[[n.upper(),n.capitalize(),n.title(),len(n)] for n in name]

>>> print(list1)

[['NARAYANA', 'Narayana', 'Narayana', 8], ['SAI', 'Sai', 'Sai', 3], ['KRISHNA', 'Krishna',
'Krishna', 7], ['VENI', 'Veni', 'Veni', 4]]

By Using:-

Syn: [starting number:: increment value

The default increment value is 1.

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

>>> lst[1::] [20,30,40,50,60,70,80,90]

>>> lst[2::] [30,40,50,60,70,80,90]


>>> lst[8::] [90]
>>> lst[-7::] [30,40,50,60,70,80,90]
>>> lst[-9::] [10,20,30,40,50,60,70,80,90]
94

>>> lst[-9::3] [10,40,70]


>>> lst[-9::-2] [10,]
>>> lst[-9::-1] [10,]
>>> lst[5:6-3] [60,30]
>>> lst[5::-4] [60,20]
>>> lst[5::-1] [60,50,40,30,20,10]
>>> lst[::-9] [90]
>>> lst[::-8] [90,10]

>>> lst[::-5] [90,40]


>>> lst[::-4] [90,50,10]

List comparison:

When comparing lists, the elements will compare from both lists parallelly.

If the first elements from both lists are same then interpreter will compare the second
elements from both lists,

 If second elements from both lists are also same then interpreter will compare the third
elements from both lists.

Syn: cmp(list1,list2)

If list1 is bigger than list2 then interpreter will return 1.

If list1 is smaller than list2 then interpreter will return -1.

If list1 and list2 are same then interpreter will return 0.

E.g1:

>>> lst1=[1,2,3]

>>> lst2=[1,3,5,6]

>>> print cmp(lst1,lst2)

Explanation:here, the first element of lst1 is ‘1’ and first element of list2 is ‘1’, so both are
same. Now interpreter will compare second elements, like 2 in the lst1 and 3 in the lst2.
95

2 from lst1 is smaller than 3 from lst2, so interpreter returned -1.


E.g.,2:

>>> lst1=[10,20,30]

>>> lst2=[10,11,12,13]

>>> print cmp(lst1,lst2)

Explanation:here, first elements both list are same. 20 from lst1 is bigger than 11, so
interpreter returned 1.

E.g.,3:

>>> lst1=[10,20,30]

>>> lst2=[10,20,30]

>>> print cmp(lst1,lst2)

Explanation:here first elements from both lists are same. So, interpreter checked second
elements from lists, second elements are also same from both lists. Interpreter checked third
elements, but third elements are also same. Finally, all elements are same from both lists, so
interpreter returned 0.

E.g.,4:

>>> lst1=[10,20,30,40]

>>> lst2=[10,11,12]
>>> print cmp(lst1,lst2)

Explanation:first elements are same, 20 from lst1 is bigger than 11 from lst2. So, interpreter
returned 1.

E.g.,5:

>>> lst1=[1,2,3]

>>> lst2=[10,20]
96

>>> print cmp(lst1,lst2)

Explanation:1 from lst1 is smaller than 10 from lst2, so interpreter returned -1.

E.g6:

>>> lst1=[10]

>>> lst2=[1,2,3,4]

>>> print cmp(lst1,lst2)

Explanation:10 from lst1 is bigger than 1 from lst2, so interpreter returned 1.

E.g7:

>>> lst1=[1,2]

>>> lst2=[1,2,3]

>>> print cmp(lst1,lst2)

Explanation:first two elements(1,2) are same from both lists. Lst1 has no third element but
lst2 has 3rd element, that means lst1 is smaller than lst2. So, interpreter returned -1. E.g8:

>>> lst1=['a',1,2]

>>> lst2=[10,20]

>>> print cmp(lst1,lst2)

Tuple Data structure

1. Tuple is used to represent a set of homogeneous or heterogeneous elements into a single


entity.

2. Tuple objects are immutable that means once if we create a tuple later we cannot modify
that tuple object.
97

3. All elements are separated by commas (,) and enclosed by parentheses. Parentheses are
optional.

4. Tuple allows duplicate elements.

5. Every element in the tuple has its own index number.

6. Tuple supports both forward indexing and also backward indexing, forward indexing starts
from 0 and backward indexing starts from -1.

7. If we take only one element in the tuple then we should use comma (,) after that single
element.

8. Tuples can be used as keys to the dictionary.

9. We can create a tuple in different ways, like with tuple(), with () or without () also.

10. The main difference between lists and tuples is- Lists are enclosed in brackets ( [ ] ) and
their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated.

Creating a tuple with tuple():

E.g.:

>>> tup=tuple([10,20,30,True,'Python'])

>>> print(tup) (10, 20, 30, True, 'Python')

>>> type(tup) <class‘tuple’>

>>> id(tup)52059760

Creating an empty tuple:

E.g.:

>>> tup=() #creating empty tuple ()

>>> print(tup) ()

>>> type(tup) <class‘tuple’>

>>> id(tup)23134256

Creating a tuple with ():


98

E.g.:

>>> tup2=(10,20,30,40,50) #creating homogeneous tuple

>>> print(tup2) (10, 20, 30, 40, 50)

>>> type(tup2) <class ‘tuple’>

>>> id(tup2)63484864

Creating a tuple without ():

E.g.:

>>> tup=10,20,True,'Py' #creating tuple without parenthesis

>>> print(tup) (10, 20, True, 'Py')

>>> type(tup) <class ‘tuple’>

>>> id(tup)67086688
Creating a tuple with heterogeneous elements:

E.g.:

>>> tup1=(10,20,30,True,"Python",10.5,3+5j)

#creating heterogeneous tuple

>>> print(tup1) (10, 20, 30, True, 'Python', 10.5, (3+5j))

>>> type(tup1) <class ‘tuple’>

>>> id(tup1)58963648

Creating a tuple with single element:

Creating a tuple with a single element is tricky, if we take only one element then the type
that tuple will be based on specified element.
E.g.:
>>> t2=(1)

>>> t2 1

>>> type(t2)<type ‘int’>


>>> t2=(True)
99

>>> print(t2) True

>>> type(t2)<type‘bool’>
So, to solve the above problem we should use comma (,) after the element in the tuple, like

E.g.:

>>> t2=(1,)

>>> print(t2) (1,)

>>> type(t2) <class‘tuple’>

E.g.:

>>> t2=(false)

>>> print(t2) False

>>> type(t2) <class ‘bool’>

Tuple Indexing:

Tuple indexing is nothing but fetching a specific element from the existing tuple by using its
index value.

E.g.:

>>> tup = (10,20,30, True,“python”,10.5,3+5j,10)

>>> print(tap) (10,20,30,‘python’10.5,(3+5j))

>>> type(p)<class‘tuple’>

>>> id(tap) 63560624

0 1 2 3 4 5 6 7

10 20 30 True python 10.5 3+5j 10

-8 -7 -6 -5 -4 -3 -2 -1

>>> tup[0]10
>>> tup[1]20
>>> tup[2]30
>>> tup[3]True
100

>>> tup[4]'Python'
>>> tup[5]10.5
>>> tup[6](3+5j)
>>> tup[7]10
>>> tup[-1]10
>>> tup[-2](3+5j)
>>> tup[-3]10.5
>>> tup[-4]'Python'
>>> tup[-5]True
>>> tup[-6]30
>>> tup[-7]20
>>> tup[-8]10

Tuple Slicing:

Tuple slicing is nothing but fetching a sequence of elements from the existing tuple by using
their index values.

E.g.:

>>> tup=(10,20,30,True,"Python",10.5,3+5j,10)

>>> print(tup) (10, 20, 30, True, 'Python', 10.5, (3+5j), 10)

>>> type(tup) <class‘tuple’>

>>> id(tup)63560496

0 1 2 3 4 5 6 7
10 20 30 True “Python” 10.5 3+5j 10

-8 -7 -6 -5 -4 -3 -2 -1

>>> tup[0:4](10, 20, 30, True)


>>> tup[0:0]()
>>> tup[0:1](10,)
101

>>> tup[0:5](10, 20, 30, True, 'Python')


>>> tup[3:5](True, 'Python')
>>> tup[2:-2](30, True, 'Python', 10.5)
>>> tup[-5:-2](True, 'Python', 10.5)
>>> tup[-5:](True, 'Python', 10.5, (3+5j), 10)
>>> tup[6:]((3+5j), 10)

E.g.,1: -

tuple1 = ( 'Narayana', 1037 , 1000, 'Python', True )

tinytuple = ('Super', 'Django',True)

print (tuple1) # Prints complete tuple

print (tuple1[0]) # Prints first element of the tuple

print (tuple1[1:3])# Prints elements starting from 2nd till 3rd

print (tuple1[2:]) # Prints elements starting from 3rd element

print (tinytuple * 2) # Prints tuple two times

print (tuple1 + tinytuple) # Prints concatenated tuple

Output:

('Narayana', 1037, 1000, 'Python', True)

Narayana

(1037, 1000)

(1000, 'Python', True) 130


('Super', 'Django', True, 'Super', 'Django', True)

('Narayana', 1037, 1000, 'Python', True, 'Super', 'Django', True)

Tuple concatenation:

We can concatenate two or more tuples in python.

E.g.:

>>> tup1=(1,2,3,'a',True) #creating first tuple tup1


102

>>> print(tup1) (1, 2, 3, 'a', True)

>>> type(tup)<class‘tuple’>

>>> tup2=(10,20,False,'b') #creating second tuple tup2

>>> print(tup2) (10, 20, False, 'b')


>>> type(tup2)<class‘tuple’>

>>> tup3=tup1+tup2 #concatenating tup1 and tup2 as tup3

>>> print(tup3) (1, 2, 3, 'a', True, 10, 20, False, 'b')

>>> type(tup3)<class‘tuple’>

Tuple multiplication or repetition:

We can multiply or repeat a tuple n number of times.

E.g.:

>>> tup1=(1,2,3,'a',True)

>>> print(tup1) (1, 2, 3, 'a', True)

>>> type(tup1) <class‘tuple’>

>>> tup1*3(1, 2, 3, 'a', True, 1, 2, 3, 'a', True, 1, 2, 3, 'a', True)

Tuple Functions:

1. All():This function returns True if all elements are true, if any element is false (either 0 or
False) then it will return Fasle. For empty tuple also it will return True.

E.g.:

>>> tup=(1,2,3)

>>> print(all(tup))True

>>> tup=(1,2,3,0)
103

>>> print(all(tup))False
>>> tup=(2,3)

>>> print(all(tup))True

>>> tup=()

>>> print(all(tup))True

>>> tup=(True,)

>>> print(all(tup))True

2. Any():This function returns true if any one element is true in the tuple.

E.g.:

>>> tup=(1,2,3)

>>> print(any(tup))True

>>> tup=(1,2,3,0)

>>> print(any(tup))True

>>> tup=(False,2,3)

>>> print(any(tup))True

>>> tup=(False,0,0,False)

>>> print(any(tup))False

>>> tup=()

>>> print(any(tup))False

3. Len():This function returns no.of elements in the tuple.

E.g.:

>>> tup=(1,2,3,4,'a',5.5)
104

>>> len(tup) 6

4. Count():This function counts the number of occurrences of a specific elements.


E.g.:

>>> tup=(1,10,20,True,0)

>>> tup.count(1) 2

>>> tup.count(0)1

5. Index():This function is used to find the index value of specific element.

E.g.:

>>> tup=(1,10,20,True,0)

>>> tup.index(0) 4

>>> tup.index(10) 1

>>> tup.index(20) 2

6. Max():This function returns maximum value from the tuple elements.

E.g.:

>>> tup=(1,3,2,55,3,5,23)

>>> max(tup)55

7. Min():This function returns minimum value from the tuple elements.

E.g.:

>>> tup=(1,3,2,55,3,5,23)

>>> min(tup)1

8. Sorted():This function sorts the data.

E.g.:

>>> tup=(1,3,2,55,3,5,23)
105

>>> sorted(tup)[1, 2, 3, 3, 5, 23, 55]

Note:by default, this function sorts the data in ascending order. We can also get in
descending order by setting True for Reverse.

E.g.:

>>> tup=(1,3,2,55,3,5,23)

>>> sorted(tup,reverse=True)[55, 23, 5, 3, 3, 2, 1]

Or

>>> t1=tuple([1,2,3,7,4])

>>> t1 (1, 2, 3, 7, 4)

>>> t2=reversed(t1)

>>> tuple(t2)(4, 7, 3, 2, 1)

9. Sum(): This function returns sum of all the elements.

E.g.:

>>> lst=[1,9,5,11,2]

>>> sum(lst)28
Del command: -

We cannot delete the element of existing tuple, but we can delete the entire tuple object
by using del command.

E.g.:

>>> tup = (10,20,“python’’,1.3)

>>> Print(tup) (10,20,‘python’,1.3)

>>> type(tup) <class‘tuple’>

>>> del tup # deleting tuple by using del command

>>> print(tup) # after deleting


106

NameError : name ‘tup’ is not defined.

We can replace the element of list but not tuple, like,

>>> lst= [10,20,30,‘py’, True]

>>> lst[4] = false #its possible in list

>>> print(lst)

[10,20,30,‘py’,False]
>>> tup=(10,20,30,'Py',True)

>>> tup[4]=False #it’s not possible in tuple

Traceback (most recent call last):

File "<py.shell#15>", line 1, in <module>

tup[4]=False

TypeError: 'tuple' object does not support item assignment.

Q. How to display the given tuple in ascending order?

Ans: >>> tup=(10,20,5,3,30)

>>> tup=sorted(tup)

>>> print(tup)[3, 5, 10, 20, 30]

Q. How to reverse the given tuple?

Ans: >>> tup=(10,20,5,3,30)

>>> tup=reversed(tup)
>>> print(tuple(tup))(30, 3, 5, 20, 10)

Nested tuple:

1. Python supports nested tuple, i.e., a tuple in another tuple.

2. Tuple allows list as it’s element.


107

E.g.:

>>> t1=(1,'a',True)

>>> print(t1)(1, 'a', True)

>>> type(t1)<class‘tuple’>

>>> t2=(10,'b',False)

>>> print(t2) (10, 'b', False)

>>> type(t2)<class‘tuple’>

>>> t3=(t1,100,'Python',t2)#creating a tuple with existing tuples t1 and t2


>>> print(t3) ((1, 'a', True), 100, 'Python', (10, 'b', False))
>>> type(t3)<class‘tuple’>

>>> print(t3[0])(1, 'a', True)


>>> print(t3[1])100
>>> print(t3[2])Python
>>> print(t3[3])(10, 'b', False)
>>> print(t3[3][0])10
>>> print(t3[3][1])b
>>> print(t3[3][2])False
>>> print(t3[0][0])1
>>> print(t3[0][1])a
>>> print(t3[0][2])True
>>> t3[0:2]((1, 'a', True), 100)
>>> t3[2:4]('Python', (10, 'b', False))

>>> t3[-2:4]('Python', (10, 'b', False))

Note: we can’t modify any element of the above tuples because tuples are immutable. If the
tuple contains a list as an element then we can modify the elements of the list as it a mutable
object.
108

E.g.:

>>> tup=(1,2,[10,12,'a'],(100,200,300),3,'Narayana')

>>> print(tup) (1, 2, [10, 12, 'a'], (100, 200, 300), 3, 'Narayana')

>>> print(tup) “ ” ”

>>> type(tup) <class‘tuple’>

>>> tup[0] 1

>>> tup[1] 2

>>> tup[2] [10, 12, 'a']

>>> tup[3] (100, 200, 300)

>>> tup[4] 3

>>> tup[5]'Narayana'
>>> tup[0]=50 #trying to replace element 1 with 50, interpreter throws

error.

TypeError:'tuple' object does not support item assignment.

>>> tup[1]=50 #trying to replace element 2 with 50, interpreter throws error.

>>> tup[1]=50 #trying to replace element 2 with 50, interpreter throws error.

TypeError:'tuple' object does not support item assignment.

>>> tup[2]=50 #trying to replace element [10,12,’a’] with 50, interpreter throws

error.

TypeError:'tuple' object does not support item assignment.

>>> tup[2][0]=50 #trying to replace element of list 100 with 50, interpreter accepts. >>>
print(tup)(1, 2, [50, 12, 'a'], (100, 200, 300), 3, 'Narayana')

Conversions:

Converting tuple to list

>>> tup=(1,2,4,9,8) #creating a tuple


109

>>> print(tup) (1, 2, 4, 9, 8)


>>> type(tup)<class‘tuple’>

>>> lst=list(tup)#converting tuple to list by using list()


>>> print(lst) [1,2,4,9,8]

>>> type(lst)<class‘tuple’>

Converting list to tuple

>>> lst=[10,20,30,40,'a'] #creating a list

>>> print(lst) [10, 20, 30, 40, 'a']

>>> type(lst)<class‘tuple’>

>>> tup=tuple(lst)#converting list to tuple by using tuple()


>>> print(tup) (10, 20, 30, 40, 'a')

>>> type(tup)<class‘tuple’>

Converting tuple to string

>>> tup=('a','b','c') #creating tuple

>>> print(tup) ('a', 'b', 'c')


>>> type(tup)<class‘tuple’>

>>> str1=''.join(tup)#converting tuple to string by using join method


>>> print(str1) abc

>>> type(str1)<class‘str’>

Converting string to tuple

>>> str1="Python Narayana" #creating a string

>>> print(str1) Python Narayana


110

>>> type(str1)<class‘str’>

>>> tup=tuple(str1)#converting a tuple to string by using tuple function.

>>> print(tup) ('P', 'y', 't', 'h', 'o', 'n', ' ', 'N', 'a', 'r', 'a', 'y', 'a', 'n', 'a')

>>> type(tup)<class‘str’>

Tuple packing:

We can create a tuple by using existing variables, so it’s called tuple packing.

E.g.:

>>> a=10

>>> b=20
>>> c='Python'

>>> d=2+5j

>>> tup=(a,b,c,d)

>>> print(tup) (10, 20, 'Python', (2+5j))

>>> type(tup) <class‘tuple’>

>>> id(tup)62673808

Tuple Unpacking:

1. Tuple unpacking allows to extract tuple elements automatically.

2. Tuple unpacking is the list of variables on the left has the same number of elements as the
length of the tuple.

>>> tup=(1,2,3,4)

>>> a,b,c,d=tup# tuple unpacking


>>> print(a) 1

>>> print(b) 2

>>> print(c) 3
111

>>> print(d) 4

Advantages of Tuple over List


• Generally, we use tuple for heterogeneous elements and list for homogeneous elements.

• Iterating through tuple is faster than with list because tuples are immutable, So there might
be a slight performance boost.

• Tuples can be used as key for a dictionary. With list, this is not possible because list is a
mutable object.

• If you have data that doesn't change, implementing it as tuple will guarantee that it remains
writeprotected

.
Difference between list and tuple:

1. If we need to add or remove the elements to object in the future then we choose list. If we
don’t want to add or remove the elements to the object in the future then we choose tuple.

2. List is represented by [] Tuple is represented by ().

3. [] are compulsory for list

() are optional for tuple

4. We can delete specific element by using Del command in the list.

We can't delete specific element by using Del in the tuple.

5. We can clear all elements of a list by using clear () We can’t clear all elements of a tuple
by using clear ().

6. When we create a tuple with one element, then we should use comma ',' after the element
Comma is not required in the list to create list with single element.

7. List is dynamic object Tuple is static object .

8. We can add or remove elements in the list by using append (), extend (), insert (), remove
() and pop () We can’t add or remove elements in the tuple by using functions.
9. Range () is used to generate the list. Range () is not used to generate the tuple.
112

10. Split () result stores in list format Database data stores in tuple format when we fetched
data from database to python application.

By using:-

>>> t= (10,‘py’,30,40,10,70,‘Narayana’,‘Python’)

>>>t[1::] (‘py’,30,40,10,70,‘Narayana’,‘Python’)

>>> t[2::] (30,40,10,70,‘Narayana’,‘Python’)

>>> t[3::] (40,10,70,‘Narayana’,‘Python’)

>>> t[7::] (‘Python’)

>>> t[8::] ()

>>> t[1::1] (‘py’,30,40,10,70,‘Narayana’,‘Python’)

>>> t[1::4] (‘py’,70)

>>> t[1::8] (‘py’,)

>>> t[1::7] (‘py’,)

>>> t[2::5] (30, ‘Python’)

>>> t[2::6] (30,)

>>> t[2::7] (30,)

>>> t[3::3] (40,‘Narayana’)

>>> t[3::4] (40,‘Python’)

>>> t[3::6] (40,)

>>> t[7::1] (‘Python’)

>>> t[8::1] ()

>>> t[2::-1] (30,‘py’,10)

>>> t[-1::5] (‘Python’)

Tuple comparison:

E.g.,1:In Python 2:
113

>>> tup1=(10,20,30)

>>> tup2=(11,12)

>>> print cmp(tup1,tup2)-1

E.g.,2:

>>> tup1=(10,20,30)

>>> tup2=(1,2,3,4,5)

>>> print cmp(tup1,tup2)1

E.g.,3:

>>> tup1=(10,20,30)

>>> tup2=(10,20,30,4,5)

>>> print cmp(tup1,tup2)-1

E.g.,4:

>>> tup1=(10,20,30)

>>> tup2=(10,20,30)

>>> print cmp(tup1,tup2)0

E.g.,5:

>>> tup1=(10,30,20)

>>> tup2=(10,20,30)

>>> print cmp(tup1,tup2)1

E.g.,6:

>>> tup1=('a','b','x')

>>> tup2=('a','b','y')

>>> print cmp(tup1,tup2)-1

E.g.,7:

>>> tup1=(True,True)
114

>>> tup2=(False,True)

>>> print cmp(tup1,tup2)1

Set- Data Structure


1. A set is unordered collection of unique elements.

2. Set is commonly used in membership testing, removing duplicates from a sequence, and
computing mathematical operations such as intersection, union, difference, and symmetric
difference.

3. Set will not allow duplicate values.

4. Insertion order is not preserved but elements can be sorted

5. The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set.

6. Sets do not support indexing, slicing,

7. Sets do not support concatenation and multiplication.

8. There are currently two built-in set types,

a. set,

b. frozenset.

Set:The set type is mutable - the contents can be changed using methods like add() and
remove(). Since it is mutable, it has no hash value and cannot be used as either a dictionary
key or as an element of another set.

Frozenset:The frozenset type is immutable. Its contents cannot be altered after it is created;
it can be used as a dictionary key or as an element of another set.

We can create a set in different ways,

1. Creating an empty set using set() and add elements to that empty set.

E.g.:
115

>>> se1=set()#creating an empty set with set()


>>> se1.add(10)#adding elements to empty set

>>> se1.add(20) #adding elements to empty set

>>> se1.add(10)#adding duplicate value to set

>>> print(se1){10, 20, 30}

2. Creating a set with elements using set().

E.g.:

>>> se2=set([1,2,4,'a',2+4j,True]) #creating set with set()

>>> print(se2) {1, 2, 4, (2+4j), 'a'}

>>> type(se2)<class ‘set’>

3. Creating a set with curly braces.

E.g.:

>>> se3={1,2,3,4,"Narayana",True} #creating a set with curly braces

>>> print(se3){1, 2, 3, 4, 'Narayana'}

>>> type(se3)<class ‘set’>

Performing membership operations :

We use ‘in’ and ‘not in’ to perform membership operations.

‘in’ and ‘not’ are used to check the specific element is a part of the existing set or not .

>>> se1={10,20,30,True,100,'Narayana','Python'}

>>> 'Narayana' in se1 True

>>> 'Django' in se1 False

>>> 'Oracle' in se1False

>>> 1 not in se1 False

>>> 100 not in se1 False

>>> 20 in se1 True


116

Removing duplicate elements from other sequence

E.g.:

>>> lst=[10,20,10,40,50,10,20]

>>> lst=list(set(lst))

>>> print(lst)[40, 10, 20, 50]

>>> type(lst)<class‘set’>

Set functions :

Add():This function adds new elements to existing set.

E.g.:

>>> se1={1,2,3,4,5}

>>> print(se1){1, 2, 3, 4, 5}

>>> se1.add(6)#adding elements

>>> se1.add(7)
>>> print(se1) {1, 2, 3, 4, 5, 6, 7}

Note:We cannot add new elements to the frozenset.

>> fs=frozenset([10,20,30,40])

>>> print(fs){10,20,30,40}
>>> fs.add(50) #trying to add new element to frozenset.

Error: AttributeError: 'frozenset' object has no attribute 'add'

Remove():it will remove elements from the set, if that element is not found then it will throw
error.

E.g.:

>>> se1={1,2,3,4,5}

>>> print(se1) {1, 2, 3, 4, 5}


117

>>> type(se1)<class‘set’>
>>> se1.remove(5) #removing element from set

>>> se1.remove(4) #removing element from set

>>> se1.remove(15)#trying to remove element which is not there in set.

Error: KeyError: 15

Discard():it will remove elements from the set, if that element is not fund in the set then it
will do nothing.

E.g.:

>>> se1={1,2,3,4,5}

>>> print(se1){1, 2, 3, 4, 5} 151


>>> se1.discard(7) #trying to remove element which not there in the set.

>>> se1.discard(20) #trying to remove element which not there in the set.

>>> se1.discard(5). #removing element which is there in the set

>>> print(se1) {1,2,3,4}

the difference between remove() and discard() is,

remove():if we take the element which is not there in the set then it will throw error.

discard():if we take the element which is not there in the set then it will do nothing, means it
will not throw error.

Copy(): this function copies the elements of one set to another new set.

E.g.:

>>> se1={1,2,3,4,5}

>>> se2=se1.copy() #copying se1 elements to se2

>>> se1 {1, 2, 3, 4, 5}

>>> se2{1, 2, 3, 4, 5}

Clear():this function clears the existing function.


118

E.g.:

>>> se1={1,2,3,4,5}

>>> print(se1) {1, 2, 3, 4, 5}

>>> type(se1)<class‘set’>
>>> se1.clear() #clearing the se1, so se1 will become empty set.

>>> print(se1) set()

Isdisjoint():this function returns True if both are empty sets or if both sets contains non-
matching elements.

E.g.:

>>> se1=set()

>>> se2=set()

>>> se1.isdisjoint(se2)True

>>> se1=set()

>>> se2={1,2,3}

>>> se1.isdisjoint(se2)True

>>> se1={1,2,3}

>>> se2={1,2,3,4}

>>> se1.isdisjoint(se2)False

Issubset():x.issubset(y) returns True, if x is a subset of y. "<=" is an abbreviation for "subset


of"
E.g.:

>>> se1={1,2,3,4,5}

>>> se2={1,2,3}

>>> se2.issubset(se1) True

>>> se1.issubset(se2)False

Or
119

>>> se2>=se1 True

>>> se1>=se2False

Issuperset():x.issuperset(y) returns True, if x is a superset of y. ">=" is an abbreviation for


"issuperset of"
E.g.:

>>> se1={1,2,3,4,5}

>>> se2={1,2,3}

>>> se2.issuperset(se1) False

>>> se1.issuperset(se2) True

>>> se2>=se1 False

>>> se1>=se2True

We can also check the elements whether they belong to set or not,

E.g.:

>>> se1={1,2,3,"Python",3+5j,8}

>>> 4 in se1 False

>>> 1 in se1 True

>>> "Python" in se1 True

>>> 10 not in se1 True

>>> "Narayana" not in se1 True

Union: it returns the union of two sets, that means it returns all the values from both sets
except duplicate values.

The same result we can get by using ‘|’ between two sets

Syn: <First_set.union (<second_set>) or

<First= set>/ <second_set>

E.g.:
120

>>> se1={1,2,3,4,5}

>>> se2={1,2,3,6,7}

>>> se1.union(se2) {1, 2, 3, 4, 5, 6, 7}

>>>se1|se2{1, 2, 3, 4, 5, 6, 7}

Or

>>>>>> se2.union(se1){1, 2, 3, 4, 5, 6, 7}

>>> se2|se1{1, 2, 3, 4, 5, 6, 7}

Intersection: it returns an intersection elements of two sets, that means it returns only
common elements from both sets.

That same operation we can get by sing ‘&’ operator.

Syn: < First_ set>.intersection (<second_set>) or

< First= set>&<second_set>

E.g.:

>>> se1={1,2,3,4,5}

>>> se2={1,2,3,6,7}

>>> se1.intersection(se2) {1,,2, 3} or

>>> se1&se2{1, 2, 3}

Or

>>> se2.intersection(se1) {1, 2, 3}

>>> se2&se1 {1, 2, 3}

Diffferenece: It returns all elements from first set which are not there in the second set.
121

Syn: < First_ set>. difference (<second_set>) or

< First= set> . <second_set>


or

E.g.:

>>> se1={1,2,3,4,5}

>>> se2={1,2,3,6,7}

>>> se1.difference(se2) {4, 5} or

>>> se1-se2 {4, 5}

Or

>>> se2.difference(se1) {6, 7}

>>> se2-se1 {6, 7}

Intersection_update:this function will update the First_Set with the result of intersection
between First_Set and Second_Set.

Syn: < First_ set>. intersection_update (<second_set>)

E.g.:

>>> se1={1,2,3,4,5}

>>> se2={1,2,3,6,7}

>>> se1.intersection_update(se2)

>>> print(se1) {1, 2, 3}

>>> print(se2) {1, 2, 3}


Or

>>> se1={1,2,3,4,5}

>>> se2={1,2,3,6,7}

>>> se2.intersection_update(se1)
122

>>> print(se1) {1, 2, 3, 4, 5}

>>> print(se2) {1, 2, 3}

Differenece_update:the result of difference between two sets will in First_Set.

Syn: < First_ set>. intersection_update (<second_set>)

E.g.:

>>> se1={1,2,3,4,5}

>>> se2={1,2,3,6,7}

>>> se1.difference_update(se2)

>>> print(se1) {4,5}

>>> print(se2) {1, 2, 3, 6, 7}


Or

>>> se1={1,2,3,4,5}

>>> se2={1,2,3,6,7}

>>> se2.difference_update(se1)

>>> print(se1) {1, 2, 3, 4, 5}

>>> print(se2) {6, 7}

Symmetric difference:It returns unmatching elements from both sets.

Syn: < First_ set> symmetric_update (<second_set>)

E.g.:

>>> se1={1,2,3,4,5}

>>> se2={1,2,3,6,7}

>>> se1.symmetric_difference(se2) {4, 5, 6, 7}


123

>>> se2.symmetric_difference(se1) {4, 5, 6, 7}


symmetric_difference_update:it will store the unmatching elements from both sets into
First_Set.

Syn: < First_ set>. intersection_update (<second_set>)

E.g.:

>>> se1={1,2,3,4,5}

>>> se2={1,2,3,6,7}

>>> se1.symmetric_difference_update(se2)

>>> print(se1) {4, 5, 6, 7}

>>> print(se2){1, 2, 3, 6, 7}

Or

>>> se1={1,2,3,4,5}

>>> se2={1,2,3,6,7}

>>> se2.symmetric_difference_update(se1)

>>> print(se1) {1, 2, 3, 4, 5}

>>> print(se2){4, 5, 6, 7}

Set and frozen sets support the following operator:

Key in s # containment check

Key in s # non-containment check

Se1== Se2 # S1 is equivalent to S2

Se1!= Se2 # S1 is inequivalent to S2

Se1= Se2 # S1 is subset to S2

Se1< Se2 # S1 is proper subset to S2

Se1= Se2 # S1 is superset to S2


124

Se1> Se2 # S1 is proper superset to S2

Se/ Se2 # the unionof S1 &S2

Se& Se2 # the intersection ofS1&S2

Se1_ Se2 # the set of element of S1 but not S2

Se1 Se2 # the set of element in precisely

one of S1 & S2.

remove() discard()

remove() used to remove specific  discard function allow an element as an


element. argument.

 It the element is not available in the  It remove the specific element.


given set remove() through keyerror.

 It is element not available in the given


set discard() doesn’t through any error.

Set Unpacking:

>>> se= {1, 2, 3, ‘x’, True}

>>> a, b, c, d= se

Print(a) 1

Print(b) <class‘int’>

Print(a) 2

Print(b) <class‘int’>

Print(a) 3
125

Print(b) <class‘int’>

Print(a) x

Print(b) <class‘str’>

Set packing

>>> a=10

>>> b=20

>>> c= 30

>>> d= ’a’

>>> se= {a, b, c, d}

>>> print(se) {10, ‘a’, 20,30}

>>> type(se) <class‘set’>

>>> id(se) 105865744

Using set in the List:

>>> lst=[10,20,30,{True,2,False,3},[1,2,{100,200,300}]]

>>> print(lst) [10, 20, 30, {False, True, 2, 3}, [1, 2, {200, 100, 300}]]

>>> len(lst) 5

>>> lst[0] 10

>>> lst[1] 20

>>> lst[2] 30

>>> lst[3] {False, True, 2, 3}


>>> len(lst[3]) 4

>>> lst.index({False,True,2,3}) 3

>>> lst[3][0]TypeError: 'set' object does not support indexing


>>> lst[4] [1, 2, {200, 100, 300}]

>>> len(lst[4]) 3
126

>>> lst[4][0] 2

>>> lst[4][1] 1

>>> lst[4][2] {200, 100, 300}

>>> lst[4].index(1) 0
>>> lst[4].index(2) 1

>>> lst[4].index({200,100,300})

>>> lst[4].index({200,300,100})

>>> lst[4].index({300,100,200})
>>> lst[0:2] [10, 20]

>>> lst[0:3] [10, 20, 30]

>>> lst[0:4] [10, 20, 30, {False, True, 2, 3}]

>>> lst[0:5] [10, 20, 30, {False, True, 2, 3}

E.g.,1:

>>> lst[0:lst[5][2]] IndexError: list index out of range

Note:the given list has index number upto 4 only, but we are trying to access 5, which is not
available.

Using set in the tuple:

E.g.,1:

>>> t=(11,True,{2,3,1},12,13,(10,20,[100,200,300,{25,35,45}]))

>>> print(t) (11, True, {1, 2, 3}, 12, 13, (10, 20, [100, 200, 300, {25, 35, 45}]))

>>> len(t) 6

>>> t[0] 11

>>> t[1] True


127

>>> t[2] {1, 2, 3}

>>> t[2][0] TypeError: 'set' object does not support indexing

>>> t[2][1] TypeError: 'set' object does not support indexing

>>> t[2][2] TypeError: 'set' object does not support indexing

>>> t[3] 12

>>> t[4] 13

>>> t[5] (10, 20, [100, 200, 300, {25, 35, 45}])

>>> t[5][0] 10

>>> t[5][1] 20

>>> t[5][2][1] 200

>>> t[5][2][2] 300

>>> t[5][2][3][0] TypeError: 'set' object does not support indexing

>>> t[5][2][3][1]TypeError: 'set' object does not support indexing


>>> t[0:2] (11, True)

>>> t[0:4] (11, True, {1, 2, 3}, 12)

>>> t.index({1,3,2}) 2

>>> len(t[5]) 3

>>> t[1:t[5][0]] (True, {1, 2, 3}, 12, 13, (10, 20, [100, 200, 300,

{25, 35, 45}]))

Dictionary Data Structure


1. Dictionary is an unordered set of key: value pairs, here keys are unique.

2. A pair of braces creates an empty dictionary: {}.

3. The main operations on a dictionary are storing a value with some key and extracting the
value given the key.

4. Dictionary keys are not allowed duplicates, but dictionary values are allowed duplicates. 5.
We can use homogeneous and heterogeneous elements for both keys and values.
128

6. Insertion order is not preserved.

7. Dictionary keys are immutable, and values are mutable.

8. Dictionary will not allow indexing and slicing.

9. Dictionaries are indexed by keys, which can be any immutable type; strings and numbers
can always be keys. Tuples can be used as keys if they contain only strings, numbers, or
tuples;

 If a tuple contains any mutable object either directly or indirectly, it cannot be used as a
key. You can’t use lists as keys, since lists can be modified in place using index assignments,
slice assignments, or methods like append() and extend().

We can create dictionary in different ways,

1. Creating empty dictionary and adding key:value pairs.

E.g.:

>>> dic1={}

>>> print(dic1) {}

>>> type(dic1)<class‘dict’>
>>> dic1['a']=10 #adding Key: Value pair to dictionary

>>> dic1['b']=20 #adding Key:Value pair to dictionary

>>> dic1['c']=30#adding Key:Value pair to dictionary


>>> dic1['a']=10 #trying to add same Key:value pair

>>>dic1['a']=50#adding new value for same key ‘a’


>>> print(dic1){'a': 50, 'b': 20, 'c': 30}

2. Creating a dictionary with dict() function

E.g.:

>>> dic1=dict([('a',10),('b',20),('c',30),('d',40)])

>>> print(dic1) {'a': 10, 'b': 20, 'c': 30, 'd': 40}
>>> type(dic1)<class‘dict’>
129

3. Creating a dictionary with curly braces including key:value pairs

E.g.:

>>> dic1={'a':10,'b':20,'c':30,'d':40}

>>> print(dic1){'a': 10, 'b': 20, 'c': 30, 'd': 40}

>>> type(dic1)<class‘dict’>

Accessing data from dictionary

We can assign values to the keys and later we can fetch values by using Keys

E.g.,1:

>>> stuDetails={'Id':100,'Name':'Sai','Age':20,'Marks':90}

>>> print(stuDetails) {'Id': 100, 'Name': 'Sai', 'Age': 20, 'Marks': 90}

>>> type(stuDetails)<class ‘dict’>

>>> print(stuDetails['Id']) 100

>>> print(stuDetails['Age']) 20

E.g.,2:

>>> stuDetails={'Id':100,'Name':'Sai', 'subjects':['SQL Server', 'Oracle', 'Python']}


>>> stuDetails {'Id': 100, 'Name': 'Sai', 'subjects': ['SQL Server', 'Oracle', 'Python']}

>>> stuDetails['Id'] 100

>>> stuDetails['Name'] 'Sai'

>>> stuDetails['subjects'] ['SQL Server', 'Oracle', 'Python']

>>> stuDetails['subjects'][0] 'SQL Server'

>>> stuDetails['subjects'][1] 'Oracle'

>>> stuDetails['age']KeyError: 'age'#this key not available


130

To prevent this type of error we can check whether the specified key existed or not by using
has_key().But this has_key()is available in python2 only not in python3 version.

>>> stuDetails.has_key('age') False #in python2 version

In python3 we have to check by using membership operator ‘in’.

>>> 'age' in stuDetails False #in python3 version

Adding new key:value pairs


{‘id’100,‘Name’:‘Sai’,‘Subjects’:[‘SQL Server’, ‘Oracle’, ‘Python’}

If we need to add another element then

>>> stuDetails['Age']=25#adding new element to the stuDetails Dictionary

>>> print(stuDetails) {'Id': 100, 'Name': 'Sai', 'subjects': ['SQL Server', 'Oracle',

'Python'], 'Age': 25}

Updating dictionary values:

If we need to change the age from 25 to 27 then

>>> stuDetails['Age']=27 #changing the age from 25 to 27

>>> print(stuDetails){'Id': 100, 'Name': 'Sai', 'subjects': ['SQL Server', 'Oracle',

'Python'], 'Age': 27}


Deleting key:value pairs from dictionary

If we need to delete the value 27 from the above dictionary then (by using pop)

>>>stuDetails.pop('Age') 27

>>> print(stuDetails)

{'Id': 100, 'Name': 'Sai', 'subjects': ['SQL Server', 'Oracle', 'Python']}

We can also delete by using popitem()

#this function removes last key:value pair in the dictionary,

>>> stuDetails.popitem() ('subjects', ['SQL Server', 'Oracle', 'Python'])

If we need to delete all key:value pairs then we can use clear()


131

>>> stuDetails.clear() #deleting all pairs, then we can have an empty dict.

>>> print(stuDetails){}

Dictionary functions

1. keys():It returns all keys from dict.

E.g.:

>>> dic1={1: 'Python', 2: (3+5j), 3: (10, 20, 30), 4: [100, 'a', False], 's': 100}

>>> dic1.keys() / dict_keys([1, 2, 3, 4, 's'])

2. values():It returns all values from the dict.

E.g.:

>>> dic1={1: 'Python', 2: (3+5j), 3: (10, 20, 30), 4: [100, 'a', False], 's': 100}

>>> dic1.values() dict_values(['Python', (3+5j), (10, 20, 30), [100, 'a', False], 100])

3.copy():it copies the dict into new dict.

E.g.:

>>>dic1={1: 'Python', 2: (3+5j), 3: (10, 20, 30), 4: [100, 'a', False], 's': 100}

>>> dic2=dic1.copy()

>>> dic1 {1: 'Python', 2: (3+5j), 3: (10, 20, 30), 4: [100, 'a', False], 's': 100}

>>> dic2{1: 'Python', 2: (3+5j), 3: (10, 20, 30), 4: [100, 'a', False], 's': 100}

4.pop():It removes specific key value pair.

E.g.:

>>> dic1={1: 'Python', 2: (3+5j), 3: (10, 20, 30), 4: [100, 'a', False], 's': 100}

>>> dic1.pop(1) 'Python'


132

>>> print(dic1) {2: (3+5j), 3: (10, 20, 30), 4: [100, 'a', False], 's': 100}

Note: we can also remove the key: value pair by using 'del' command.

E.g.:

>>> del dic1[2]

>>> print(dic1){3: (10, 20, 30), 4: [100, 'a', False], 's': 100}

5. pop item():It will not allow any argument, but it will remove the last key value pair from
the existing dict.

E.g.:

>>> d={‘id:1’,‘Name’. ‘Teja’}

>>> d. popitem()

>>>(‘Name’, ‘Teja’)

>>> d

6.clear():It removes all key:value pairs from dict.

E.g.:

>>> tup=(1,2,3,4,5) #creating tuple

>>> dic1.fromkeys(tup)#taking tuple elements as keys in the dict.

dic1 {1: None, 2: None, 3: None, 4: None, 5: None}

By default, values are “None” if we need to get ‘0’ as default then,

>>> tup=(1,2,3,4,5)

>>> dic={}.fromkeys(tup,0)

>>> dic {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}

we can also use list elements as keys in the dict and the elements must be unique

>>> lst=[1,2,3,4,5]#creating list


>>> dic2.fromkeys(lst) #taking list elements as keys in the dict dic2 {1: None, 2: None,

3: None, 4 None, 5: None}

7.get():This function is used to get the value of specified key.


133

E.g.:

>>> stuDetails= {'Id': 100, 'Name': 'Sai', 'subjects': ['SQL Server', 'Oracle', 'Python'], 'id':
1000, 'name': 'nani'}

>>> stuDetails.get('Id') 100

>>> stuDetails.get('subjects') ['SQL Server', 'Oracle', 'Python']

8.Items():This function is used to get all items. All key and value pairs will be displayed in
tuple format.

E.g.:
>>> stuDetails= {'Id': 100, 'Name': 'Sai', 'subjects': ['SQL Server', 'Oracle', 'Python'], 'id':
1000, 'name': 'nani'}

>>> stuDetails.items() dict_items([('Id', 100), ('Name', 'Sai'), ('subjects', ['SQL Server',


'Oracle', 'Python']), ('id', 1000), ('name', 'nani')] )

9.Update():The current dictionary will be updated with the all key:value pairs from another
dictionary.

E.g.:

>>> stuDetails={'Id':100,'Name':'Sai', 'subjects':['SQL Server', 'Oracle', 'Python']}

>>> stuDetails1={'id':1000,'name':'nani'}

>>> stuDetails.update(stuDetails1)

>>> print(stuDetails)

{'Id': 100, 'Name': 'Sai', 'subjects': ['SQL Server', 'Oracle', 'Python'], 'id': 1000, 'name': 'nani'}

How to perform arithmetic operations on the values of a dictionary?

Ans. >>> d1={'sub1':80,'sub2':90,'sub3':70,'sub4':80}

>>> print(d1) {'sub1': 80, 'sub2': 90, 'sub3': 70, 'sub4': 80}

>>> s=sum(d1.values())
134

>>> print(s) 320

>>> mx=max(d1.values())

>>> print(mx) 90
>>> mn=min(d1.values())

>>> print(mn) 70
>>> cnt=len(d1.values())

>>> print(cnt)4

Difference b/w pop() and popitem()

Pop() Popitem()

 pop() function allows one argument  popitem() doesn’t allow any argument

 It will delete the key value pain based on  It will delete the last key value pair from
the given key . as an argument. existing dictionary.

All data types- mutable and immutable

class Description Mutable Immutable

Int Integer value 

Str Character string 

Float Floating-point number 

Bool Boolean value 


Complex Complex value

List Sequence of objects 

Set Orderedsetofuniqueobject  
Frozenset Immutable form set

Tuple
135

Dictionary Sequence of objects

Key:value pairs 

E.g.:

# create a mapping of state to abbreviation

states ={'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' }

# create a basic set of states and some cities in them

cities = { 'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville' }

# add some more cities

cities['NY'] = 'New York'

cities['OR'] = 'Portland'

# print out some cities

print( '- ' * 20)

print ("NY State has: ", cities['NY'])

print ("OR State has: ", cities['OR'])

# print some states print ('- ' * 20)

print ("Michigan's abbreviation is: ", states['Michigan'])

print ("Florida's abbreviation is: ", states['Florida'])

# do it by using the state then cities dict

print ('- ' * 20)

print ("Michigan has: ", cities[states['Michigan']])

print ("Florida has: ", cities[states['Florida']])

# print every state abbreviation

print ('- ' * 20)

for state, abbrev in states.items():


136

print ("%s has the city %s" % (abbrev, city))

# now do both at the same time

print ('- ' * 20)

for state, abbrev in states.items():

print ("%s state is abbreviated %s and has city %s" % ( state, abbrev, cities[abbrev]))

print ('- ' * 20)

# safely get an abbreviation by state that might not be there

state = states.get('Texas', None)

if not state:

print ("Sorry, no Texas.")

# get a city with a default value

city = cities.get('TX', 'Does Not Exist')

print ("The city for the state 'TX' is: %s" % city)

Output:

NY State has: New York

OR State has: Portland

……………………………………………………………..

Michigan's abbreviation is MI

Florida's abbreviation is FL

……………………………………………………………..

Michigan has: Detroit

Florida has: Jacksonville

…………………………………………………………………

Oregon is abbreviated OR
137

Florida is abbreviated FL

California is abbreviated CA

New York is abbreviated NY

Michigan is abbreviated MI

…………………………………………………………………………

CA has the city San Francisco

MI has the city Detroit

FL has the city Jacksonville

NY has the city New York

OR has the city Portland

…………………………………………………………………

Oregon state is abbreviated OR and has city Portland

Florida state is abbreviated FL and has city Jacksonville

California state is abbreviated CA and has city San Francisco

New York state is abbreviated NY and has city New York

Michigan state is abbreviated MI and has city Detroit

……………………………………………………………………………

Sorry, no Texas.

The city for the state 'TX' is: Does Not Exist

Setdefault():

d.setdefault(k,v)

If the key is already available then this function returns the corresponding value.

If the key is not available then the specified key_value will be added as new item to the
dictionary.

1. d= {100: “durga”, 200:“ram”, 300:“shiva”}


138

2. print(d.setdefault 400,“pavan”)
3. print(d)
4. print(d.setdefault100,“sachin”)
5. print(d)
6.
7. Output
8. Pavan
9. {100:“durga”,200:“ram”,300:‘‘shiva’’,400:‘‘pavan’’}
10. Durga
11. {100:“durga”,200:“ram”,300:‘‘shiva’’,400:‘‘pavan’’}

10. update():

d.update(x)

All item present in the dictionary x will be added to dictionary d.

Q. Write a program to take dictionary from the keyboard & print the sum of value?

1. d= eval(input (‘Enter dictionary’))


2. S= Sum(d.value())
3. Print(“sum=”,3)
4. .
5. Output
6. D:\python_classes> py test.py
7. Enter dictionary : {‘A’:100,‘B’:200,‘C’:300}
8. Sum=600

Q. Write a program to find number of occurrences of each letter present in the given string?

1. word = input(“Enter any word”)


2. d{}
3. for x in word
4. d[x]
5. for k, v in d.get (x,o)+1
6. print(k,“occured”, v,“times”)
7. .
8. Output
139

9. D:\python_classes> py test.py
10. Enter any word : missi ssippi
11. m occurred 1 time
12. i occurred 4 time
13. s occurred 4 time
14. p occurred 2 time

Q. Write a program to find number of occurrence of each vowel present in the given string?

1. word = input(“Enter any word”)


2. vowels={‘a’,‘e’,‘i’,‘o’,‘u’}
3. d{}
4. for x in word
5. if x is vowel
6. d[x]= d.get(x,o)+1
7. for k, v in d.get (x,o)+1
8. print(k,“occured”, v, “times”)
9.
10. Output
11. D:\python_classes> py test.py
12. Enter any word : dog animal dog animal
13. a occurred 4 time
14. i occurred 2 time
15. o occurred 2 time

Q. write a program to accept student name and marks from the keyboard and create a
dictionary. Also, display student marks by using taking student name as input?

1. n= int (input(“Enter the number of student”))


2. d {}
3. for i in range(n)
4. name = input(“Enter student name”)
5. marks= input(“Enter student marks”)
6. d[name]
7. while true
8. name=input(input(“Enter student name to get marks:”)
140

9. marks= d.get(name,-1)
10. if marks == -1
11. print(“student not found”)
12. else
13. print(“student not found”, name “are”, marks)
14. Option = input(“Do you want to find another student marks[Yes/No]”)
15. If option ==“No”
16. Break
17. Print(“Thanks for using application”)
18. .
19. Output
20. D:\ python_classes > py test.py
21. Enter the number of student: 5
22. Enter student name: Santosh
23. Enter student marks: 80
24. Enter student name: Dhan Lakshmi
25. Enter student marks: 80
26. Enter student name: Narayana
27. Enter student marks: 70
28. Enter student name: Pinny
29. Enter student marks: 60
30. Enter student name: Vinny
31. Enter student marks: 50
32. Enter student name to get marks: Narayana
33. The marks of Narayana are 70.
34. Do you want to find another student marks[Yes/No] No
35. Enter student name to get marks: since
36. Student not found
37. Do you want to find another student marks[Yes/No] No
38. thanks for using our application

Dictionary Comprehension:

Comprehension concept applicable for dictionaries also,


141

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


2. print(sequence)
3. double = {x:2 *x for x in range(1,6)}
4. print(double)
5. .
6. Output
7. {1:1, 2:4, 3 :9, 4:16, 5:25}
8. {1:1, 2:4, 3 :6, 4:8, 5:18}

Assignment- 2
 1. What are the different types of data structures in python?

A.

2. What is a string? What is the data type to represent string value?

A.

3. What is a List? What is the data type of list? Create one list?

A.

4. What is a Tuple? What is the data type? Create one tuple?

A.

5. What is a set? What is the data type? Create one set?

A.

6. What is dictionary? What is the data type of it? Create one dictionary?
142

A.

7. What is mutable and immutable? Explain each?

A.

8. Is string mutable or immutable? Why?

A.

9. What are the starting index numbers for both forward and backward indexing?
A.

10. What is indexing and slicing? Differences between both?

A.

11. What are the IndexError and TypeError errors?

A.

12. St = ’python developer’

a. Display as ‘Python developer’

b. Display as ‘Python Developer’


143

c. Count number of Es in that string.

d. Find index position of first ’o’ in the above string.

e. Find index position of second ‘o’ in the above string.

f. Spilt the same string into two elements like ‘python’,’developer’

g. Display string in reverse.

h. From the above string, display only ‘on dev’.

i.From above string remove ‘thon’

j.Copy the same string into other new strings like str1,str2 and str3 at a time

13. Generate a list [10,12,14,16,18,20] by using range function?

A.

14. lst=[10,20,'Python',10.5,1,10,True,False,0] what are the results of,

a. How to display the count of elements in the above list?

b. How to count no. of occurrences of ‘10’ in the above list?

c. What are the no. of occurrences ‘1’ in the above list?

d. How to add complex number 10+5j to the above list?

e. How to add both complex number 1+2j and float value 1.3 to the above list.
144

f. How to add bool value ‘True’ between 10 and 20 in the above list?

g. How to remove the str value ‘Python’ from the above list?

h. How to reverse the above list?

i.How to copy the above list lst to another list lst1?

j.Display index position of float value 10.5 in the above list?

k. Replace float value 10.5 with 20.5

15. What are the differences between append() and extend() in list?

A.

16. What is the ‘Del’ command? Explain with one example?

A.

17. How to convert a list to string? Give one example?

A.

18. How to convert a string to list? Give one example?

A.

19. How to convert tuple to list? Give one example?

A.
145

20. How to convert list to tuple? Give one example?

A.

21. How to convert tuple to string? Give one example?

A.

22. How to convert string to tuple? Give one example?

A.

23. What is tuple? Does tuple allow duplicate elements?

A.

24. Can we add new element to the existing set? How can we add?

A.

25. Can we add new elements to the frozenset? If no, give one example?

A.

26. Let’s take two sets

se1={1,2,3,4,5}

se2={1,2,3,6,7}
146

1. Perform union between se1 and se2, by using ‘I’ also

2. Perform intersection between se2 and se1, by using ‘&’ also

3. Perform difference between se2 and se1, by using ‘-’ also.

4. What intersectionupdate?and perform between se1 and se2 and vice versa.

5. What is difference_update?and perform between se1 and se2 and vice versa.

6. What is symmetric_difference? Perform between se1 and se2 and vice versa.

7. What is symmetric_difference_update? perform between se1 and se2 and vice versa.

27. Difference between remove() and discard()?

A.

28. Is frozenset mutable or immutable?

A.

29. What is the result of isdisjoint() if one set contains elements and otherset is empty?

A.

30. What is the difference between ‘=’ and ‘==’? explain with one example?

A.

31. How to check whether the specific element is existed or not in the given list? Example?
147

A.

32. >>> se1={11,12,13,14,15}

>>> se2={11,12,13,16,17} what is the result of

a. se1==se2?

b. se1!=se2

c. se1<= se2

d. se1<se2

e. se2>se1

f. se1.isdisjoint(se2)

33. In what cases isdisjoint method will be True? Give example?

A.

34.>>> s1={1,2,3}

>>> s2={1,2,3,4} what is the result of

a. s1=s2

b. s1<=s2

c. s1> s2
148

d. s1>=s2

e. s1.isdisjoint(s2)

f. s1.issubset(s2)

g. s1.issuperset(s2)

h. s2.issubset(s1)

i.s2.issuperset(s1)

j.s1!=s2

k. 4 not in s2?

l.1 in s2?

35. >>> s1{},

>>> s2{} what is the result of

a. s1=s2

b. s1<=s2

c. s1> s2

d. s1>=s2
149

e. s1>= s2

f. s1.isdisjoint(s2)

g. s1.issuperset(s2)

h. s1.issubset(s2)

i. s2.issuperset(s1)

36. >>> s1={True,False,10,20,3.5}

>>> s2={1,0} what is the result of

a. s2.issubset(s1)

b. s1.issubset(s2)

c. s1.isspuerset(s2)

d. s2.issuperset(s1)

e. s2>s1

f. s1=s2

g. s1>=s2

h. s2<=s1

i. s2=s1

37. Can we use duplicate keys in dictionaries?


150

A.

38. >>> set1={10,20,30,40,50}

>>> set2={10,20,30,60,70}

a. Display all distinct elements from both sets

b. Display only nonmatching elements from s1 set.

c. Display only non-matching elements from both sets

d. Store the common elements from both sets into set1

e. Remove matching elements from set1

f. Store non-matching elements from both sets into set2

g. How to take backup of set1 to new set set3?

39. Create one empty dictionary and add any 5 key:value pairs?

A.

40. Can we list and tuple as values in dictionary? If yes then create one dictionary with tuple
and list as values?

A.
151

41. stuDetails={'Id':100,'Name':'Sai', 'subjects':['SQL Server', 'Oracle', 'Python']}

a. modify the value of name as ‘Durga’

b. add new pair age:25

c. display all keys from the stuDetails dictionary?

d. Display all values from the stuDetails dictionary?

e. Display all subjects which are stored in the stuDetails dictionary?

f.Remove name key from the stuDetails?

g. Create new dictionary from the tuple element?

E.g.:tup=(1,2,3,4,5)

1.Store value ‘Sai’ for key 1

2.Store value ‘Mahesh’ for key 2

3.Store value True for key 3

4.Store value 3+6j for key 4

5.Store value 1000 for key 5

h. remove all pairs from the above dictionary

42. St=”python narayana” how to get the following from the above string

a. St[3::5]

b. St[1::1]

c. St[-1::-3]
152

d. St[2::-1]

e. St[1::15]

FAQ’s On Data structure


1. How display the given string in lower case?
2. What is the purpose of capitalize()
3. How to display the given string st="PYthon Dev" as "pyTHON dEV"?
4. Is string mutable or immutable object?
5. How to represent an empty string?
6. What is the output format of split function?
7. How to check whether the given string is in lower case or not?
8. How to find the index number of second occurrence 'o' in "oracle developer"?
9. Can we add a new string to the existing string?
10. What is a list and what is the data type of list?
11. How to add a new element to the existing list?
12. What is the insert()?
13. What is the difference between append() and extend()?
14. Can we delete a specific character of a string by using del ?
15. Can we remove all characters from a string by using clear()?
16. Is list mutable or immutable object?
17. How can we decide whether a specific data structure is mutable or immutable?
18. Can we add multiple elements to the existing list at required place?
19. What is the difference between remove() and pop()?
20. How to know the length of a list?
21. Is insertion order preserved or not in list?
22. What is the range() and what is required argument in the range()?
23. What are the different ways to create a list?
24. Can we give duplicate elements in list?
25. How to convert a list into string?
26. What is a tuple?
27. What is the difference between tuple and list?
28. How to create a tuple with one element?
29. Can we create a tuple without () and tuple()? if yes, then how?
153

30. Can we give duplicate elements in the tuple?


31. How to add a group of elements to the existing tuple?
32. Can we remove elementsfrom tuple?
33. What is the difference between del command and clear()?
34. Can we delete a specific element of a list by using del command?, if yes, then how?
35. Can we delete a specific element from the tuple by using del command? if yes, then
how?
36. What is any() and all()?
37. What is a set?
38. Is insertion order preserved or not in tuple?
39. Is insertion order preserved or not in set?
40. How to add a new element to the existing set?
41. Can we add duplicate element to the existing set?
42. Does a set allow duplicate elements?
43. What is issuperset() and issubset()?
44. What is the difference between remove() and discard()?
45. What is the main purpose of a set?
46. If a list contains duplicate elements then how to remove duplicate elements from the
list?
47. How to convert a list into set?
48. How to convert a set into string?
49. Can we concatenate two sets?
50. Can we multiply a set n number of time?
51. Can we use a list in set?
52. Can we concatename a string and a set?
53. How to display [10,30] from [1,3,10,5,7,30,5]?
54. How to reverse a string? example?
55. Can we use a set in tuple?
56. How to display a string in ascending order(a-z)?
57. How to display a string in descending order(z-a)?
58. How to remove apart of string?

ex: st='oracle dev' o/p:'oracle'

59. How to reverse a list without using reverse()?


154

60. What is the difference between list and set?


61. What is the main purpose of tuple? 62.
62. What is dictionary?
63. What is the main purpose of dict?
64. Can we add a new key:value pair to the existing dict? how?
65. How to access the value of a specific key from the dict?
66. How to remove a specific key:value pair from the dict?
67. How to update the existing value of a specific key in the dict?
68. How to display all keys from the dict?
69. How to get all values from the dictionary?
70. What are the different ways to create a dict?
71. How to create a dict by using an existing tuple?
72. How to update a dict by using another dict?
73. What is the copy()
74. What is the get () in dict?
75. If the two sets are empty then what is the result of issuperset() and issubset()?
76. If the two sets are having different elements then what is the output of issuperset()
and issubset()
77. What is the difference between intersection() and intersection_update()
78. How to create an empty set?
79. What are the different ways to create a string?
80. Is dict mutable or immutable?
81. Can we give a duplicate key in the dict?
82. What the replace()?
83. Can we delete a specific key:value pair by using del command?
84. Can we delete a specific element of a set by using del command?
85. What is the indexing and slicing?
86. Can we generate a heterogeneous list by using range()?
87. How to represent an empty set?
88. What is a list packing and list unpacking?
89. How to perform string packing?
90. Can we concatenate two dicts?
91. Is insertion order preserved or not in dict?
92. What is the difference between title() and capitalize()?
155

93. What is swapcase()?


94. What is the difference between pop() and popitem()
95. Can we create a new dict by using existing string?
96. When we create a new dict by using an existing obj, then what is the default value for
all keys?
97. What is the purpose of join()?
98. Can we count the number of occurrences of a specific element in the set?
99. What is the default delimiter in the split()?

100. Why set is not supporting indexing?

Operators
An operator is a symbol that tells the compiler to perform certain mathematical or logical
manipulations.

Operators are used in program to manipulate data and variables. Python language supports
the following types of operators.

1.Arithmetic Operators

2.Assignment Operators

3.Comparison (i.e., Relational) Operators

4.Logical Operators

5. Bitwise Operators

6.Membership Operators

7. Identity Operators

1. Arithmetic Operators:

Assume variable ‘a’ holds 4 and variable ‘b’ holds 2, then,

Operator Description Example

+Addition - Adds values on

either side of the operatora+b=6


156

-Subtraction - Subtracts right

hand operand from left hand operanda-b=2

*Multiplication - Multiplies values on

either side of the operatora*b=8

/Division - Divides left hand

operand by right hand operanda/b = 2

%Modulus -Divides left hand operand by

right handoperand and returns remaindera%b=0

**Exponent - Performs exponential

(power) calculation on operatorsa**b =(b to the power of a)16

//Floor Division - The division of 9//2 is equal to

operands where the result is 4 and 9.1//2.0 is

thequotient in which the digits equal to 4.0

afterthedecimal point are removed.

2.Assignment Operator:

Operator DescriptionExample

=Simple assignment operator,

Assigns values from right side

operands to left side operandc = a + b will assign value of a + b into c

+=Add AND assignment operator, It

adds right operand to the left operand


157

and assign the result to left operandc += a is equivalent to c = c +a

-=Subtract AND assignment operator, It

subtracts right operand from the left

operand and assign the result

to left operandc -=a is equivalent to c = c- a

*=Multiply AND assignment operator, It

multiplies right operand with the left

operand and assign the result

to left operandc *= a is equivalent to c = c *a

/=Divide AND assignment operator, It

divides left operand with

the right operand and assign

the result to leftoperandc /= a is equivalent to c = c /a

%=Modulus AND assignment operator, It

takes modulus using two

operands and assign the result

to left operandc %= a is equivalent to c = c %a

**=Exponent AND assignment operator,

Performs exponential (power) calculation

on operators and assign value

to the left operand c**=a is equivalent to c=c**a

/=Floor Division and assigns a value,

Performs floor division on operators

and assign value to the left operand c //= a is equivalent to c = c

E.g.
158

a = 20

b = 10

c=0

print('a value is',a)

print('b value is',b)

c += a

print ("Add AND - Value of c is ", c )

c *= a

print ("Multiply AND - Value of c is ", c )

c /= a

print ("Divide AND - Value of c is ", c )

c=2 c %= a

print ("Modulus AND - Value of c is ", c)

c **= a

print ("Exponent AND - Value of c is ", c)

c //= a

print ("Floor Division AND - Value of c is ", c)

c -= a

print ("Subtract AND - Value of c is ", c )

output:

a value is 20

b value is 10

Add AND - Value of c is 20

Multiply AND - Value of c is 400

Divide AND - Value of c is 20.0


159

Modulus AND - Value of c is 2

Exponent AND - Value of c is 1048576

Floor Division AND - Value of c is 52428

Subtract AND - Value of c is 5240

3. Comparison Operator:

Operator Description Example

==Checks if the value of two

operands are equal or not,

if yes then condition is true.(a == b) is not true

!= Checks if the value of two

operands are not equal ,

if values are not equal then

condition become true.(a != b) is true.

>Checks if the value of left

operand is greater than

the value of right operand, if

yes then condition becomes true.(a > b) is not true.

<Checks if the value of left

operand is less than

the value of right operand, if

yes then condition becomes true.(a > b) is true.

>=Checks if the value of left

operand is greater than or equal

to value of right operand, if


160

yes then condition becomes true.(a >= b) is not true.

<=Checks if the value of left

operand is less than

the value of right operand, if

yes then condition becomes true.(a <= b) is not true.

4.Logical Operator:

NOT

X NOT X
True False

False True

AND

XYX AND Y

TrueFalse

FalseTrueFalse

TrueTrueTrue

FalseFalseFalse

OR

XYX OR Y

TrueFalseTrue
161

FalseTrueTrue

TrueTrueTrue

FalseFalseFalse

E.g.:

>>> a=10

>>> b=20

>>> a==10 and b==20

>>> a==20 and b==10

>>> a==10 and b==10

>>> not a==20 and b==20

>>> not a==11 and not b==21

>>> a==20 or b==20

>>> not a==12 and not b==10

5. Bitwise Operator:

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60;

and b = 13; Now in binary format they will be as follows:

a = 0011 1100

b = 0000 1101

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011
162

there are following Bitwise operators supported by Python language

Operator DescriptionExample

&Binary AND Operator copies .(a & b) will give

a bit to the result if it 12 which is

exists in both operands. 0000 1100

| Binary OR Operator copies (a | b) will give

a bit if it exists in 61 which is

eather operand.0011 1101

^Binary XOR Operator copies (a ^ b) will give

the bit if it is set in one 49 which is

operand but not both.0011 0001

~Binary Ones Complement(~a ) will give -61 which is

operator is unary and has 1100 0011 in 2's complement

the effect of 'flipping' bits.form due to a signed binary no.

<<Binary Left Shift Operator. a<<2 will give 240

the left operands value is moved240 which is

leftby the number of bits specified 1111 0000

by the right operand.

>>Binary Right Shift Operator. a >> 2 will give

the left operands value is moved 15 which is

right by the number of bits specified 0000 1111


163

by the right operand.

6. Membership Operator:

In addition to the operators discussed previously, Python has membership operators,


which test for membership in a sequence, such as strings, lists, or tuples. There are two
membership operators,

Operator Description Example

InEvaluates to true if it x in y, here in

finds a variable in the results in a 1

specified sequence andif x is a member of

false otherwise.sequence y.

not inEvaluates to true if it x in y, here not in

does not find a variable results in a 1

in the specified sequence if x is a member of

and false otherwise.sequence y.

E.g.:

>>> lst=[1,2,3,4,’Python’,True]

>>> 4 in lstTrue
>>> 10 in lstFalse
>>> 3 not in lstFalse
>>> 20 not in lstTrue

7. Identity Operator:

Identity operators compare the memory locations or references of two objects. There
are two Identity operators explained below:

OperatorDescriptionExample
164

IsEvaluates to true if the x is y, here is

variables on either side of x is y, here is

the operator point to the id(x) equals to

same object and false otherwise.id(y).

is notEvaluates to false if the x is not y, here is

variables on either side of is not results in 1 if

the operator point to the id(x) is not equal to

same object and true otherwise.id(y).

E.g.,1:

>>> st="Sai"

>>> id(st)57264032

>>> st1="Sai"

>>> id(st1)57264032

>>> st is st1True
>>> st is not st1False

E.g.,2:

>>> lst=[1,2,3,4]

>>> id(lst)57297136

>>> lst1=[1,2,3,4]

>>> id(lst1)57240512

>>> lst is lst1False


>>> lst is not lst1True
165

Operators Precedence: -

The following table lists all operators from highest precedence to lowest.

OperatorDescription

**Exponentiation (raise to the power)

~+-complement, unary plus and

minus (method names for the

last two are +@ and -@)

* / % //Multiply, divide, modulo and floor division

+-Addition and subtraction

>><< Right & left bitwise shift

& Bitwise ‘AND’

 Bitwise exclusive ‘OR’ and regular ‘OR’

<=<>> =Comparison operators

<>== !=Equality operators


= %= /= //= -= += *= **=Assignment operators
is notIdentity operators
in not inMembership operators
not or andLogical operators

Exercise on operators:

1. True and True

2. False and True

3.1 == 1and 2 == 1
166

4. "test" == "test"

5. == 1 or 2 != 1

6. True and 1 == 1

7. False and 0 != 0

8.True or 1 == 1

9."test" == "testing"

10. 1 != 0 and 2 == 1

11. test" != "testing"

12. "test" == 1

13. not (True and False)

14. not (1 == 1 and 0 != 1)

15. not (10 == 1 or 1000 == 1000)

16. not (1 != 10 or 3 == 4)

17. not ("testing" == "testing" and "Zed" == "Cool Guy")

18. 1 == 1 and not ("testing" == 1 or 1 == 0)

19. "chunky" == "bacon" and not (3 == 4 or 3 == 3)

20.3 == 3 and not ("testing" == "testing" or "Python" == "Fun")

Some example of bitwise operator:


1. Bitwise AND
2.Bitwise OR

3. Bitwise XOR

4. Bit Left shift

5. Bit Right shift


167

E.g., of bitwise operator


168

Some examples on bitwise operators:

>>> a=20

>>> b=25

>>> c=15

>>> a & b16

>>> a & b & c 0

>>> a /b&c 29

>>> a&b /c31

>>>abc 2

>>> a&b<<2 4

>>>a &b/c<<2 60

>>> a/b/c<<2 61
169

>>> a &b/c>>2 19

>>>a/b/c>>2 31

Some examples on logical operator:

>>> a=100

>>> b=150

>>> c=200

>>> a==b and a<bFalse

>>> a!=c and b<c True

>>>a==b and a==c and a<bFalse

>>>a!=b and b>c or a=b False

>>> not a==b and a<b and a<c True

>>> not a=b or a==c False

>>> not a<b or a==c True

Conditional Statements
Conditional statements will decide the execution of a block of code based on the expression.
The conditional statements return either True or False.

Python supports four types of conditional statements,

1. Simple IF or IF statement

2. IF – ELSE Statement

3. IF ELSE IF (elif) Statement

4. Nested IF statement

IF Statement:

The Python if statement is same as it is with other programming languages. It executes a set
of statements conditionally, based on the value of a logical expression.
170

Here is the general form of a one way if statement

Syntax:

if expression :

statement_1

statement_2

.........................................

In the above syntax, expression specifies the conditions it produces either true or false. If the
expression evaluates true then the same amount of indented statement(s) following it will be
executed. This group of the statement(s) is called a block.

E.g.,1:

marks=int(input("Enter your percentage of marks to know pass or failed: "))

if marks>=35:

print("You are passed ...")

output: Enter your percentage of marks to know pass or failed: 45

You are passed ...

E.g.,2: compare values and display message

a=int(input("Enter First Value: "))

b=int(input("Enter Second Value: "))

c=int(input("Enter third Value: "))

if a>b <c)

print(“a is greater than b and also c”)

To text max value in two values

max= a if (a>b) elseb;

or

if a>b:
171

x=a

else:

x=b
E.g.,3: if name is more then or one character then do all string methods

name=input("Enter name: ")

if len(name)>0:

print "The length of name is: ", len(name)

print "The given name is: ",name

print "The capitalization of name is: ",name.capitalize()

print "The title of the name is: ",name.title()

print "The lower case form of given string: ",name.lower()

print "The upper case form of given string: ",name.upper()

print "The reverse of given string: ", ''.join(reversed(name))

print "The asc order of given string is: ", ''.join(sorted(name))

print "The desc order of given string is: ", ''.join(reversed(sorted(name)))

E.g.,4:

people = 20

cats = 30

dogs = 15

if people < cats:

print ("Too many cats! The world is doomed!")

if people > cats:

print ("Not many cats! The world is saved!")

if people < dogs:

print ("The world is drooled on!")


172

if people > dogs:

print ("The world is dry!")

dogs += 5

if people >= dogs:

print ("People are greater than or equal to dogs.")

if people <=dogs:

print("People are greater than or equal to dogs.")

if people ==dogs:

print("People are dogs")

Output:

Two many cats the world is dommed!

The world is dry!

People are greater than or equal to dogs.

People are less than or equal to dogs.

People are dogs.

If-else Statement:

In python if-else statement has two blocks, first block follows the expression and other
block, follows the else clause there is the syntax;

Syntax:-

If expression:

Statement 1

Statement 2

………………..

……………….
173

else:

Statement 3

Statement 4

In the above case, if the expression evaluate to true then the same amount of indented
statement follows the expression and if the expression evaluates to false the same amount of
indented statements follows else block,

E.g.,1:Write python script to check whether the given number is even or oddnumber.

a=int(input(‘Enter your number’:))

if a  2 ==0:

print (a, “is a even number”)

else:

print(a, “is a odd number”)

Output:

Enter your number:20

20 is even number

Or

Enter your number: 21

21 is odd number.

E.g.,2: write a python script to know passed or failed.

marks= int(input(“Enter your percentage of marks to know pass or failed”:))

if marks >= 35:

print(“you are passed”)

else:

print(“you are failed”)

Output:
174

Enter your percentage of marks to know pass or failed: 20

You are failed.

Enter your percentage of marks to know pass or failed: 40

You are passed.

E.g.,3: Check whether he entered proper name or not, if it is more than or equal to one
character then do all string operations else display “please enter valid name”.

name=input("Enter name: ")

if len(name)<=o

print(“please enter a valid name”)

else:

print(“The length of name is:”,len(name))

print(“The given name is:”, name)

print(“The capitalization of name is:”, name.capitalz:)

print(“The title of the name is:”, name.title())

print(“The lowercase form of given string:”, name.lower)

print(“The uppercase form of given string:”, name.upper())

print(“The reverse of given string:”,”join(reversed(name)))

print(“The asc order of given string is:”.” Join(sorted(name)))

print(“The desc order of given string is:”.“join(reversed(sorted(name))))

Output:-

Enter name: python dev

The length of name is: 10

The given name is: python dev

The capitalization of name is: Python dev

The title of the name is:Python Dev


175

The lowercase form of given string: python dev

The uppercase form of given string:PYTHON DEV

The reverse of given string:Ved nohtyp

The asc order of given string is: dehnoptvy

The desc order of given string is: yvtponhed

Output:-

Enter name:

Please enter a valid name.

E.g.,4: Enter two values and find out bigger value.

num1=int(input("Enter first number: "))

num2=int(input("Enter second number: "))

if num1> num2:

print(num1,'is greater than'num2)

else:

print(num1,'is smaller than ', num2)

Output :

Enter First Number: 10

Enter Second Number: 5

10 is greater than 5.

Enter first Number:5

Enter second Number:7

5 is smaller than 7

elif statement:
176

It will check the condition1 first, if the condition1 is true then it will execute the block of
statements which are following the condition, if the condition1 is false then it will check the
condition2.

If the condition2 is true then it will execute the block of statements which follow the
condition2, if the condition2 is false then it will check the conditio3, like this it will check all
conditions. If all conditions are false then it will execute the elseblock.

Syntax:

if condition1 :

statement_1

statement_2

elif condition2:

statement_3

statement_4

elif condition3:

statement_5

statement_6

.
.
.
.

else:

statement_7

E.g.,1: marks example

marks=int(input("Enter your percentage of marks : "))

if marks>=0 and marks<35:

print(“you are failed”)


177

elif marks>=35 and marks <50:

print(“you got 3rd class”)

elif marks>=50 and marks <60

print(“you got 2nd class”)

elif marks>=60 and marks <75

print(“you got 1st class”)

elif marks>=75 and marks <= 100

print(“you got distinction”)

else:

print(“invalid marks”)

Output:

Enter your percentage of marks : 50

You got 2nd class.

Enter your percentage of marks : 90

You got distinction.

Enter your percentage of marks : 20

You are failed.

E.g.,2: Food timing example

time=(input(“Enter your time”))

if time > 7 and time< 10:

print(“it’s time to have breakfast….”)

if time >=10 and time< 12:

print(“it’s time to have sninch….”)

elif time >=12 and time< 15:

print(“it’s time to have lunch….”)


178

elif time >=15 and time<18:

print(“it’s time to have snacks….”)

elif time >=18 and time<20:

print(“it’s time to have dinner….”)

elif time >=20 and time<=24:

print(“it’s sleeping time….”)

elif time >1 and time<=7:

print(“it’s sleeping time ….”)

else:

print(‘you entered invalid time’)

Output:

Enter your time : 8


It’s time to havebreakfast

Enter your time: 13


It’s time to have lunch

Enter your time: -2


You enter invalid time.

Enter your time: 3


It’s sleeping time.

E.g.,3: find bigger value of two given values.

a=int(input("Enter first value: "))

b=int(input("Enter second value: "))


179

if a>b:

print(a,'is greater than' b)

elif b>a:

print(b,'is greater than ', a)

else:

print(a,‘and’,b,‘are same values’)

Output1 :

Enter First Number: 10

Enter Second Number: 15

15 is greater than 10

Output2:

Enter First Value: 10

Enter Second Value: 10

10 and 10 are same values

Output3:

Enter First Value: 15

Enter Second Value: 10 

15 is greater than 10

E.g.,4: find biggest value of three given values.

a=int(input("Enter First Value: "))

b=int(input("Enter Second Value: "))

c=int(input("Enter third Value: "))

if a>b and a>c:

print(a,'is greater than ',b,'and',c)

elif b>c:
180

print(b,'is greater than ',a,'and',c)

else:

else: print(c,'is greater than ',a,'and',b)

Output 1:

Enter First Value: 10

Enter Second Value: 20

Enter third Value: 15

20 is greater than 10 and 15

Output 2:

Enter First Value: 10

Enter Second Value: 5

Enter third Value: 30

30 is greater than 10 and 5

Output 3:

Enter First Value: 10

Enter Second Value: 3

Enter third Value: 5

10 is greater than 3 and 5

Output 4:

Enter First Value: 10

Enter Second Value: 10

Enter third Value: 10

Three are same values

E.g.,5

people = 30
181

cars = 40

buses = 15

if cars > people:

print ("We should take the cars.")

elif cars < people:

print ("We should not take the cars.")

else:

print ("We can't decide.")

if buses > cars:

print ("That's too many buses.")

elif buses < cars:

print ("Maybe we could take the buses.")

else:

print ("We still can't decide.")

if people > buses:

print ("Alright, let's just take the buses.")

else:

print ("Fine, let's stay home then.")

output:

We should take the cars.

Maybe we could take the buses.

Alright, let's just take the buses.

E.g.,6
182

print ("You enter a dark room with two doors. Do you go through door #1 or

door #2?”)

door = input("> ")

if door == "1":

print ("There's a giant bear here eating a cheesecake. What do you do?")

print ("1. Take the cake.")

print ("2. Scream at the bear.")

bear = input("> ")

if bear == "1":

print ("The bear eats your face off. Good job!")

elif bear == "2":

print ("The bear eats your legs off. Good job!")

else:

print ("Well, doing %s is probably better. Bear runs away." % bear)

elif door == "2":

print ("You stare into the endless abyss at Cthulhu's retina.")

print ("1. Blueberries.")

print ("2. Yellow jacket clothespins.")

print ("3. Understanding revolvers yelling melodies.")

insanity = input("> ")

if insanity == "1" or insanity == "2":

print ("Your body survives powered by a mind of jello. Good job!")

else:

print ("The insanity rots your eyes into a pool of muck. Good job!")

else:
183

print ("You stumble around and fall on a knife and die. Good job!")

Output:

You enter a dark room with two doors. Do you go through door #1 or door #2?

>1

There's a giant bear here eating a cheesecake. What do you do?

1. Take the cake.

2. Scream at the bear.

>1

The bear eats your face off. Good job!

Nested if statement:

Python supports using if statements in anotherif statement.

If the upper if condition is true then the inner if will be evaluated, if the upper if is false then
it will not check the inner if statement.

Syntax:

If condition1:

If conditio2:

If condition31:

Statement1

Statement2

…….

Elif condition32:

Statement1

Statement2

…….

Else:
184

Statement1

Statement2

Elif condition21:

Statement1

Statement2

……..

Elif statement22:

Statement1

Statement2

……

Else:

Statement1

Statement2

Elif condition11:

Statement1

Statement2

Else:

Statement1

Statement2

E.g.,1:

Database contains only male records, if user enters about female then display ‘female records
are not available and if user enters about male then check employees name, if male employee
name existed then display his details, if that name is not available then display ‘nobody is
there with that name’. if he enters any wrong gender then display ’you entered wrong
gender’. Finally display ‘thank you’ at the end of result.

male records displaying


185

gender=input("Enter gender: ")

name= input("Enter name ")

if gender=="Female" or gender=="Male":

ifgender=='Female':

print("Female records are not available")

else:

if name=='Satya' and gender=="Male":

print("Satya is from Hyd and working as SE")

elif name=='Narayana' and gender=="Male":

print("Narayana is from Nagpur and working as ASE")

elif name=='Nani' and gender=="Male":

print("Nani is from Hyd and working as TL")

else:

print("Nobody is there with that name")

else:

print("You entered wrong gender: ")

print("Thank")

Output:

Enter gender: Male

Enter name Satya

Satya is from hyd and working as SE

Thank you.

Male records display example

gender=input("Enter your gender: ")

name=input("Enter your name: ")


186

if gender=="Male" or gender=="Female":

if gender!="Female":

if name=="Satya":

print("Satya is from Hyd and having 10 years exp")

elif name=="Sai":

print("Sai if from Mumbai and having 20 years exp")

elif name =="Narayana":

print("Narayana is having 6 years exp and from hyd")

else:

print("sorry, your name is not available in the database")

else:

print("Sorry Female records are not available in the database..")

else:

print("Sorry, You entered invalid gender" )

print("Thank You ......")

Output:

Enter your gender: Male1

Enter your name: Satya

Sorry, You entered Male1 , its invalid gender Please check once

Thank You ......

Enter your gender: Male

Enter your name: Sai

Sai if from Mumbai and having 20 years exp

Thank You ......


187

Enter your gender: Female

Enter your name: Renu

Sorry, Female records are not available in the database..

Thank You ......

E.g.,2:checking the eligibility of interview

name=input('Enter you name: ')

qual= input('Enter your qualification: ')

year=int(input('Enter passed out year: '))

per=eval(input('Enter your percentage: '))

qual=qual.lower()

name=name.capitalize()

if qual=='B.tech' or qual=='be':

if year==2016 or year==2017:

elif per>=0 and per<35:

print(‘Hello’, ‘name’, ‘don’t come to interview because you got’,‘per’,

‘percentage only’)

elif per>=35 and per<50:

print(‘Hello’, ‘name’, please come to interview with work exp’)

elif per>=50 and per<60:

print(‘Hello’, ‘name’, please come to interview after two month’)

elif per>=60 and per<75:

print(‘Hello’, ‘name’, please come to interview after tomorrow’)

elif per>=75 and per<100:

print(‘Hello’, ‘name’, please come to interview today because you


188

got, ‘per’, ‘percentage’)

else:

print(‘Hello’, ‘name’, ‘you entered’, ‘per’, ‘It invalid percentage ’)

elif year< 2016:

print(‘Hello’, ‘name’, ‘you entered’ ‘year’, ‘So, you are not fresher’)

else:

print(‘Hello’, ‘name’, ‘you entered’ ‘year’, ‘It’s invalid pass out year’)

else:

print(‘Hello’, ‘name’, ‘you entered’ ‘qual’, ‘So, you are not eligible’)

print(‘thank you for your interest in our company’)

Output1:

Enter your name: Nani

Enter your qualification: B.tech

Enter your pass out year: 2017

Enter your percentage: 88

Hello, Nani, please come to interview today because you got 88 percentage.

Thank you for your interest in our company.

Output2:

Enter your name: Nani

Enter your qualification: Degree

Enter your pass out year: 2016

Enter your percentage: 75

Hello, Nani, you entered degree So, you are not eligible’.

Thank you for your interest in our company.

Output3:
189

Enter your name: Krishna

Enter your qualification: B.E.

Enter your pass out year: 2018

Enter your percentage: 90

Hello, Krishna you entered 2018. it’s invalid passed out year.

Thank you for your interest in our company.

Output4:

Enter your name: Madhu

Enter your qualification: B.tech

Enter your pass out year: 2014

Enter your percentage: 77

Hello,you entered 2014, So, you are not fresher.

Thank you for your interest in our company.

Output5:

Enter your name: Venu

Enter your qualification: B.tech

Enter your pass out year: 2017

Enter your percentage: 10

Hello, Venu don’t come to interview because you got 10 percentage only.

Thank you for your interest in our company.

Iterative Statements

For Loop:

For loop allows a code block to be repeated a certain number of times.

E.g.,1:

St =“Python Developer”
190

For i in st:

Print(i)

Output:

E.g.,2: for loop on list object

Lst =[1,2, 3.5,“Python”, 4+5j, True]

For i in lst:

Print(i)

Output:

2
191

3.5

Python

(4+5j)

True

E.g.,3: for loop on tuple object

tup = (1,2,3, True, False,“Narayana”)

for i in tup

print(i)

Output:

True

False

Narayana

E.g.,4: for loop on set object

Se= {2,3,‘python’, 0,0,True, 2+6j, ‘Narayana’}

for i in se:

print(i)

Output:

Python

2
192

True

Narayana

(2+6j)

E.g.,5: for loop on dict. Object:

dic = {1:‘a’, 2:‘b’,3:‘c’}

for i in dic:

print(i)

Output:

E.g.,6: displaying 10th table by using range function

for i in range(1,11):

r= 10*i

print(‘10’, ‘*’,i,‘=’,r)

Output:

10*1= 10

10*2= 20

10*3= 30

10*4= 40

10*5= 50

10*6= 60

10*7= 70

10*8= 80
193

10*9= 90

10*10= 100

For loop with else:

A for loop can have an optional else block as well. The else part is executed if the item in the
sequence used in for loop exhausts.

Break statement can be used to stop a for loop. In such case, the else part is ignored. Hence,
for loops part runs if no break occurs .

Here, is an example to illustrate this.

E.g.:

Mylist =[“Narayana”, 100, “Python”, True]

for i in Mylist

Print(i)

else: # here else is optional, without else also possible.

Print(“specified”,len (Mylist); “itemover’’)

Output:

Narayana

100

Python

True

Specified 4 items over

While Loop:

In python programming language, a while loop statement repeatedly execute a target


statement as long as a given condition is true.

Syntax:

While expression:
194

Statement1

Statement2

Statement3

……………………

E.g.: Display first 5 numbers.

num=1

while( num<=5):

print(“the count is:”, num)

num+1

print(“Thank you”)

Output:

The count is: 1

The count is: 2

The count is: 3

The count is: 4

The count is: 5

E.g.: Display sequence of first 10 numbers.

Mynum=10

myvar = 0

while myVar < myNum:

print(‘square of+(myVar)’+‘is’+ (myVar**2)

myVar += 1

Output:

Square of0 is 0

Square of 1 is 1
195

Square of 2 is 4

Square of 3 is 9

Square of 4 is 16

Square of 5 is 25

Square of 6 is 36

Square of 7 is 49

Square of 8 is 64

Square of 9 is 81

Square of 1o is 100

E.g.: Display sum of all natural number of given number.

num=5

sum=0

i=1

while i<= num

sum= sum+i

i=i+1

print(“The sum is”, sum)

Output: the sum is 15

E.g.: Display all even number to before given number.

Target-Num=10

Var=1

While Var< Target_Num

if var%2!=0:

var+=1
196

continue

print(‘This number=’str(var))

var+=1

print(“Displayed all even number before”, var)

Output:

This number = 2

This number = 4

This number = 6

This number = 8

Displayed all even number before 10.

E.g.: Checking username and password.

While Tree:

Name = input(“Enter Name:”)

Pwd= input(“Enter Password”)

if pwd== ‘Durgasoft’:

print(“you entered correct details”)

print(“congratulations”, name)

break

print(“Thankyou”, name)

Output:

Enter Name: Narayana

Hello, Narayana please enter your password.

Enter Password: Durgasoft

You entered correct details.


197

Congratulations Narayana

Thank you Narayana

While loop with else:

We can have an optional ‘else’ block with while loop as well.

The else part is executed if the condition in the while loop evaluates too false. The while
loop can be terminated with a “break statement”.

In such case, the else part is ignored. Hence a while loops else part runs if no break occurs
and the condition is false.

int= 0

while int < 3

print(“Now we are in inside loop”)

int = int+1

else:

print(“Now we are in else block”)

Output:

Now we are in inside loop

Now we are in inside loop

Now we are in inside loop

Now we are in else block.

E.g.,1:

i=0

number =[ ]

while i<6:

print(“At the top i is %d” %i)

numbers. Append(i)
198

i=i+1

print(“Numbers now :”numbers)

print(“At the bottom i is %d” %i)

print(“The numbers:”)

for num in numbers:

print(num)

Output:

At the top i is 0

Number now: [0]

At the bottom i is 1

At the top i is 1

Number now : [0,1]

At the bottom i is 2

At the top i is 2

Number now : [0,1,2]

At the bottom i is 3

At the top i is 3

Number now : [0,1,2,3]

At the bottom i is 4

At the top i is 4

Number now : [0,1,2,3,4]


199

At the bottom i is 5

At the top i is 5

Number now : [0,1,2,3,4,5]

At the bottom i is 6

The number

Python Transfer Statements


1. break: -

We can use break statement inside loops to break loop execution based on some condition.

E.g.:

1. for i in range(10)

2. if i ==7

3. print(“processing is enough….plz. break”)

4. break

5. print(i)

6.

7. D:\ python_classes> py test.py

8. 0
200

9. 1

10. 2

11. 3

12. 4

13. 5

14. 6

15. processing is enough…. Plz break

E.g.:

1. cart=[ 10,20,600,60,70]

2. for itemin cart:

3. if i item> 500;

4. print(“To place this order insurance must be required”)

5. break

6. print(item)

7.

8. D:\python_classes> py test.py

9. 10

10. 20

11. To place this order insurance must be required.

2. Continue:-

We can use continue statement to skip current iteration and continue next iteration.

E.g.,1: To print odd numbers in the range 0 to 9.

1. for i in range(10):

2. if i % 2==0

3. continue
201

4. print(i)

5.

6. D:\python_classes>py test.py

7. 1

8. 3

9. 5

10. 7

11. 9

E.g.,2:

1. cart=[10,20,500,700,50,60 ]

2. for item in cart

3. if item> =500

4. print(“we cannot process this item:”, item)

5. continue

6. print(item)

7.

8. Output

9. D:\python_classes> py.test

10. 10

11. 20

12. we cannot process that item: 500

13. we cannot process that item: 700

14. 50

15. 60
202

E.g.,3:

1. numbers=[10, 20, 0, 5,0,30]

2. for n in numbers

3. if n==0

4. print(“Hey, how we can divide with xero….just skipping”)

5. continue

6. print(“100/{ }”format(n,100/n))

7.

8. Output

9.

10. 100/10=10.0

11. 100/20= 5.0

12. Hey, how we can divide with zero…. Just skipping.

13. 100/5=20

14. Hey, how we can divide with zero…. Just skipping.

15. 100/30 = 3.3333333333935

Loops with else block:

Inside loops execution, if break statement not executed, then only else part will be executed.

else means loop without break.

E.g.:

1. cart = [10,20,30,40,50]

2. for item in cart:

3. if item>= 500:

4. print(“We cannot process this order”)

5. break
203

6. print(item)

7. else:

8. print(“Congrats…. all items processed successfully.”)

9.

10.Output

11. 10

12. 20

13. 30

14. 40

15. 50

16. Congrats…. all items processed successfully.

E.g.:

1. cart = [10,20,30,40,50]

2. for item in cart:

3. if item>= 500:

4. print(“We cannot process this order”)

5. break

6. print(item)

7. else:

8. print(“Congrats…. all items processed successfully.”)

9.

10.Output

11. D:\ python_classes >py test.py

12. 10

13. 20
204

14. we cannot process this order.

Q. What is difference b/w for loop and while loop in python?

Ans. We can use loops to repeat code execution.

Repeat code in every item in sequence ==> for loop.

Repeat code as long as condition is true ==> while loop

Q. How to exit from the loop?

Ans. By using break statement.

Q. How to skip some iterations inside loop?

Ans. By using continue statement.

Q. When else part will be executed wrt loops?

Ans. It loop executed without break.

3. Pass Statement:

Pass is a keyword in python.

In our programming syntactically if block is required which won’t do anything then we can
define that empty block with pass keyword.

Pass

l- it is an empty statement

l- it is null statement

l- it won’t do anything.

E.g.:

if True:

SyntaxError: unexpected EoF while parsing

if True pass

==> valid
205

def mi()

syntaxError: unexpected EoF while parsing

def mi(): 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 keyword.

Python Functions
Functions are first class objects in python what it means that they can be treated as just like
any other variables and you can pass them as arguments to another function or return them as
return statement.

They are known in most programming languages, sometimes also called subroutines or
procedures.

Functions are used to utilize code in more than one place in a program. The only way
without functions to reuse code consists in copying the code.

A function in Python is defined by a def statement. The general syntax looks like this:

Syntax:

def function-name(Parameter list): # function defined statements, i.e. the function body

function-name(actual parameters list) #function call

E.g.:

1.Write a python function to add two numbers.

>>>defadd(x,y):

Return x+y

>>>add(10,20)30
206

2. Write a python function to find maximum value of two given values

>>> def max(x,y):

if x>y:

return x

else:

return(y)

>>> max(1,2) 2

>>>max(10,2)10

3. Write a python function to find max value of three values given values

>>>def max of three (x, y, z):

if x>y: and x>y:

return x

elif y>z:

return y

else

return z

>>> max of three(100, 3, 20) 100

>>> max of three(10, 3, 20) 20

>>> max of three(10, 20, 30) 30

Default arguments

Default parameters assume a default value if a value is not provided by the actual parameters
in the function call.

def display_message(times,message):

for i in range(times):

print(message)
207

display_message(4,'Python Narayana')

output:

Python Narayana

Python Narayana

Python Narayana

Python Narayana

So, we can set some default values to the formal parameters in the function definition. Those
are called default arguments. So, that if we don’t specify actual parameters in the function
call then interpreter takes formal parameters values and continue the operation.

def display_message(times=5,message="This is Python time"):

for i in range(times):

print(message)

display_message()

output:

This is Python time

This is Python time

This is Python time

This is Python time

This is Python time

In the above function we didn’t pass the actual parameters in the function call, so interpreter
has taken the default values and continued the operation.

If we pass the actual values when we have default values already in the function definition,
then interpreter takes actual values and continue the operation.

def display_message(times=5,message="This is Python time"):

for i in range(times):

print(message)
208

display_message(2,'Python Narayana')

output:

Python Narayana

Python Narayana

Generally, the first actual parameter will map to the first formal parameter and second actual
parameters will map to the second formal parameters and so on…

If we give those mappings in the reverse way then it will throw error like,

def display_message(times=5,message="This is Python time"):

for i in range(times):

print(message)

>>> display_message('Narayana',3)

Output:
TypeError: 'str' object cannot be interpreted as an integer.

Keyword argument:

 If we use any ‘Variable Name’ or formal arguments in function call for the purpose of
assigning actual arguments.

 Then those are called “keyword argument”.

Syntax:def fun_def(positional/formal args,keyword args):

function_call(actual args, keyword args)

def display (a, n, msg.) :

for i in range(n):

print(msg)

display (10, msg=‘py’, n=3)


209

Non keyword args keyword argument

If we don’t use any ‘Variable Name’ or formal arguments names in function call then there
are called “Non-keyword argument”.

def display_message(times=5,message="This is Python time"):

for i in range(times):

print(message)

displaymessage(message='Python Narayana',times=2)

Output:

Python Narayana

Python Narayana

 If the “lengths” of both actual args & format args is “same” and function_call has all
keyword args then it is known as “Fixed Length keyword argument”

def display (n,msg)

for i in range(n):

print(msg)

display (msg=‘py’, n=3)

 If the length’s of both format & actual args is same and any variable or formal argument
is not used in the function call then those are called ”Fixed Length non_keyword argument”

def display (n, msg.)

for i in range(n):

print(msg)

display (2, ‘py’)

 args and  keyword args:


210

 args – variable length non-keyword argument

 kwargs – variable

 args is used to handle the variable length args and with non-keyword args in the funcall.

Syntax:

def fun_name (non-default args, default args, variable length non keywords args):

def fun_name (non-default args, default args, args):

fun_call (actual_args)

Non

def display (b, a=10, c):

print (b, a, c) variable length non-keyword

Default

display (3, 4, 5, 6) actual args

O/p:3 4 (5,6)

Note: The output format of variable length non-keyword args. is ‘Tuple’.

def display (b, a=10, c)

print (a, b, c)

display (3, 2, 6)

O/p:3 2 (6,)

def display (b, a=10, c)

print (a, b, c)

display (3, 2 )
211

O/p:3 2 ()

def display (b, a=10, c)

print (a, b, c)

display ()

O/p:3 10 ()

 In the above example, the default argument ‘b’ is not required a formal argument from
the function call because it is assigned with ‘10’ as a default value.

 The variable length non_keyword args ‘c’ is also not required value because a variable
length means ‘O’ or more.

 kwargs: It is usedto handle variable length keyword args.

def fun_name(non-default args, variable length keywords or **args)

fun_call (actual args)


def display (a, b=10, **c):
print(a, b, c)
display(1, 5, x=10; z=20; z= ‘Santoshi’)

O/p:1 5 {10, 20, z: ‘Santoshi’}


def display (a, b=10,**c, **d):

print(a, b, c, d)

display (1, 5, y=10, 20, 30, m=‘py’,x=‘dev’)

O/p:1 5 (10, 20, 30) { m:‘py’,x:‘dev’}

def display (a, b=10, *c, **d):

print(a, b, c, d)

display(1)
212

Output:

1 10 () {}

display (2, 5)

2 5 () {}

display (2, 3, 10)

2 3 (10,) {}

Syntax of both *args and ** args:

def fun-def (non-default args, default args, *args, **kw args)

fun_ call (actual- args)

 The values are optional for default args, * args, ** kwargs.

def display (a, b=10*c, **d):

print(a, b, c, d)

display(1)

Output:

1 10 () {}

Scope of the variables:

All variables in a program may not be accessible at all locations in that program, they are
accessible depends on where you have declared the variables.

Python supports two types of variables,

1. Local variables

2. Global variables

Local variables:
213

Local variables are variables which are declared outside of a function.

Let’s an example with local and global variables scopes,

Here,loc_var is a local variable and glo_var is a global variable.

glo_var=0

def cal_product_of_two_values(num1,num2):

loc_var = num1*num2

print("The result of LOCAL Variable is: ",loc_var)

return loc_var

print("The result of GLOBAL Variable before calling the function is: ",glo_var)
glo_var=cal_product_of_two_values(3,5)

print("The result of GLOBAL Variable after calling the function is: ",glo_var)

Output:

The result of GLOBAL Variable before calling the function is: 0

The result of LOCAL Variable is: 15

The result of GLOBAL Variable after calling the function is: 15 

We can also use global variable in the functions like,

glo_var=0

def cal_product_of_two_values(num1,num2):

loc_var = num1*num2

print("The result of LOCAL Variable is: ",loc_var)

print("The result of GLOBAL Variable in the function is: ",glo_var)

return loc_var

print("The result of GLOBAL Variable before calling the function is: ",glo_var)
glo_var=cal_product_of_two_values(3,5)
214

print("The result of GLOBAL Variable after calling the function is: ",glo_var)

Output:

The result of GLOBAL Variable before calling the function is: 0

The result of LOCAL Variable is: 15

The result of GLOBAL Variable in the function is: 0

The result of GLOBAL Variable after calling the function is: 15

We can’t use local variable outside the function where it is declared, if we use the interpreter
will throw error,

glo_var=0

def cal_product_of_two_values(num1,num2):

loc_var = num1*num2

print("The result of LOCAL Variable is: ",loc_var)

return loc_var

print("The result of GLOBAL Variable before calling the function is: ", glo_var)
glo_var=cal_product_of_two_values(3,5)

print("The result of GLOBAL Variable after calling the function is: ",glo_var)

print("The result of LOCAL Variable after function call is: ",loc_var)

Output:

The result of GLOBAL Variable before calling the function is: 0

The result of LOCAL Variable is: 15

The result of GLOBAL Variable after calling the function is: 15


215

NameError: name 'loc_var' is not defined

Arguments packing & Unpacking

When we need to call a function definition with function call which having a ‘List’

With size 3. So, if we pass simply then it will not work.

def pack_Var ( arg1, arg2, arg 3)

print(arg1, arg2, arg3)

my_list = [100, 200, 300] # Creating list with size 3 element

pack_Var(my_list) # calling a func with my_list

Output:

TypeError: pack_var() missing 2 required positional arguments: 'arg2' and 'arg3'.

In this case we should use unpack the my_list.

This is called “argument unpacking”.

def pack_var(arg1,arg2,arg3):

print(arg1,arg2,arg3)

my_list=[100,200,300]

pack_var(*my_list)

Output:100 200 300

We can also pack the arguments, like, When we don’t know how many arguments need to be
passed to a python function, we can pack all arguments in a tuple. This is called “argument
packing”

def sum_of_args(*args):

sum=0

for i in range(0,len(args)):

sum=sum+args[i]
216

return sum

print(sum_of_args(2,20,30))

O/p:52

or

print(sum_of_args(20,20,30))

O/p:70

E.g.:

def cheese_and_crackers(cheese_count, boxes_of_crackers):

print ("You have %d cheeses!" % cheese_count)

print ("You have %d boxes of crackers!" % boxes_of_crackers)

print ("Man that's enough for a party!") print ("Get a blanket.\n")

print ("We can just give the function numbers directly:")

cheese_and_crackers(20, 30)

Output:

We can just give the function numbers directly: You have 20 cheeses!

You have 30 boxes of crackers!

Man that's enough for a party!

Get a blanket

Python Programs
1. Write a python function to check the given number is even or odd.

num= int(input(“Enter any value:”))

def even or odd(n)

if n/2=0

print(num, ‘is even number’)


217

else:

print(num,‘is odd number’)

Output:

Enter any value: 12

12 is even number.

Enter any value:13

13 is odd number.

2. Write Python function to check the given number is positive or negative?

num=int(input('Enter any value’))

def posorneg(n):

if n>=0:

print('num,'. is positive number')

else:

print('num,'. is negative number')

Output:

Enter any value: 8

8 is positive number.

Enter any value: -9

-9 is odd number.

3. Write a python function to check given number is divisible by 10 or not?

num=int(input('Enter any number:’))

def div by 10(n):

if n /10==0:

print('num,'. is divisible by 10')

else:
218

print('num,'. is not divisible by 10)

Output:

Enter any value: 12

12 is not divisible by 10.

Enter any value: 50

50 is divisible by 10.

4. Write a python function to display first n even numbers?

num=int(input('Enter any number: '))


lst.=[]

def nevennums(n):

for i in range(10000):

if len(lst)==n:

break

print(lst)

nevennums(num)

Output:

Enter anynumber: 10

[0,2, 4, 6, 8, 10, 12, 14, 16, 18]

Enter any number: 5

[0, 2, 4, 6, 8]

5. Write a python function to print even number upto ‘n’.

num=int(input('Enter any number: '))


def first nevennums(n):

for i in range(n+1):

if i/2==0:
219

first nevennums(num)

Output:

Enter any number: 10

10

Enter any number: 11

10

6. Write a python function to print sum of digits of number n.

num=int(input('Enter any number: '))


def Sum of digits (n):

S=0

for i in range(n+1):

S=S+i

Print(S)

Sum of digits(num)
220

Output:

Enter any number: 15

120

Enter any number: 4

10

7. Write a python function to print the largest number of three given values.

num1=int(input('Enter first value: '))

num2=int(input('Enter second value: '))

num3=int(input('Enter first value: '))

def largest number(a,b, c):

if a>b and a>c:

print(a,'is largest number of',b, and’ c)

elif b>c:

print(b,'is largest number of', a, and’ c )

else:

print( c,'is largest number of', a, and’ b)

Output:

Enter first number: 10

Enter second number: 11

Enter third number: 14

14 is thelargest number of 10 and 11

Enter first number: 6

Enter second number: 3

Enter third number: 2


221

6 is the largest number of 3 and 2

8. Write a python function to reverse the number or string.

st=(input('Enter any string or number: '))


def reversestring(s):

str1 = s[: :-1):

print(s+1)

reversestring(str)

Output:

Enter any string: Python Narayana

anayaraN nohtyP

Enter any string: 1234

4321

Or

st=(input('Enter any string or number: '))


def reversestring(s):

str1 = “. join( reversed(s))

print(s+1)

reversestring(str)

Output:

Enter any string or number : Django

oganjo

Enter any string: 7382

2837

#9. Write a python function to print the factors of given number.

num=int(input('Enter any value: '))


def factors(n):
222

for i in range(1,n+1):

if n/i==0:

print(i)

factors(num)

Output:

Enter any number: 10

10

Enter any number: 10

10

20

10. Write a python function to print factorial of given number.

num=int(input('Enter any number: '))


def factors(n):

S=1

for i in range(1,n+1):

S=S*i

print(s)

factorial(num)
223

O/p:

Enter any number: 5

120

Enter any number:3

11. Write a python function to swap two given numbers

num1=int(input('Enter first number: '))

num2=int(input('Enter second number: '))

def swap(x ,y):

temp=x

x=y

y=temp

print('first number is,’, after swapping is', x)

print('second number after swapping is', y)


swap(num1,num2)

O/p:

Enter first value: 13

Enter second value: 12

first number is 13, after swapping is 12

second number is 12, after swapping is 13

12. Write a python function to check the number is prime or not

num=int(input('Enter any number: '))


def prime & not(n):

for i in range(2,n):

if n/2==0:
224

print(num, ‘is not a prime’)

break

else:

print(num, ‘is prime’)

prime or not(sum)

Output:

Enter any number: 12

12 is not prime

Enter any number: 7

7 is prime

13. Write a python function to check the given no is palindrome or not.

n=int(input('Enter any number: '))


def palindrome or not(num):

if num==str(num)[ 6:: -1]:

print(num, ‘is palindrome number’)

else:

print(num, ‘is palindrome’)

palindrome or not(n)

Output:

Enter any number: 12321

12321 is palindrome.

Enter any number: 123432

123432 is palindrome.

14. Check given number is amstrong or not.


225

num=int(input('Enter any three digit number: '))


def armstrong or not(n):

S=0

While n>0:

digit= n/10

S+= digit**3

n//=10

if num == 3:

print(num, ‘is aarmstrong number’)

else:

print(num, ‘is not armstrong’)

armstrong or not(n)

Output:

Enter any number: 151

151 is not aromstrong number.

Enter any number: 153

153 is armstrong number.

15. Print Fibonacci series for below n number

num=int(input('Enter any number: '))


def fibonnacci(n):

t1= 0

t2=1

for i in range(1000):

temp= t1+t2
226

t1=t2

t2= temp

if t1>=n:

break

print(t1)

fibonacci(num)

Output:

Enter any number: 100

13

21

34

55

89

Enter any number: 10

5
227

16. Write a python function to print first 10 fibonacci series numbers.

num=int(input('Enter any number: '))


def fibonnacci(n):

t1= 0

t2=1

lst=[0]

temp=0

while temp< 1000:

temp=t1+t2

t1=t2

t2= temp

lst. append(H)

if len (lst)==n:

for i in range(1000):

print(i)

fibonacci(num)

Output:

Enter any number: 5

Enter any number: 7


228

17.Write a python function to print the given three values in asc and desc order .

a=eval(input(“Enter first value”))

b=eval(input(“Enter first value”))

c=eval(input(“Enter first value”))

def order of values(x,y,z)

if x>y and x>z:

if y>z:

print(‘The desc order is’, x, y, z)

print(‘The asc order is’, t, y, z)

else:

print(‘The desc order is’, y, z, x)

print(‘The asc order is’, x, z, y)

else:

print(‘The desc)

elif y>x and y>z:

if x>z:

print(‘The desc order is’, y, x, z)


229

print(‘The asc order is’, z, x, y)

else:

print(‘The desc order is’, y, z, x)

print(‘The asc order is’, x, t, y)

elif z>x and z>y:

if x>y:

print(‘The desc order is’, z, x, y)

print(‘The asc order is’, y, x, z)

else:

print(‘The desc order is’, z, y, x)

print(‘The asc order is’, x, y, z)

order of value(a, b, c)

Output:

Enter first value : 12

Enter second value : 11

Enter third value : 15

The desc order is 15 12 11

The asc order is 11 12 15

Enter first value :3

Enter second value : 2

Enter third value :1

The desc order is 3 2 1

The asc order is 1 2 3

18. Write a python program to check the marital status, gender, age.
230

marsta= input(“Enter marital status(married or single):”).lower()

gen= input(“Enter your gender(male or female):”).lower()

age= int(input(“Enter your age”))

if marsta == “Married”:

print(“you are not allowed to marry again”)

elif marsta == “single”:

if gen== “male”:

if age >= 21:

print(“congrats, you are eligible to marry”)

else:

print(“sorry, you are not eligible to marry”)

elif gen == “female”

if age>= 18:

print(“congrats, you are eligible to marry”)

else:

print(“sorry, you are not eligible to marry”)

else:

print(“you entered valid gender”)

else:

print(“you entered invalid marital status”)

Output:

Enter marital status(married or single): married

Enter your gender(male or female): male

Enter your age: 24

you are not allowed to marry again


231

Enter marital status(married or single): married

Enter your gender(male or female): female

Enter your age: 17

you are not allowed to marry again

Enter marital status(married or single): single

Enter your gender(male or female): male

Enter your age: 22

congrats, you are eligible to marry.

19. Write a python function to print nth table.

n=int(input("Enter any number: "))

def table display(n):

for i in range(1,11):

print(x,'*',i,'=',i*x)

table display(num)

Output:

Enter any value: 10

10 * 1 = 10

10 * 2 = 20

10 * 3 = 30

10 * 4 = 40

10 * 5 = 50

10 * 6 = 60
232

10 * 7 = 70

10 * 8 = 80

10 * 9 = 90

10 * 10 = 100

20. Write a python function to remove vowels from given string.

st = input(‘Enter any string’)

V = ‘aeiouAEIOU’

st = list(st)

for i in st:

if i in v:

st = st.replace(i,‘’)

st= ‘join (st)

print(st)

O/p:

Enter any string: Python Narayana

Python Narayana

Enter any string: Django framework

Ding framework

21. Write a python function to copy a given string into new variable and count how many
character one copied.

st = input(‘Enter any string’)

def copystring (st):

c =0

str1 = ‘ ’

for i in st:
233

str1+ =i

c= c+1

print(st1)

print(c)

copystring(st)

O/p:

Enter any string: Python Narayana

Python Narayana

22. Write a python function to count no. of digit in given no.

num=input('Enter any value’)

def countdigits(n):

n1 =len(n)

print(n)

countdigits(num)

Output:

Enter any value: 12345

Enter any value: 788

23. write a python function to print power value base on two given base and exponent value.

base = int(input(“Enter base value:”))

expo = int(input(“Enter exponent value:”))

def power (m, n)

x= base ** expo

print(x)
234

power(base expo)

O/p:

Enter base value: 3

Enter exponent value: 2

Enter basevalue: 4

Enter exponent value: 5

24. Write a python function to check weather user given string or number.

x=input('Enter either string or number: ')

def stronum(m):

if m.isalpha() == True:

print(x,'is a string value’)

elif m.isalnum() == True:

print(x,'is alpha numeric value)

else:

print( x,'is not a complete string ornumber or alpha_numeric value.’)

O/p:

Enter any string or number: python

Python is string value.

Enter any string or number: 1038

1038 is number value.

Enter any string or number: CS 1035

CS 1035 is alpha_numeric value.


235

Enter either string or number:sai@gmail.com

sai@gmail.com is not a complete string or number or alpha_numeric value.

25. Write a python function to check whether character is vowel or consonant.

char = input(‘Enter any character’)

def vowel or conso(ch)

Vowel = ‘aeiouAEIOU’

if ch in vowel:

print(char, ‘is a vowel ’)

else:

print(char, ‘is a consonant’)

vowel or conso(char)

O/p:

Enter any char: a

ais a vowel.

Enter any char: x

x is a consonant.

Enter any char: y

y is a consonant.

26. Write a python function to print following pattern.

****
****
236

****
****
n=4

def pattern1(n):

for i in rang(n):

for i in range(n):

for j in range(n)

print(‘*’, end=’ ’)

print(‘\n’)

pattern1(n)

27. Write a python function to print following pattern.

*
**
***
****
n=4

def pattern2(n):

for i in rang(n+1):

for i in range(n+1):

for j in range(i)

print(‘*’, end=’ ’)

print(‘\n’)

pattern2(n)

28. Write a python function to print following pattern.

*
**
***
237

****
*****
******
*******
n=5

def pattern3(n):

k =0

for i in rang(1, n+1):

for j in range(1,(n-i)+1):

Python Format Function

Some basics about formatting:

print("This is {} and working as {}".format('Narayana',"Python Developer"))

O/p: This is Narayana and working as Python Developer

print("This is {0} and working as {1}".format('Narayana',"Python Developer"))

O/p: This is Narayana and working as Python Developer

print("This is {1} and working as {0}".format('Narayana',"Python Developer"))

O/p: This is Python Developer and working as Narayana

print("This is {1} and working as {1}".format('Narayana',"Python Developer"))

O/p: This is Python Developer and working as Python Developer

print("We eat {} time per {}".format(3,"day")

O/p: We eat 3 time per day

Display squares and cubes for given numbers:

Traditional way:

for i in range(1,11):
238

print(i, " ",i*i," ",i*i*i)

Output:

111

248

3 9 27

4 16 64

5 25 125

6 36 216

7 49 343

8 64 512

9 81 729

10 100 1000

By using format function:

>>> for i in range(1,11):

print("{:1d} {:6d} {:6d}".format(i,i*i,i*i*i))

Output:

111

248

3 9 27

4 16 64

5 25 125

6 36 216
239

7 49 343

8 64 512

9 81 729

10 100 1000

Format function with dictionary:

persons={'name':'Sai', "Age":28}

#Traditional way of using keys in the sentence

print( "My name is " +persons['name']+ " and i am "+str(persons['Age'])+" years old")
print( "My name is " persons['name'], " and i am ",str(persons['Age']), " years old")

#by using format function also we can use value with corresponding keys in the sentence
print("My name is {} and i am {} years old".format(persons['name'],persons['Age']))
print("My name is {0} and i am {1} years old".format(persons['name'],persons['Age']))
print("My name is {0[name]} and i am {1[Age]} years old".format(persons,persons))
print("My name is {0[name]} and i am {0[Age]} years old".format(persons))

Output:

My name is Sai and i am 28 years old

My name is Sai and i am 28 years old

My name is Sai and i am 28 years old

My name is Sai and i am 28 years old

My name is Sai and i am 28 years old

My name is Sai and i am 28 years old

Format function with list:

lst=["Narayana","Python",3]

print("My Name is {0[0]} and i have been giving training on {0[1]} for {0[2]}

years ".format(lst))
240

Output:

My Name is Narayana and i have been giving training on Python for 3 years.

Adding formatting to the place holder

for i in range(1,5):

msg="The current value is {:02} ".format(i)

print(msg)

Output:

The current value is 01

The current value is 02

The current value is 03

The current value is 04

Format function with tuple:

lst=("Sai","Python",2)

print("My Name is {0[0]} and i have been giving training on {0[1]} for {0[2]}

years ".format(lst))

O/p: My Name is Sai and i have been giving training on Python for 2 years

Format dates#about dates we will discuss in modules concept

E.g.,1:

import datetime

my_date = datetime.datetime(2017,10,16,23,20,44)

sentence="{:%B %d, %Y}".format(my_date) print(sentence)

O/p: October 16, 2017


241

E.g.,2:

import datetime

my_date = datetime.datetime(2017,10,16,23,20,44)

print("{0:%B %d, %Y} fell on {0:%A} and {0:%w}

day of this week and {0:%d} day of this month and {0:%j} day of

the year".format(my_date))

Output:

October 16, 2017, fell on Monday and 1 day of this week and 16 day of this month

and 289 day of the year

Some other examples

Eg1:

age = input("How old are you? ")

height = input("How tall are you? ")

weight = input("How much do you weigh? ")

print ("So, you're {} years old, {} feet tall and {} kgs weight.".format(age,

height, weight))

Output:

How old are you? 27

How tall are you? 5.9

How much do you weigh? 75

So, you're 27 years old, 5.9 feet tall and 75 kgs weight.

Eg2:

def add(a, b):

print ("ADDING {} + {}".format(a, b))


242

return a + b

def subtract(a, b):

print ("SUBTRACTING {} - {}".format (a, b))

return a - b

def multiply(a, b):

print ("MULTIPLYING {} * {}".format (a, b))

return a * b

def divide(a, b):

print ("DIVIDING {} / {}".format(a, b))

return a / b

print ("Let's do some math with just functions!") age = add(30, 5) height = subtract

(78, 4) weight = multiply(90, 2) iq = divide(100, 2) print ("Age: {}, Height: {},

Weight: {}, IQ: {}".format (age, height, weight, iq))

Output:

Let's do some math with just functions!

ADDING 30 + 5

SUBTRACTING 78 - 4

MULTIPLYING 90 * 2

DIVIDING 100 / 2

Age: 35, Height: 74, Weight: 180, IQ: 50.0

Lambda Function
1. lambda function is a small anonymous functions, i.e. functions without name.
243

2. These functions are throw-away functions, i.e. they are just needed where they have been
created.

3. We use a lambda function when we require a nameless function for short time.

General syntax of a lambda function is quite simple:

lambda argument_list: expression

The argument list consists of a comma separated list of arguments and the expression is an
arithmetic expression using these arguments.

E.g.:

a= lambda x,y: x if x>y else y

print(a(20,5))

20

In the above script lambda x,y: x if x>y else y is lambda function whereas x,y are the
arguments and x if x>y else y is expression.

The above function has no name, and it returns a function object which is assigned to a
identifier ‘a’.

Generally we use def keyword to create a function definition but in this case we “don’t use
def keyword” instead we use “lambda keyword”.

We can use either def or lambda methods to create a function.


Q.Write a function to add two numbers?

By using def

def add_nums(x,y): return x+y

print(add_nums(1,2))3

by using Lambda

a=lambda x,y:x+y

print(a(1,2)) 3

Q.Write a function to find maximum value of given two numbers.


244

def max_nums(x,y):

if x>y:

return x

else:

return y

O/p:print(max_nums(20,5))20

By using lambda

a= lambda x,y: x if x>y else y

O/p:print(a(20,5))20

Q.Write a function to calculate square for given number.

By using def

def square_val(x):

return x*x

O/p:print(square_val(10))100

By using lambda

a = lambda x: x*x

O/p:print(a(10))100

Lambda functions are mainly used in combination with the functions filter(), map() and
reduce().

Filter():

Filter function mainly takes two arguments, first one is a function and second one is list of
arguments.

r=filter (func,seq)
245

This function calls all the items from the existing sequence and a new sequence is returned
which contains the elements that are evaluated to True.

Q. Write a function to return only odd numbers from the existing list which contains values
from 1 to 20?

lst=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

odd_nums = list(filter(lambda x: (x%2==1),lst))

print(odd_nums)

O/p:

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Q. Write a python code to separate positive values from the given list which contains both
positive and negative numbers.

lst=range(-10,10)

print(lst) [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

a= list((filter(lambda x:x>0,lst)))

print(a)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Q. Write a python script to get intersection elements from both lists?

a=[1,2,3,4,5,6]

b=[4,10,11,1]

lst=list(filter(lambda x:x in a,b))

print(lst)[4, 1]

Map():

The map function contains two arguments like,

r=map (func,seq)
246

The first argument func is the name of a function and the second a sequence (e.g. a list) seq.
map() applies the function func to all the elements of the sequence seq. It returns a new list
with the elements changed by func.

E.g.:
Write a function to add elements from different sets

a = [1,2,3,4],

b = [17,12,11,10]

c = [-1,-4,5,9]

list(map(lambda x,y:x+y, a,b)) [18, 14, 14, 14]

list(map(lambda x,y,z:x+y+z, a,b,c))[17, 10, 19, 23]

E.g.

Write a python script to find squares for all elements in the given list.

a=[2,4,5,6]

a=map(lambda x:x*x,a)

print(a) [4, 16, 25, 36]

Since it's a built-in, map is always available and always works the same way.

from operator import add

a=[1,2,3,4]

b=(1,2,3,4)

x=map(add,a,b)

print(x)[2, 4, 6, 8]

If function is None, the identity function is assumed; if there are multiple arguments,
map()returns a list consisting of tuples containing the corresponding items from all iterables
(a kind of transpose operation).

m = [1,2,3]

n = [1,4,9]
247

new_tuple = map(None, m, n)

print(new_tuple)

O/p:[(1, 1), (2, 4), (3, 9)]

We can still use lambda as a function and list of functions as sequence, like

def square_values(x):

return (x**2)

def cube_values(x):

return (x**3)

funcs = [square_values, cube_values]

for r in range(5):

value = map(lambda x: x(r), funcs)

print value

Output:

[0, 0]

[1, 1]

[4, 8]

[9, 27]

[16, 64]

Reduce()

Reduce function contains two arguments like,

x=reduce(func,seq)

The function continually applies the function func() to the sequence seq. It returns a single
value.

Syntax:

If seq = [ s1, s2, s3, ... , sn ], calling reduce(func, seq)


248

works like this:

Initially the first two elements of seq will be applied to func, i.e. func(s 1,s2) The list on
which reduce() works looks now like this: [ func(s1, s2), s3, ... , sn ]

In the next step func will be applied on the previous result and the thirdelement of the list,
i.e.

func(func(s1, s2),s3)

The list looks like this now: [ func(func(s1, s2),s3), ... , sn ]

Continue like thisuntiljust one element is left and return this element as the result of
reduce()

Q. Write a function to find maximum number from given list by using lambda.

a=[1,2,3,4]

d=reduce(lambda x,y:x if x>y else y,a)

print(d) 4

Q. Write a python script to add all the elements in the given list.

a= reduce(lambda x,y:x+y,[10,11,12,13,14,15])

print(a)

Q. Write a python script to add all even numbers before 100.

a= reduce(lambda x,y: x+y, range(0,101,2))

print(a)2550

Object Oriented Procedure/Programming


1. Introduction to OOP

2. Class and Object

3. Accessing Variables and Methods from class

4. Self-keyword
249

5. Docstring

6. Class or static variables

7. Constructor

8. Instance or non-static variables

9. Data hiding

10. Data abstraction

11. Encapsulation

12. Tightly encapsulation

13. Inheritance

a. Single level inheritance

b. Multi-level inheritance

c. Hierarchical inheritance

d. Multiple inheritance

14. Polymorphism

a. Method overloading

b. Method Overriding

Introduction:

In all the programs, we have designed our programaround functions i.e. blocks of statements
which manipulate the data. This is called the “procedure-oriented” way of programming.
There is another way of organizing your program which is to combine data and functionality
and wrap it inside something called an object. This is called the “objectoriented
programming” paradigm. Classes and objects are the two main aspects of object oriented
programming. A class creates a new type where objects are instances of the class.

Classes and Objects:

1. Object is simply a collection of data (variables) and methods (functions).


250

2. Objects are an encapsulation of variables and functions into a single entity.

3. Objects get their variables and functions from classes.

4. Classes are essentially a template to create your objects.

5. Class is a blueprint for the object

6. A class is the blueprint from which theindividual objects are created. Class is composed of
three things:

a name, attributes, and operations.

Class data members and member functions or

data and functions or

data and member or

variables and functions or

variable and method or

states and behaviours.

E.g.,1:

If we think of class as a sketch(Phototype) of a house. It contains all the details about the
floors, doors, windows etc. Based on these descriptions we build the house. House is the
object.

We can make many houses from the description. So, we can create many objects from a
class. An object is also called an “instance of a class” and the process of creating this object
is called “instantiation”.

E.g.,2:

In an apartment, we may have multiple houses are there and almost all are having same
structure. we define a class by using class keyword.

Accessing Variable

class ClsName:

VarName = "Python"
251

def function(self):

print("Python is very simple and easy language")

ObjName=ClsName()

print(ObjName.VarName)

Output:Python

We can create multiple different objects with the same class(which is having variables and
functions). Each object contains its own copy of the variables

class ClsName:

VarName = "Python"

def function(self):

print("Python is very simple and easy language")

ObjNameA=ClsName()

ObjNameB=ClsName()

ObjNameB.VarName="Developer"

print(ObjNameA.VarName)

print(ObjNameB.VarName)

Output:

Python

Developer

Accessing Function:

We can also access the function to the object separately like a variable,

class ClsName:

VarName = "Python"
252

def function(self):

print("Python is very simple and powerful language")

ObjName=ClsName()

ObjName.function()

print(ClsName.__doc__)

Output:

Python is very simple and powerful language.

Self :

Class methods have only one specific difference from ordinary functions - they must
have an extra first name that has to be added to the beginning of the parameter list, but you
do not give a value for this parameter when you call the method, Python will provide it. This
particular variable refers to the object itself, and by convention, it is given the name “self”.

Although, you can give any name for this parameter, it is strongly recommended that you
use the name self - any other name is definitely frowned upon. There are many advantages to
using a standard name - any reader of your program will immediately recognize it and even
specialized IDEs (Integrated Development Environments) can help you if you use self.

Note for C++/Java/C# Programmers

The self in Python is equivalent to the “this” pointer in C++ and the “this” reference in Java
and C#.

You must be wondering how Python gives the value for self and why you don't need to
give a value for it.

An example will make this clear. Say you have a class called ‘MyClass’ and an instance of
this class called “myobject”.
253

When you call a method of this object as myobject.method(arg1, arg2), this is


automatically converted by Python into MyClass.method(myobject, arg1, arg2) - this is all
the special self is about.

This also means that if you have a method which takes no arguments, then you still have
to have one argument - the self.

Docstring:

The first string is called docstring and it has brief description about the class.

Docstring is not mandatory, but it is recommended.

When we define a class then class creates a local namespace where all its attributes are
defined, attributes are may be data or functions.

There are special attributes also in it that begins with double underscore (__), for example
__doc__ which displays the docstring in that class. Let’s see some examples on class and
objects,

class ClsName:

"This ClsName class contains VarName and fucntion attributes"

VarName = "Python"

def function(self):

print("Python is very simple and easy language")

In the above example, just one class is created with one variable and one function.

class ClsName:

"This ClsName class contains VarName and fucntion attributes"

VarName = "Python"
def function(self):

print("Python is very simple and easy language")

ObjName=ClsName()
254

Now the object ObjName holds the object of class ClsName which contains the variable and
function that are defined in ClsName class.

Now we can access variables and functions separately.

Static variables or class variables

1. The variables which are declared inside the class and outside all the methods are known as
class variables or static variables.

2. Class or static variables are shared by all objects.

3. The data which common for all the objects is recommended to represent as static variable
or class variable.

4. Memory will be allocated only once for all class or static variables.

5. We can also modify the values of static or class variables

6. We can access the static or class variables within the class or outside the class also by
using class name. 

E.g.:

class Myclass:

i="Python"#static or class variable

j="Dev"##static or class variable


def DisMethod(self):

print(Myclass.i) #accessing static variables with class name

print(Myclass.j)

x1=Myclass()

print(x1.i) #accessing static variables outside the class

print(x1.j) x1.DisMethod()#it works like DisMethod(x1)

Output:

Python
255

Dev

Python

Dev

In C++ and Java, we can use static keyword to make a variable as class variable. The
variables which don’t have preceding static keyword are instance variables.

Python doesn’t require a static keyword. All variables which are declared in class
declaration are class variables or static variables. And variables which are declared
insideclass methods are instance variables or non-static variables.

Constructor:

1. Constructor is a special function which we call automatically when we create object for
respective class.

2. It can be defined by using __ini__() in python

3. It will not return anything

4. It is mainly used for initializing the variable __init__ is a kind of constructor, when an
instance of a class is created,

python calls __init__() during the instantiation to define additional behaviour that should
occur when a class is instantiated, basically setting up some beginning values for that object
or running a routine required on instantiation.

init is an abbreviation for initialization.

Non-static variables or instance variables:

1. The variables which are declared inside the method and with the ‘self’ keyword is known
as instance variable or non-static variable.

2. Instance variables are owned by the specific instances of a class. This means the instance
or non-static variables are different for different objects (every object has a copy of it).

3.Instance variables are always introduced with the word self. They are typically introduced
and initialized in a constructor method named __init__.
256

4. We can define instance variables in a constructor or in a method.

5. The data which is separate for every object is recommended to represent as a instance
variable or non-static variable.

6. Memory will be allocated for all instance variables whenever we create an object.

7. Instance variables of a class can be accessed within the same class by using ‘self’
keyword. And same variables also can be accessed outside the class by using reference
variable name.

E.g., 1:

class employee:

loc="Hyderabad"#class variable
def __init__(self,Empno,Ename,Sal):

self.Empno=Empno#instance variable
self.Ename=Ename#instance variable
self.Sal=Sal#instance variable

def display(self):

print("Emp number is ",self.Empno)

print("Emp name is ",self.Ename)

print("Emp Salary is ",self.Sal)

print ("Emp Location is ",employee.loc)

emp1=employee(101,"Sai",10000)

emp1.display()

emp2=employee(102,"Nani",20000)

emp2.display()

emp3=employee(103,"Renu",30000)

emp3.display()

Output:
257

Emp number is 101

Emp name is Sai

Emp Salary is 10000

Emp Location is Hyderabad

Emp number is 102

Emp name is Nani

Emp Salary is 20000

Emp Location is Hyderabad

Emp number is 103

Emp name is Renu

Emp Salary is 30000

Emp Location is Hyderabad

E.g.,2:

class Myclass:

def method1(self):

self.i="Python"

def display(self):

print(self.i)

Obj1= Myclass ()

Obj1.method1() #returns Python

Obj1.display()
Obj1.i="It is very easy"
258

Obj1.display()#returns It is very easy

Obj2= Myclass ()

Obj2.method1() #returns Python

Obj2.display()

Obj2.i="it is very powerful"

Obj2.display()#returns it is very powerful


Obj1.display()#returns It is very easy
Obj2.display()#returns it is very powerfulNarayana

Output:

Python

It is very easy

Python

It is very powerful

It is very easy

It is very powerful

Data hiding:

Outside person can’t access our internal data directly or our internal data should not go
out directly this OOP feature is nothing but data hiding. After validation or authentication
only, outside person can access our internal data.

E.g.,1:after providing proper username and password we can be able to access our gmail
inbox information.

E.g.,2:even though we are valid customer of the bank, we can be able to access our account
information and we cannot access others account information By declaring data member
(variable) as private (__) only we can achieve data hiding.
259

E.g.:

class accout:

__a=100

def getBal():

#validation return __balance

The biggest advantage of data hiding is security.

It is highly recommended to declare a data member as private (with underscore)

Data abstraction:

Hiding internal information and just highlight the set of services what we are offering is
the concept of abstraction.

Through bank ATM GUI screen, bank people are highlighting the set of services what
they are offering without highlighting internal implementation, like the server they used to
work, the database they used to the customer details, the language they used to implement
communication between application and database.

1. Outside person doesn’t know how it is implemented internally, so “security” is provided.

2. For example a bank ATM GUI is developed by python now, and python program
execution speed is not up to mark, so the new language is there ‘Sython’, now we can change
internal implementation from python to ‘sython’ without effecting the GUI display and end-
user. We can do any modifications to internal implementation without effecting to end-user.
That’s why enhancement became very easy.

3. For example we need to know how the ATM card is implemented and everything about
ATM card before use, then nobody can use ATM cards. Because it’s not possible to know
everything. That’s why without knowing anything about internal implementation we are
using ATM cards, and also WhatsApp. So here its improving easiness to end-user.

4. So we are able to do any internal implementation changes without effecting end user so
here maintainability of application becomes very easy.
260

Encapsulation:

1. The process of binding the data members and corresponding methods into a single unit is
called encapsulation.

2. Every python class is example of encapsulation.

3. Class student has data members plus data methods is encapsulation.

4. Encapsulation is nothing but the “combination of data hiding and data abstraction”.

5. If any component follows data hiding and data abstraction then that component is called
“encapsulated component”.

6. Encapsulation is about ensuring the safe storage of data as attributes in an instance.

7. Encapsulation tells us that :

a. Data should only be accessed through instance methods.

b. Data should always be correct based on the validation requirement set in the

class methods.

c. And Data should be safe from changes by external processes.

Encapsulation = data hiding + abstraction.

E.g.:

capsule with medicine inside

class account: __balance=100000

def getBal():

# validation

print(__balance)

def setBal(self,balance):

#validation

self.balance=balance
261

Let’s take bank ATM GUI screen and imagine there are only two button are there, like
BalanaceEnquiry and UpdateBalance.

The above class contains data members which are declared as private for hiding from the
others and also class contains methods like getBal() and setBal().

When the end-user clicks on Balance Enquiry button then automatically it will call

getBal() method, and when user clicks on UpdateBalance button then automatically it will
call setBal() method.

The complete and confidential data is hidden inside the class and just abstraction is given
in the GUI. So finally the above class contains data members and methods.

The main advantages of encapsulation are

1. We can achieve security

2. Enhancement will become very easy

3. It improves maintainability of application.

The main advantage of encapsulation is security, but the main disadvantage of


encapsulation is it increases length of the code and slows down execution.

A class is said to be tightly encapsulated if and only if each and every variable declared as
private.

Whether class contains corresponding getter or setter methods or not and whether these
methods are declared as public or not these things we are not required to check.

class classA:

__a=10

__x=100

class classB(classA):

b=20

class classC(classA):

__c=30
262

Here, classA and classC are tightly encapsulated classes because each and every variable
under these two classes are private so nobody can access from outside, but everyone can
access variable under classB.

If parent class is not tightly encapsulated then automatically all corresponding its child
classes are not tightly encapsulated

class classA:

a=10

x=100

class classB(classA):

__b=20

__y=40

class classC(classA):

__c=30

__z=50

Here, even though classB and classC are having all private variables but these two classes
are the child classes of classA which is not tightly encapsulated class.

Here, all non-private variables from classA can be accessed from classB and classC that’s
why classB and classC are not tightly encapsulated classes.

Inheritance

Classes can be derived from other classes. The derived class (the class that is derived from
another class) is called a subclass.

The class from which it's derived is called the superclass. The following figure illustrates
these two types of classes:

A class
Superclass
263

Subclass Another class

The subclass inherits state and behaviour in the form of variables and methods from its
superclass. The subclass can use just the items inherited from its superclass as is, or the
subclass can modify or override it. So, as you drop down in the hierarchy, the classes become
more and more specialized:

We use inheritance for code reusability.

1. Single level inheritance

2. Multi-level inheritance

3. Multiple inheritance

4. Hierarchical inheritance

1. Single level inheritance:

The process of inheriting all attributes from one class to the other class is known

as single level inheritance.

Class A

Class B

E.g.:

class A:a1=100
def methodA1(self):

print('This is methodA1 belongs to class A')

def methodA2(self):
264

print('This is methodA2 belongs to class A')

class B(A):

b1=200

def methodB1(self):

print('This is methodB1 belongs to class B')

def methodB2(self):

print('This is methodB2 belongs to class B')

ObjB=B()

print(ObjB.b1)

ObjB.methodB1()

ObjB.methodB2()
print(ObjB.a1)

ObjB.methodA1()

ObjB.methodA2()

Output:

200

This is methodB1 belongs to class B

This is methodB2 belongs to class B

100

This is methodA1 belongs to class A

This is methodA2 belongs to class A

2. Multi-Level inheritance:

The process of inheriting all attributes from one base class, again from this derived class to
another derived class & so on.
265

Class A

Class B

Class C

E.g.

class A:

a1=100

def methodA1(self):
print('This is methodA1 belongs to class A')
def methodA2(self):

print('This is methodA2 belongs to class A')

class B(A):

b1=200

def methodB1(self):

print('This is methodB1 belongs to class B')


def methodB2(self):

print('This is methodB2 belongs to class B')

class C(B):

c1=300

def methodC1(self):

print('This is methodC1 belongs to class C')

def methodC2(self):

print('This is methodC2 belongs to class C')


266

class D(C):

d1=400

def methodD1(self):

print('This is methodD1 belongs to class D')

def methodD2(self):

print('This is methodD2 belongs to class D')


ObjD=D()
print(ObjD.d1)

ObjD.methodD1()

ObjD.methodD2()

print(ObjD.c1)

ObjD.methodC1()

ObjD.methodC2()
print(ObjD.b1)

ObjD.methodB1()

ObjD.methodB2()

print(ObjD.a1)

ObjD.methodA1()

ObjD.methodA2()

Output:

400

This is methodD1 belongs to class D

This is methodD2 belongs to class D

300

This is methodC1 belongs to class C

This is methodC2 belongs to class C


267

200

This is methodB1 belongs to class B

This is methodB2 belongs to class B

100

This is methodA1 belongs to class A

This is methodA2 belongs to class A

3. Hierarchical inheritance:

The process of inheriting all attributes from one base class into multiple derived classes is
called hierarchical inheritance.

Class A

Class B Class C Class D

class A:

a1=100

def methodA1(self):

print('This is methodA1 belongs to class A')

def methodA2(self):

print('This is methodA2 belongs to class A')

class B(A):

b1=200

def methodB1(self):
268

print('This is methodB1 belongs to class B')

def methodB2(self):

print('This is methodB2 belongs to class B')

class C(A):

c1=300

def methodC1(self):

print('This is methodC1 belongs to class C')

def methodC2(self):

print('This is methodC2 belongs to class C')

class D(A):

d1=400

def methodD1(self):

print('This is methodD1 belongs to class D')

def methodD2(self)

print('This is methodD2 belongs to class D')

ObjD=D()

print(ObjD.d1)

ObjD.methodD1()

ObjD.methodD2()

print(ObjD.a1)

ObjD.methodA1()

ObjD.methodA2()

ObjC=C()

print(ObjC.c1)

ObjC.methodC1()
269

ObjC.methodC2()

print(ObjC.a1)

ObjC.methodA1()

ObjC.methodA2()

ObjB=B()

print(ObjB.b1)

ObjB.methodB1()

ObjB.methodB2()

print(ObjB.a1)
ObjB.methodA1()

ObjB.methodA2()

Output:

400

This is methodD1 belongs to class D

This is methodD2 belongs to class D

100

This is methodA1 belongs to class A

This is methodA2 belongs to class A

300

This is methodC1 belongs to class C

This is methodC2belongs to class C

100

This is methodA1 belongs to class A

This is methodA2 belongs to class A

200
270

This is methodB1 belongsto class B

This is methodB2 belongs to class B

100

This is methodA1 belongs to class A

This is methodA2 belongs to class A

4. Multiple inheritance:

The process of inheriting all attributes from multiple base classes into single derived class
this process is known as multiple inheritance.

Class A Class B Class C

Class D

E.g.:
class A:

a1=100

def methodA1(self):

print('This is methodA1 belongs to class A')

def methodA2(self):

print('This is methodA2 belongs to class A')

class B:

b1=200

def methodB1(self):
271

print('This is methodB1 belongs to class B')

def methodB2(self):

print('This is methodB2 belongs to class B')

class C:

c1=300

def methodC1(self):

print('This is methodC1 belongs to class C')

def methodC2(self):

print('This is methodC2 belongs to class C')

class D(C,B,A):

d1=400

def methodD1(self):

print('This is methodD1 belongsto class D')

def methodD2(self):

print('This is methodD2 belongs to class D')

ObjD=D()

print(ObjD.d1)

ObjD.methodD1()

ObjD.methodD2()

print(ObjD.c1)

ObjD.methodC1()

ObjD.methodC2()

print(ObjD.b1)

ObjD.methodB1()

ObjD.methodB2()
272

print(ObjD.a1)

ObjD.methodA1()

ObjD.methodA2()

Output:

400

This is methodD1 belongs to class D

This is methodD2 belongs to class D

300

This is methodC1 belongs to class C

This is methodC2 belongs to class C

200

This is methodB1 belongs to class B

This is methodB2 belongs to class B

100

This is methodA1 belongs to class A

This is methodA2 belongs to class A

Polymorphism

This is also a “built in” python example of polymorphism.

The same operation results in different behaviours depending on the type of data is given.
The same idea(same operation- different behaviour) can be applied to our own class and
objects.

Polymorphism is the ability to leverage the same interface for different underlying forms
such as data types or classes. This permits functions to use entities of different types at
different times.
273

For object-oriented programming in Python, this means that a particular object belonging
to a particular class can be used in the same way as if it were a different object belonging to a
different class.

Polymorphism allows for flexibility and loose coupling so that code can beextended and
easily maintained over time.

Generally, polymorphism supports method overlading and method overriding butpython


will not supportmethodoverloading.
Method overloading

The concept of defining multiple methods with same name but different number of
parameters is called method overloading.

class classA:

def method1(self):

print('this method belongs to class classA')

class classB:

def method1(self,a):

print('this method belongs to class classB')

ObjB=classB()

ObjB.method1(10)

ObjB.method1()#it will return error so overloading will not support

Output:
This method belongs to class classB

Method overriding:

The concept of defining multiple methods with the same name with the same number of
parameters is called method overriding.

E.g.:

class classA:
274

def method1(self):

print('this method belongs to class classA')

class classB:

def method1(self):

print('this method belongs to class classB')

ObjB=classB()

ObjB.method1()

Output:

This method belongs to class classB

Real time example for Method overloading:

class BankAccount:

def __init__(self,balance=10000):

self.balance=balance

def deposite(self,value):

self.balance=self.balance+value

print('The current balance is: ',self.balance)

def withdraw(self,value):

self.balance=self.balance-value

print('The current balance is: ',self.balance)


class SavingsAccount(BankAccount):

def __init__(self,balance=10000):

self.balance=balance

self.balance=self.balance+(value*1.03)

print('The current balance in savings account is: ',self.balance)


class CurrentAccount(BankAccount):
275

def __init__(self,balance=10000):

self.balance=balance

def withdraw(self,value):

if value>1000:

print('You can withdraw lessthan 1000 only')

else:

self.balance=self.balance-value

print('You current amount in current account is', self.balance)


SA=SavingsAccount()

CA=CurrentAccount()

while True:

print('1.Savings Account')

print("2.Current Account")

MOption=int(input('Please select the account type: '))

if MOption==1:

print('1.Withdraw')

print('2.Deposite')

SOption=int(input('Please select any operation type: '))

if SOption==1:

value=int(input('Please enter amount to withdraw from savings account: '))

SA.withdraw(value)

elif SOption==2:

value=int(input('Please enter amount to deposite in savings account: '))

SA.deposite(value)

else:
276

print('You entered ',SOption,'Its invalid operatoion')

elif MOption==2:

print('1.Withdraw')

print('2.Deposite')

SOption=int(input('Please select any operation type: '))

if SOption==1:

value=int(input('Please enter amount to withdraw from current account: '))

CA.withdraw(value)

elif SOption==2:

value=int(input('Please enter amount to deposit in current account: '))

CA.deposite(value)

else:
print('You entered ',SOption,'Its invalid operation')

else:

print('You entered ',MOption,'Its invalid Account Type')

break#this example is done without break statement

Output1:

1.Savings Account

2.Current Account Please select the account type: 1

1.Withdraw

2.Deposite

Please select any operation type: 1

Please enter amount to withdraw from savings account: 2000


277

The current balance is: 8000

Output2:

1.Savings Account

2.Current Account

Please select the account type: 1

1.Withdraw

2.Deposite

Please select any operation type: 2

Please enter amount to deposit in savings account: 3000

The current balance in savings account is: 11090.0

Output3:

1.Savings Account

2.Current Account

Please select the account type: 2


1.Withdraw

2.Deposite

Please select any operation type: 1

Please enter amount to withdraw from current account: 1500

You can withdraw lessthan 1000 only

Output4:

1.Savings Account

2.Current Account

Please select the account type: 2

1.Withdraw
278

2.Deposite Please select any operation type: 1

Please enter amount to withdraw from current account: 500

You current amount in current account is 9500

Output5:

1.Savings Account

2.Current Account

Please select the account type: 2

1.Withdraw

2.Deposite

Please select any operation type: 2

Please enter amount to deposite in current account: 2000

The current balance is: 11500

Reading and writing files:

Variables are a fine way to store data while your program is running, but if you want your
data to persist even after your program has finished, you need to save it to a file.

A file has two key properties: a filename (usually written as one word) and a path. The path
specifies the location of a file on the computer.

There is a file on my windows 10 laptop with the filename empdata.txtin the path.

'C:\Users\Narayana\AppData\Local\Programs\Python\Python36-32'.

These all refer to folders or directories. Folders can contain files and other folders.

For e.g., empdata.docxis in the python 36-32 folder, which is inside the python folder,
which is inside the Program folder, which is inside the Local folder, which is inside the
AppData folder. which is inside the Narayana folder, Which is inside the Users,Which is
inside the C drive.

C:\ is called root folder which contains all other folders.


279

Working with slashes (\ or /):

On Windows, paths are written using backslashes (\) as the separator between folder names.
OS X and Linux, however, use the forward slash (/) as their path separator.

If we want our programs to work on all operating systems, we will have to write our
Python scripts to handle both cases.

 Fortunately, this is simple to do with the os.path.join()function.

If we pass it the string values of individual file and folder names in our path,
os.path.join()will return a string with a file path using the correct path separators.

>>> import os

>>> os.path.join('a','b','c') 'a\\b\\c

'>>> os.path.join('Users','Narayana','AppData','Local','Programs','Python','Python36-32')

'Users\\Narayana\\AppData\\Local\\Programs\\Python\\Python36-32'

The os.path.join() function is helpful if we need to create strings for filenames.

For e.g., the following example joins names from a list of filenames to the end of a folder’s
name:

>>> files=["empdetails.txt",'custdata.docx','productsdata.csv','salesdetails.txt']

>>>fornamein files:

print(os.path.join("C:\\Users\\Narayana\\AppData\\Local\\Programs\\Python\\Python36-
32",name))

The Current Working Directory:

Every program that runs on our computer has a current working directory or cwd. Any
filenames or paths that do not begin with the root folder are assumed to be under the current
working directory. We can get the current working directory as a string value with the
os.getcwd()function and change it with os.chdir().

>>> os.getcwd()
280

'C:\\Users\\Narayana\\AppData\\Local\\Programs\\Python\\Python36-32'

>>> os.chdir("E:\FilesFolder")

>>> os.getcwd()

'E:\\Files Folder'

Absolute vs. Relative Paths:

There are two ways to specify a file path.

• An absolute path, which always begins with the root folder

• A relative path, which is relative to the program’s current working directory.

There are also the dot (.) and dot-dot (..) folders. These are not real folders but special names
that can be used in a path. A single period (“dot”) for a folder name is shorthand for “this
directory.” Two periods (“dot-dot”) means “the parent folder.”

Relative Paths Absolute Paths

…\ C:\

.\ C:\ bacon

..\fizz C:\bacon\fizz

.\fizz\spam.txt C:\bacon\fizz\spam.txt

..\Eggs C:\eggs

..\eggs\spam.txt C:\eggs\spam.txt

….\spam.txt C:\spam.txt

File Sizes and Folder Contents:

Once we have ways of handling file paths, we can then start gathering information about
specific files and folders. The os.path module provides functions for finding the size of a file
in bytes and the files and folders inside a given folder.

• Calling os.path.getsize(path) will return the size in bytes of the file in the path argument.
281

• Calling os.listdir(path) will return a list of filename strings for each file in the

path argument. (Note that this function is in the os module, not os.path.)

>>>os.path.getsize('C:\\Users\\Narayana\\AppData\\Local\\Programs\\Python\\Python36-32\\
empdata.txt')

94
Here, empdata.txt file size is 94bytes.

>>>os.listdir("C:\\Users\\Narayana\\AppData\\Local\\Programs\\Python\\Python36-32")

['all functions.py', 'bankexample.py', 'browser.py', 'comp.py', 'compre.py', 'data.pdf',


'Decorator Example.py','details.docx', 'details1.docx','empdata.txt', 'multithreading.py',
'mydata.pdf', 'myfile.py', 'ourdata.csv','python3.dll', 'snakegame.py', 'tcl', 'test.py', 'testing.py',
'testing12.py', 'Tools', 'unittst1.py', 'urdata.docx', 'userexp.py', 'ut.py', 'ut1.py',
'vcruntime140.dll', 'webpage.py', 'while.py', 'zipp.py', '__pycache__']

Here, it is displaying all files which are in python 36-32 folder.

If we want to find the total size of all the files in this directory, then we can use
os.path.getsize()and os.listdir()together.

* File Handling *
282
283
284
285
286
287
288
289

You might also like