Python - Clouds It Guru
Python - Clouds It Guru
Python - Clouds It Guru
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
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:
programming languages are run by compiler. That’s why these all languages are
Note: Most of the people call Python is a scripting language because the way of
scripting languages.
Featured Of Python
a. The syntax of is very simple and easy to remember so anybody can easily remember
b. Even non-technical persons also can learn or work with python language. So here
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
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
g. Python has few keywords, simple structure, and a clearly defined syntax. This allows
a. Python language is more expressive. The sense of expressive is the code is easily
understable.
1. Linux
2. Ubuntu
3. LibreOffice
4. Mozilla Firefox
5. Mono
7. VLC Player
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
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.
a. The Python is very rich in libraries. They help us to do various things involving regular
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. The program is built around procedures or functions which are nothing but
c. The program is built around objects which combine data and functionality. Python is
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,
9. High-level Language:
a. When you write programs in Python, you never need to bother about the low-level details
1. Interactive Language
6
2. Beginners Language
3. Easy – to – learn
4. Easy – to – maintain
5. Easy to – work
8. Scalable
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
PATH=C:\Users\Narayana\AppData\Local\Programs\Python\Python36-32\Scripts\,
C:\Users\Narayana\AppData\Local\Programs\Python\Python36-32\.
1. GUI Applications
3. Gaming Applications
4. Scripting Applications
5. Task Applications
6. Network Applications
7. Animation Applications
Simply python can be used to make games, do data analysis, control robot, hardware, create
Advantages:
Scripting language
Scripting language
Interface to Other programming languages. – Can include code from C, Java, .Net
Used by Lot many MNCs and worlds topmost organizations like Google, NASA,
Huge library.
Disadvantages:
It has wide range of applications from web development, scientific and mathematical
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
Python programming is very fun; it is very to understand and write the python code.
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
2. Not overlystrict:-
You don’t need to define the type of variable in python. Also, it’s not necessary to
Python enforces you to follow good practice these small things can make learning
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
Pythonhas a large supporting community. These are numerous active forums online
a. Learn Python
b. Google Forum
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
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 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
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).
interpreter.
1. Interactive Mode
2. Script Mode
1. Interactive mode:- command line shell, we type Python programs, and the
>>> 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
In script mode, we write python program in a file and use the interpreter to execute
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…
E.g.:
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)
open the file FirstProgram.py, click on run tab and then run module or press F5. Now we
Python Identifiers
13
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
>>> _total=10
>>> to_tal=20
>>> total_=30
>>> _to_tal_=40
>>> __total='Python'
>>> total__='Narayana'
>>> to__tal='Nani'
>>> ___to__tal_=100
14
be in a list or tuple
>>> a=100
>>> A=200
>>> var='python'
Keywords
The keywords in python are having some predefined functionality. These keywords may
>>> 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',
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
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:
Else:
17
However, the second block in this e.g.,will generate or error because first print in the else part
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:
else:
print (hello’)
print (b)
print (bye…’)
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.
item = two+
item = three
Statement contained within the [ ],{},() brackets do not need use the line continuation
character.
For e.g.:
Quotations in python
Pythonaccepts single(‘), double (“) and triple (“or’”) quotes to denote sharing literals,
Generally, triple quotes are used to write the string across, triple quotes are used to
For Example,
Word = ‘word’
sentences“”””,
Comments in Python
Comments are use in programming to describe the purpose of the code. This helps
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
# First comment
print “Hello, python!”, second comment “This will produce following result:”
Hello, python!
Name = “palatal” # declaring variable name you can comment multiple lines
as follows.
# Python is easy.
Python supports so many functions. Some of those are print(), type(), id()
20
Type (): - This function checks the data types of specific variable.
Python- Variable
Variables are nothing but reserved memory locations to store values. This means that
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.
We can assign single value to single variable or multiple variables at a time. And
also, we can assign single value to multiple variables.
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
>>>{d (m) }
>>> n = 20.4
>>> r = ‘Narayana’
>>> x=y=z= 10
>>> print(x)
>>>print(y)
>>>print(z)
E.g.
My_name= ‘Simran’
My_height= # 74 inches
My_weight = 75 # kg
My_eyes = ‘Blue’
My_teeth = ‘white’
My_hair= ‘black’
Output:-
E.g.:2 :--
Cars = 100
Space_in_a_car =4.0
Drivers = 100
Passengers = 90
Car_not_driver = cars_drivers
Car_driver = drivers
Average_passengers_per_car = passenger/car_driver
Output :-
E.g., 3 :-
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
#Watch that comma at the end try removing it to see what happen.
Output :-
…………..
Cheese
Burger.
E.g., 4 :-
Output :-
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.
\\ backslash(\)
\’ single quote(‘)
\” double quote(“)
\aASCII bell(BTL)
\bASCII backspace(BS)
>>> x=10
>>> y= 20
>>> print(sum)
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
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.
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.
>>> print(n) 10
>>> print(n) 10
>>> print(n) 10
>>> print(“““Hello ””” + Name +, How are you How your + loc.””)
Open file and write the following code & save the file.
→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: -
‘10’
‘100’
‘10’
‘10’ ““ 10””
In python 3: -
>>> x
‘10’
‘Enter any value= 10’ # entered data is treated as string with or without
>>> x
“ “10” ”
File “” , line 1, in
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
E.g. : -
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
E.g.: -
x = input(‘‘Enter value’’)
10 ===> int
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.
Q. Write a program to read 2 numbers from the keyboard & print sum.
Output: -
………..…….…………………………………..
……………………………………………….
32
Q. Write a program to read employee data from the keyboard and print that data.
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
E.g.: -
x= eval(“10=20=30”)
O/p: -60
E.g.: -
x= eval(input(“Enter expression”))
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)
E.g.: -
D:\python_classes pytest.py 10 20 30
Within the python program this command line argument are available
test.py 10 20 30
line argument.
Import argv
Print(type(argv))
D:\python_classes\ py_test.py
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
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.: -
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.: -
6. 10 20
7. 30
Note 3: -If we are buying to access command line arguments with out-of-range index
E.g.:-
Note 4: -In python there are argument module to phase command line argument &
E.g.: -
Input()
Raw_input()
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
E.g.: -
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. Print(“Hello”)
2. Print(“Python”)
3. Print(“Narayana”)
O/p :-
1. Hello
2. Python
3. Narayana
1. Print(“Hello”, end‘’)
2. Print(“Python”)
3. Print(“Narayana”)
Note: -The default values for end attribute is \n, which is nothing but new line character.
39
We can pass any object(like, list ,tuple, set etc) as argument to the print () statement.
E.g. : -
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: -
%c===> int
%d ===> float
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: -
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.
1. Int
2. FloatData Types
3. Complex
4. Bool
If we assign integer value to any variable then interpreter decides that variable as int type
variable,
E.g.:
>>> a=10.
>>> print(a) 10
>>> id(a)1625909520
If we assign float value to any variable then interpreter decides that variable as Float Type
variable.
E.g.:
>>> b=10.5
>>> id(b)47460096
If we assign string value to any variable then interpreter decides that variable as String type
variable.
42
E.g.:
>>> c='Narayana'
>>> id(c)52367056
If we assign either True or False to any variable then interpreter decides that variable as Bool
type variable.
E.g.:
>>> d=True
>>> id(d)1625727600
If we assign complex number to any variable then interpreter makes that variable as
Complex type variable.
E.g.:
>>> e=3+4j
>>> id(e)47539552
2. eval function
43
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: -
>>> id(b)6925376
>>> id(c)52351136
>>> print(x) 10
>>> print(y) 20
>>> id(y)1625909680
>>> print(z) 30
>>> id(z)1625909840
>>> print(a) 10
>>> print(b) 20
Way-3:(shortest way): -
>>> print("The sum is " + str(int(input("Enter First Number: ")) + int(input("Enter Second
Number: "))))
2.Float(): -
This float() conversion function is used to convert other types into float type.
Way-1:
>>> id(b)52354144
>>> c=a+b
>>> id(c)52367096
>>> x=float(a)
>>> y=float(b)
>>> id(y)47459712
>>> z=x+y
>>> id(z)46410368
Way-2:(shorter way): -
>>> c=a+b
Way-3:(shortest way): -
>>> 31.0
3.Complex(): -
This complex() conversion function is used to convert string type data into Complex type.
Way-1:
>>> x=complex(a)
47
>>> id(x)47539768
Way-2: -
>>> (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
>>> id(a)52354272
>>> x=bool(a)
>>> id(x)1625727600
Way-2: -
>>> 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.
>>> print(a) 10
>>> type(b)
>>> print(d)(2+5j)
49
Assignment-1
1. Who is the father of Python?
Ans:
Ans:
3. Why did Guido Van Rossum keep the name ‘PYTHON’ to his language?
Ans:
Ans:
Ans:
6.What is a Python?
Ans:
Ans:
50
Ans:
Ans:
10. What are the different types of languages used to develop the Python language? Ans:
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:
Ans:
Ans:
Ans:
16. What are the different types of OSs where we can run python?
Ans:
Ans:
Ans:
Ans:
Ans:
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:
Ans:
Ans:
Ans:
28. Who will decide the type of variable in Python language? Developer or interpreter?
Ans:
Ans:
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:
Ans:
34. What is identifier in python? Can a single identifier contain combination of upper
case, lower case, underscore, and number?
Ans:
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:
Ans:
Ans:
Ans:
42. Can we convert string type data to our required data type? Different ways?
Ans:
Ans:
Ans:
45. What is the difference between type conversion functions and eval()?
Ans:
Ans:
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:
>>> name='Narayana'
>>> print(name)
>>> name="Narayana"
>>> name='''Narayana'''
(or)
>>> name="""Narayana"""
>>> print(name)Narayana
name="""Hello, Welcome to
world of PYTHON
print(name)
Hello, Welcome to
world of PYTHON
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'
Forward index: -
Python allows negative indexing for its sequences. The index of -1 refers to the last item,
Backward index: -
If we modify the content of the existing object then the indexes also will be changed
E.g.:
>>> print(x)
>>> 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
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[2:4]) RA
>>> print(a[7:8])A
>>> print(a[-8:-6]) NA
>>> print(a[-5:-4])A
String Concatenation: -
1. We can concatenate two or more strings into a single string is called concatenation.
E.g.: -
>>> string1='Python'
>>> string2='Developer'
60
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'
String is immutable object because we cannot replace or alter the existing string object.
E.g.: -
>>> st='Python'
>>> print(st)python
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])
String unpacking: -
1. String unpacking allows extracting all characters of string into different variables
automatically.
E.g.: -
>>> str1="Python"
>>> id(str1)23941472
>>> print(a)P
>>> print(b) y
>>> type(b)<class‘str’>
>>> print(c) t
>>> print(d) h
62
>>> print(e) o
>>> print(f)n
String Functions: -
1. Capitalize(): -This function converts first letter of first word in the given string into upper
case.
E.g.: -
>>>str1.capitalize()'Python developer'
2. Title(): -This function converts first character of each word in the given string into upper
case.
E.g.: -
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.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.: -
>>> str3='PYTHON'
>>> str3.isupper()True
5. lower(): -This function converts all lettersof given string into lower case.
E.g.: -
>>> str3='PYTHON'
6. upper(): -This function converts all letters of given string into upper case.
E.g.: -
7. len(): -This function counts the number of characters in the given string.
E.g.: -
>>> len(str1)16
8. count() : -This function counts no.of occurrences of a specific character in the given
string.
E.g.: -
>>> str1.count('o')2
9. find(): -This function finds the index position of specific character in the given string.
E.g.: -
10. split(): -This function splits the given strings into multiple strings.
Eg1: -
>>> str3='python.developer.in.TCS'
>>> str4='developer'
11. lstrip(): -This function removes specific special character to left side of given string.
E.g.: -
str1='!!!!!!Python Developer!!!!!!!'
12. rstrip(): -This function removes specific special character to the right side of given
string.
E.g.: -
str1='!!!!!!Python Developer!!!!!!!'
E.g.: -
str1='!!!!!!Python Developer!!!!!!!'
65
>>> str1='PyThOn'
>>> str1.swapcase()'pYtHoN'
E.g.: -
>>> str='Python'
>>> print(str)Python
>>> str=''.join(reversed(str))
>>> print(str)nohtyP
15. replace(): -This function replaces an existing character(s) with new character(s).
E.g.: -
>>> str2=str1.replace('learner','developer')
>>> str1='Python'
>>> str2=str1.replace('thon','')
>>> print(str2) Py
del command:-
We can delete the entire string objects permanently by using del command.
E.g.,1: -
>>> 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: -
>>> type(str1)<class‘str’>
>>> id(str1) 63806464
>>> st="python"
>>> ''.join(sorted(st))'hnopty'
>>> st1="PyThON deVELoPer"#if string contains both upper and lower cases
>>> ''.join(sorted(st1))'ELNOPPTVdeehory'
>>>st = ‘python’
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'
>>> print(st)
>>> st =‘hyderbad’
Way1: -
>>> st = ‘durga_soft’
‘durga’
Way2: -
>>> st = ‘durgasoft’
>>> a= st.split(‘s’)[0]
>>> print(a)
[‘durga’]
Way3: -
>>> st [o:5]
‘durga’
68
Using:: :-
>>> st[15::] ‘’
>>> st[6::9] ‘’
>>> st[7::2]‘nnhy’
String Compressor: -
E.g.,1: -
Str1 = ‘b’
Str2 = ‘a’
if st1> st2:
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
E.g.,2: -
St1 = ‘a’
St2 = ‘b’
if st1> st2:
else :
71
Output: -
b is bigger than a.
E.g.: -
st1= ‘python’
st2= ‘narayana’
if st1> st2:
else :
Output: -
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:
else :
72
Output: -
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.
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:-
>>> print(List1) [ ]
>>> type(List1)<class‘list’>
E.g.,3: -
>>> type(List1)<class‘str’>
E.g.,1: -
>>> print(list1) [ ]
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
We can also use range function to create list. Syn: range(StartingIndexValue, LastValue-
1,RangeValue) Here, both Starting IndexValue and RangeValue are optional.
E.g.,1: -
In python 2 version
>>>list1=list(range(10))
>>> type(list1)<class‘list’>
E.g.,2: -
>>>list1=list(range(0,10))
>>> type(list1)<class‘list’>
E.g.,3: -
>>>list1=list(range(2,8))
>>> type(list1)<class‘list’>
E.g.,4: -
>>>list1=list(range(-4,4))
>>> type(list1)<class‘list’>
E.g.,5: -
>>> List1=list(range(0,10,2))
>>> type(list)<class‘str’>
By using []: -
>>> lst = [ ]
>>> print(lst) []
By using list(): -
>>>print(lst1) []
>>> type(lst1)<class‘lst’>
By using range(): -
>>> lst1 []
List Indexing: -
1. By using list indexing we can fetch specific element from the list, by using its index
number.
E.g.: -
0 1 2 3 4 5 6
-7 -6 -5 -4 -3 -2 -1
76
E.g.:-
print (list1[0]) 10
print (list1[1]) 20
print (list1[2]) 30
print (list1[-5]) 30
print (list1[-6]) 20
print (list1[-7]) 10
python 2 python 3
………………………………………………………………………………………………….
List Slicing: -
E.g.: -
0 1 2 3 4 5 6
-7 -6 -5 -4 -3 -2 -1
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]
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.
Same address
>>> lst.append(40)
List Concatenation :
E.g.,1 :-
>>> List1=[10,'Python',5.5]
>>> List2=[20,30,'Narayana',3+4j]
E.g.,2: -
>>>l4 [10,20,30,40]
E.g.:
>>> List1=[10,'Python',5.5]
>>> List5=List1*3
List Functions:
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
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
E.g.: -
>>> 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
>>> 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():
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)
E.g., 2:
>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]
>>> List1.remove(True)
8. Pop():
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
E.g.,2:
>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]
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()
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:
del command:
This command is used to remove any specific element in the list (or) to remove entire list
object permanently.
E.g.,1:
>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]
E.g.,2:
>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]
E.g.:
>>> List1=[10,20,'Python',30,True,'Narayana',10,3+4j]
remove() pop()
It removes the specific element from the It also removes the specific element as
existing list. remove() function.
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.
>>> lst
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?
0 1 2 3 4
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']
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'
E.g.:
>>> List1=[10,'Python',5.5]
>>> List2=[20,30,'Narayana',3+4j]
>>> List3=[1,True,2,'Durga']
>>> NestList=[List1,List2,List3]
[1,True,2, ‘Durga’]]
0 1 2
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:
E.g.:
>>> type(Str1)<class‘str’>
>>> List1=Str1.split()
E.g.:
>>> type(List1)<class‘str’>
>>> Str2=" ".join(List1)
>>> type(Str2)<class‘str’>
E.g.:String
>>> Str1='Python'
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'
>>> Lst1=[10,20,30,40,'Guido',50]
>>> id(Lst1)53663224
List Packing:
>>> a=10
>>> b=20
>>> c=True
>>> d='Py'
>>> list1=[a,b,c,d]
>>> type(list1)<class‘list’>
List Unpacking:
1. List unpacking allows to extract all list elements automatically into different variables.
91
>>> lst=[10,20,'Python',True]
>>> print(a) 10
>>> type(a)<class‘int’>
>>> print(b) 20
>>> type(c)<class‘str’>
>>> type(d)<class‘bool’>
Q. How to generate a list as per user requirements?
UserList=range(start_val,end_val,step_size)
print(UserList)
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]
s=[1,20,3,6,8]
s1=[1,2,3,8]
output: -
[2, 22, 6]
[2, 22, 6]
List comprehension:
It provides an easy way to create list objects from any iterable objects based on some
conditions.
>>> type(lst1)<class‘list’>
Q. How to display squares for all even elements in the given list?
>>> 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]
E.g.:
name=['narayana','sai','krishna','veni']
>>> print(list1)
[['NARAYANA', 'Narayana', 'Narayana', 8], ['SAI', 'Sai', 'Sai', 3], ['KRISHNA', 'Krishna',
'Krishna', 7], ['VENI', 'Veni', 'Veni', 4]]
By Using:-
>>> lst=[10,20,30,40,50,60,70,80,90]
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 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]
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
>>> lst1=[10,20,30]
>>> lst2=[10,11,12,13]
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]
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
Explanation:1 from lst1 is smaller than 10 from lst2, so interpreter returned -1.
E.g6:
>>> lst1=[10]
>>> lst2=[1,2,3,4]
E.g7:
>>> lst1=[1,2]
>>> lst2=[1,2,3]
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]
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.
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.
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.
E.g.:
>>> tup=tuple([10,20,30,True,'Python'])
>>> id(tup)52059760
E.g.:
>>> print(tup) ()
>>> id(tup)23134256
E.g.:
>>> id(tup2)63484864
E.g.:
>>> id(tup)67086688
Creating a tuple with heterogeneous elements:
E.g.:
>>> tup1=(10,20,30,True,"Python",10.5,3+5j)
>>> id(tup1)58963648
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‘bool’>
So, to solve the above problem we should use comma (,) after the element in the tuple, like
E.g.:
>>> t2=(1,)
E.g.:
>>> t2=(false)
Tuple Indexing:
Tuple indexing is nothing but fetching a specific element from the existing tuple by using its
index value.
E.g.:
>>> type(p)<class‘tuple’>
0 1 2 3 4 5 6 7
-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)
>>> 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
E.g.,1: -
Output:
Narayana
(1037, 1000)
Tuple concatenation:
E.g.:
>>> type(tup)<class‘tuple’>
>>> type(tup3)<class‘tuple’>
E.g.:
>>> tup1=(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
E.g.:
>>> tup=(1,2,3,4,'a',5.5)
104
>>> len(tup) 6
>>> tup=(1,10,20,True,0)
>>> tup.count(1) 2
>>> tup.count(0)1
E.g.:
>>> tup=(1,10,20,True,0)
>>> tup.index(0) 4
>>> tup.index(10) 1
>>> tup.index(20) 2
E.g.:
>>> tup=(1,3,2,55,3,5,23)
>>> max(tup)55
E.g.:
>>> tup=(1,3,2,55,3,5,23)
>>> min(tup)1
E.g.:
>>> tup=(1,3,2,55,3,5,23)
105
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)
Or
>>> t1=tuple([1,2,3,7,4])
>>> t1 (1, 2, 3, 7, 4)
>>> t2=reversed(t1)
>>> tuple(t2)(4, 7, 3, 2, 1)
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.:
>>> print(lst)
[10,20,30,‘py’,False]
>>> tup=(10,20,30,'Py',True)
tup[4]=False
>>> tup=sorted(tup)
>>> tup=reversed(tup)
>>> print(tuple(tup))(30, 3, 5, 20, 10)
Nested tuple:
E.g.:
>>> t1=(1,'a',True)
>>> type(t1)<class‘tuple’>
>>> t2=(10,'b',False)
>>> type(t2)<class‘tuple’>
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) “ ” ”
>>> tup[0] 1
>>> tup[1] 2
>>> tup[4] 3
>>> tup[5]'Narayana'
>>> tup[0]=50 #trying to replace element 1 with 50, interpreter throws
error.
>>> 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.
>>> tup[2]=50 #trying to replace element [10,12,’a’] with 50, interpreter throws
error.
>>> 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:
>>> type(lst)<class‘tuple’>
>>> type(lst)<class‘tuple’>
>>> type(tup)<class‘tuple’>
>>> type(str1)<class‘str’>
>>> type(str1)<class‘str’>
>>> 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)
>>> id(tup)62673808
Tuple Unpacking:
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)
>>> print(b) 2
>>> print(c) 3
111
>>> print(d) 4
• 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.
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.
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[8::] ()
>>> t[8::1] ()
Tuple comparison:
E.g.,1:In Python 2:
113
>>> tup1=(10,20,30)
>>> tup2=(11,12)
E.g.,2:
>>> tup1=(10,20,30)
>>> tup2=(1,2,3,4,5)
E.g.,3:
>>> tup1=(10,20,30)
>>> tup2=(10,20,30,4,5)
E.g.,4:
>>> tup1=(10,20,30)
>>> tup2=(10,20,30)
E.g.,5:
>>> tup1=(10,30,20)
>>> tup2=(10,20,30)
E.g.,6:
>>> tup1=('a','b','x')
>>> tup2=('a','b','y')
E.g.,7:
>>> tup1=(True,True)
114
>>> tup2=(False,True)
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.
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.
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.
1. Creating an empty set using set() and add elements to that empty set.
E.g.:
115
E.g.:
E.g.:
‘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'}
E.g.:
>>> lst=[10,20,10,40,50,10,20]
>>> lst=list(set(lst))
>>> type(lst)<class‘set’>
Set functions :
E.g.:
>>> se1={1,2,3,4,5}
>>> print(se1){1, 2, 3, 4, 5}
>>> se1.add(7)
>>> print(se1) {1, 2, 3, 4, 5, 6, 7}
>> fs=frozenset([10,20,30,40])
>>> print(fs){10,20,30,40}
>>> fs.add(50) #trying to add new element to frozenset.
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}
>>> type(se1)<class‘set’>
>>> se1.remove(5) #removing element from 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}
>>> se1.discard(20) #trying to remove element which not there in the set.
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{1, 2, 3, 4, 5}
E.g.:
>>> se1={1,2,3,4,5}
>>> type(se1)<class‘set’>
>>> se1.clear() #clearing the se1, so se1 will become empty 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
>>> se1={1,2,3,4,5}
>>> se2={1,2,3}
>>> se1.issubset(se2)False
Or
119
>>> se1>=se2False
>>> se1={1,2,3,4,5}
>>> se2={1,2,3}
>>> 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}
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
E.g.:
120
>>> se1={1,2,3,4,5}
>>> se2={1,2,3,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.
E.g.:
>>> se1={1,2,3,4,5}
>>> se2={1,2,3,6,7}
>>> se1&se2{1, 2, 3}
Or
Diffferenece: It returns all elements from first set which are not there in the second set.
121
E.g.:
>>> se1={1,2,3,4,5}
>>> se2={1,2,3,6,7}
Or
Intersection_update:this function will update the First_Set with the result of intersection
between First_Set and Second_Set.
E.g.:
>>> se1={1,2,3,4,5}
>>> se2={1,2,3,6,7}
>>> se1.intersection_update(se2)
>>> se1={1,2,3,4,5}
>>> se2={1,2,3,6,7}
>>> se2.intersection_update(se1)
122
E.g.:
>>> se1={1,2,3,4,5}
>>> se2={1,2,3,6,7}
>>> se1.difference_update(se2)
>>> se1={1,2,3,4,5}
>>> se2={1,2,3,6,7}
>>> se2.difference_update(se1)
E.g.:
>>> se1={1,2,3,4,5}
>>> se2={1,2,3,6,7}
E.g.:
>>> se1={1,2,3,4,5}
>>> se2={1,2,3,6,7}
>>> se1.symmetric_difference_update(se2)
>>> 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(se2){4, 5, 6, 7}
remove() discard()
Set Unpacking:
>>> 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’
>>> 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.index({False,True,2,3}) 3
>>> len(lst[4]) 3
126
>>> lst[4][0] 2
>>> lst[4][1] 1
>>> 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]
E.g.,1:
Note:the given list has index number upto 4 only, but we are trying to access 5, which is not
available.
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[3] 12
>>> t[4] 13
>>> t[5] (10, 20, [100, 200, 300, {25, 35, 45}])
>>> t[5][0] 10
>>> t[5][1] 20
>>> 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,
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
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().
E.g.:
>>> dic1={}
>>> print(dic1) {}
>>> type(dic1)<class‘dict’>
>>> dic1['a']=10 #adding Key: Value pair to dictionary
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
E.g.:
>>> dic1={'a':10,'b':20,'c':30,'d':40}
>>> type(dic1)<class‘dict’>
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}
>>> print(stuDetails['Age']) 20
E.g.,2:
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.
>>> print(stuDetails) {'Id': 100, 'Name': 'Sai', 'subjects': ['SQL Server', 'Oracle',
If we need to delete the value 27 from the above dictionary then (by using pop)
>>>stuDetails.pop('Age') 27
>>> print(stuDetails)
>>> stuDetails.clear() #deleting all pairs, then we can have an empty dict.
>>> print(stuDetails){}
Dictionary functions
E.g.:
>>> dic1={1: 'Python', 2: (3+5j), 3: (10, 20, 30), 4: [100, 'a', False], 's': 100}
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])
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}
E.g.:
>>> dic1={1: 'Python', 2: (3+5j), 3: (10, 20, 30), 4: [100, 'a', False], 's': 100}
>>> 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.:
>>> 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. popitem()
>>>(‘Name’, ‘Teja’)
>>> d
E.g.:
>>> tup=(1,2,3,4,5)
>>> dic={}.fromkeys(tup,0)
we can also use list elements as keys in the dict and the elements must be unique
E.g.:
>>> stuDetails= {'Id': 100, 'Name': 'Sai', 'subjects': ['SQL Server', 'Oracle', 'Python'], 'id':
1000, 'name': 'nani'}
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'}
9.Update():The current dictionary will be updated with the all key:value pairs from another
dictionary.
E.g.:
>>> stuDetails1={'id':1000,'name':'nani'}
>>> stuDetails.update(stuDetails1)
>>> print(stuDetails)
{'Id': 100, 'Name': 'Sai', 'subjects': ['SQL Server', 'Oracle', 'Python'], 'id': 1000, 'name': 'nani'}
>>> print(d1) {'sub1': 80, 'sub2': 90, 'sub3': 70, 'sub4': 80}
>>> s=sum(d1.values())
134
>>> mx=max(d1.values())
>>> print(mx) 90
>>> mn=min(d1.values())
>>> print(mn) 70
>>> cnt=len(d1.values())
>>> print(cnt)4
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.
Set Orderedsetofuniqueobject
Frozenset Immutable form set
Tuple
135
Key:value pairs
E.g.:
states ={'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' }
cities['OR'] = 'Portland'
print ("%s state is abbreviated %s and has city %s" % ( state, abbrev, cities[abbrev]))
if not state:
print ("The city for the state 'TX' is: %s" % city)
Output:
……………………………………………………………..
Michigan's abbreviation is MI
Florida's abbreviation is FL
……………………………………………………………..
…………………………………………………………………
Oregon is abbreviated OR
137
Florida is abbreviated FL
California is abbreviated CA
Michigan is abbreviated MI
…………………………………………………………………………
…………………………………………………………………
……………………………………………………………………………
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.
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)
Q. Write a program to take dictionary from the keyboard & print the sum of value?
Q. Write a program to find number of occurrences of each letter present in the given string?
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?
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?
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:
Assignment- 2
1. What are the different types of data structures in python?
A.
A.
3. What is a List? What is the data type of list? Create one list?
A.
A.
A.
6. What is dictionary? What is the data type of it? Create one dictionary?
142
A.
A.
A.
9. What are the starting index numbers for both forward and backward indexing?
A.
A.
A.
j.Copy the same string into other new strings like str1,str2 and str3 at a time
A.
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?
15. What are the differences between append() and extend() in list?
A.
A.
A.
A.
A.
145
A.
A.
A.
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.
se1={1,2,3,4,5}
se2={1,2,3,6,7}
146
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.
A.
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.
a. se1==se2?
b. se1!=se2
c. se1<= se2
d. se1<se2
e. se2>se1
f. se1.isdisjoint(se2)
A.
34.>>> s1={1,2,3}
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?
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)
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
A.
>>> set2={10,20,30,60,70}
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
E.g.:tup=(1,2,3,4,5)
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]
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
4.Logical Operators
5. Bitwise Operators
6.Membership Operators
7. Identity Operators
1. Arithmetic Operators:
2.Assignment Operator:
Operator DescriptionExample
E.g.
158
a = 20
b = 10
c=0
c += a
c *= a
c /= a
c=2 c %= a
c **= a
c //= a
c -= a
output:
a value is 20
b value is 10
3. Comparison Operator:
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
5. Bitwise Operator:
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60;
a = 0011 1100
b = 0000 1101
~a = 1100 0011
162
Operator DescriptionExample
6. Membership Operator:
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
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
Operators Precedence: -
The following table lists all operators from highest precedence to lowest.
OperatorDescription
Exercise on operators:
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
12. "test" == 1
16. not (1 != 10 or 3 == 4)
3. Bitwise XOR
>>> a=20
>>> b=25
>>> c=15
>>> a /b&c 29
>>>abc 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
>>> a=100
>>> b=150
>>> c=200
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.
1. Simple IF or IF statement
2. IF – ELSE 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
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:
if marks>=35:
if a>b <c)
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
if len(name)>0:
E.g.,4:
people = 20
cats = 30
dogs = 15
dogs += 5
if people <=dogs:
if people ==dogs:
Output:
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.
if a 2 ==0:
else:
Output:
20 is even number
Or
21 is odd number.
else:
Output:
174
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”.
if len(name)<=o
else:
Output:-
Output:-
Enter name:
if num1> num2:
else:
Output :
10 is greater than 5.
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
else:
print(“invalid marks”)
Output:
else:
Output:
if a>b:
elif b>a:
else:
Output1 :
15 is greater than 10
Output2:
Output3:
15 is greater than 10
elif b>c:
180
else:
Output 1:
Output 2:
Output 3:
Output 4:
E.g.,5
people = 30
181
cars = 40
buses = 15
else:
else:
else:
output:
E.g.,6
182
print ("You enter a dark room with two doors. Do you go through door #1 or
door #2?”)
if door == "1":
print ("There's a giant bear here eating a cheesecake. What do you do?")
if bear == "1":
else:
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
>1
Nested if 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.
if gender=="Female" or gender=="Male":
ifgender=='Female':
else:
else:
else:
print("Thank")
Output:
Thank you.
if gender=="Male" or gender=="Female":
if gender!="Female":
if name=="Satya":
elif name=="Sai":
else:
else:
else:
Output:
Sorry, You entered Male1 , its invalid gender Please check once
qual=qual.lower()
name=name.capitalize()
if qual=='B.tech' or qual=='be':
if year==2016 or year==2017:
‘percentage only’)
else:
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’)
Output1:
Hello, Nani, please come to interview today because you got 88 percentage.
Output2:
Hello, Nani, you entered degree So, you are not eligible’.
Output3:
189
Hello, Krishna you entered 2018. it’s invalid passed out year.
Output4:
Output5:
Hello, Venu don’t come to interview because you got 10 percentage only.
Iterative Statements
For Loop:
E.g.,1:
St =“Python Developer”
190
For i in st:
Print(i)
Output:
For i in lst:
Print(i)
Output:
2
191
3.5
Python
(4+5j)
True
for i in tup
print(i)
Output:
True
False
Narayana
for i in se:
print(i)
Output:
Python
2
192
True
Narayana
(2+6j)
for i in dic:
print(i)
Output:
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
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 .
E.g.:
for i in Mylist
Print(i)
Output:
Narayana
100
Python
True
While Loop:
Syntax:
While expression:
194
Statement1
Statement2
Statement3
……………………
num=1
while( num<=5):
num+1
print(“Thank you”)
Output:
Mynum=10
myvar = 0
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
num=5
sum=0
i=1
sum= sum+i
i=i+1
Target-Num=10
Var=1
if var%2!=0:
var+=1
196
continue
print(‘This number=’str(var))
var+=1
Output:
This number = 2
This number = 4
This number = 6
This number = 8
While Tree:
if pwd== ‘Durgasoft’:
print(“congratulations”, name)
break
print(“Thankyou”, name)
Output:
Congratulations Narayana
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
int = int+1
else:
Output:
E.g.,1:
i=0
number =[ ]
while i<6:
numbers. Append(i)
198
i=i+1
print(“The numbers:”)
print(num)
Output:
At the top i is 0
At the bottom i is 1
At the top i is 1
At the bottom i is 2
At the top i is 2
At the bottom i is 3
At the top i is 3
At the bottom i is 4
At the top i is 4
At the bottom i is 5
At the top i is 5
At the bottom i is 6
The number
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
4. break
5. print(i)
6.
8. 0
200
9. 1
10. 2
11. 3
12. 4
13. 5
14. 6
E.g.:
1. cart=[ 10,20,600,60,70]
3. if i item> 500;
5. break
6. print(item)
7.
8. D:\python_classes> py test.py
9. 10
10. 20
2. Continue:-
We can use continue statement to skip current iteration and continue next iteration.
1. for i in range(10):
2. if i % 2==0
3. continue
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 ]
3. if item> =500
5. continue
6. print(item)
7.
8. Output
9. D:\python_classes> py.test
10. 10
11. 20
14. 50
15. 60
202
E.g.,3:
2. for n in numbers
3. if n==0
5. continue
6. print(“100/{ }”format(n,100/n))
7.
8. Output
9.
10. 100/10=10.0
13. 100/5=20
Inside loops execution, if break statement not executed, then only else part will be executed.
E.g.:
1. cart = [10,20,30,40,50]
3. if item>= 500:
5. break
203
6. print(item)
7. else:
9.
10.Output
11. 10
12. 20
13. 30
14. 40
15. 50
E.g.:
1. cart = [10,20,30,40,50]
3. if item>= 500:
5. break
6. print(item)
7. else:
9.
10.Output
12. 10
13. 20
204
3. Pass Statement:
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:
if True pass
==> valid
205
def mi()
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
E.g.:
>>>defadd(x,y):
Return x+y
>>>add(10,20)30
206
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
return x
elif y>z:
return y
else
return z
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.
for i in range(times):
print(message)
display_message()
output:
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.
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,
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.
for i in range(n):
print(msg)
If we don’t use any ‘Variable Name’ or formal arguments names in function call then there
are called “Non-keyword argument”.
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”
for i in range(n):
print(msg)
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”
for i in range(n):
print(msg)
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):
fun_call (actual_args)
Non
Default
O/p:3 4 (5,6)
print (a, b, c)
display (3, 2, 6)
O/p:3 2 (6,)
print (a, b, c)
display (3, 2 )
211
O/p:3 2 ()
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.
print(a, b, c, d)
print(a, b, c, d)
display(1)
212
Output:
1 10 () {}
display (2, 5)
2 5 () {}
2 3 (10,) {}
print(a, b, c, d)
display(1)
Output:
1 10 () {}
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.
1. Local variables
2. Global variables
Local variables:
213
glo_var=0
def cal_product_of_two_values(num1,num2):
loc_var = num1*num2
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 after calling the function is: 15
glo_var=0
def cal_product_of_two_values(num1,num2):
loc_var = num1*num2
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:
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
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:
When we need to call a function definition with function call which having a ‘List’
Output:
def pack_var(arg1,arg2,arg3):
print(arg1,arg2,arg3)
my_list=[100,200,300]
pack_var(*my_list)
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.:
cheese_and_crackers(20, 30)
Output:
We can just give the function numbers directly: You have 20 cheeses!
Get a blanket
Python Programs
1. Write a python function to check the given number is even or odd.
if n/2=0
else:
Output:
12 is even number.
13 is odd number.
def posorneg(n):
if n>=0:
else:
Output:
8 is positive number.
-9 is odd number.
if n /10==0:
else:
218
Output:
50 is divisible by 10.
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]
for i in range(n+1):
if i/2==0:
219
first nevennums(num)
Output:
10
10
S=0
for i in range(n+1):
S=S+i
Print(S)
Sum of digits(num)
220
Output:
120
10
7. Write a python function to print the largest number of three given values.
elif b>c:
else:
Output:
print(s+1)
reversestring(str)
Output:
anayaraN nohtyP
4321
Or
print(s+1)
reversestring(str)
Output:
oganjo
2837
for i in range(1,n+1):
if n/i==0:
print(i)
factors(num)
Output:
10
10
20
S=1
for i in range(1,n+1):
S=S*i
print(s)
factorial(num)
223
O/p:
120
temp=x
x=y
y=temp
O/p:
for i in range(2,n):
if n/2==0:
224
break
else:
prime or not(sum)
Output:
12 is not prime
7 is prime
else:
palindrome or not(n)
Output:
12321 is palindrome.
123432 is palindrome.
S=0
While n>0:
digit= n/10
S+= digit**3
n//=10
if num == 3:
else:
armstrong or not(n)
Output:
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:
13
21
34
55
89
5
227
t1= 0
t2=1
lst=[0]
temp=0
temp=t1+t2
t1=t2
t2= temp
lst. append(H)
if len (lst)==n:
for i in range(1000):
print(i)
fibonacci(num)
Output:
17.Write a python function to print the given three values in asc and desc order .
if y>z:
else:
else:
print(‘The desc)
if x>z:
else:
if x>y:
else:
order of value(a, b, c)
Output:
18. Write a python program to check the marital status, gender, age.
230
if marsta == “Married”:
if gen== “male”:
else:
if age>= 18:
else:
else:
else:
Output:
for i in range(1,11):
print(x,'*',i,'=',i*x)
table display(num)
Output:
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
V = ‘aeiouAEIOU’
st = list(st)
for i in st:
if i in v:
st = st.replace(i,‘’)
print(st)
O/p:
Python Narayana
Ding framework
21. Write a python function to copy a given string into new variable and count how many
character one copied.
c =0
str1 = ‘ ’
for i in st:
233
str1+ =i
c= c+1
print(st1)
print(c)
copystring(st)
O/p:
Python Narayana
def countdigits(n):
n1 =len(n)
print(n)
countdigits(num)
Output:
23. write a python function to print power value base on two given base and exponent value.
x= base ** expo
print(x)
234
power(base expo)
O/p:
Enter basevalue: 4
24. Write a python function to check weather user given string or number.
def stronum(m):
if m.isalpha() == True:
else:
O/p:
Vowel = ‘aeiouAEIOU’
if ch in vowel:
else:
vowel or conso(char)
O/p:
ais a vowel.
x is a consonant.
y is a consonant.
****
****
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)
*
**
***
****
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)
*
**
***
237
****
*****
******
*******
n=5
def pattern3(n):
k =0
for j in range(1,(n-i)+1):
Traditional way:
for i in range(1,11):
238
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
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
persons={'name':'Sai', "Age":28}
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:
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.
for i in range(1,5):
print(msg)
Output:
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
E.g.,1:
import datetime
my_date = datetime.datetime(2017,10,16,23,20,44)
E.g.,2:
import datetime
my_date = datetime.datetime(2017,10,16,23,20,44)
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
Eg1:
print ("So, you're {} years old, {} feet tall and {} kgs weight.".format(age,
height, weight))
Output:
So, you're 27 years old, 5.9 feet tall and 75 kgs weight.
Eg2:
return a + b
return a - b
return a * b
return a / b
print ("Let's do some math with just functions!") age = add(30, 5) height = subtract
Output:
ADDING 30 + 5
SUBTRACTING 78 - 4
MULTIPLYING 90 * 2
DIVIDING 100 / 2
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.
The argument list consists of a comma separated list of arguments and the expression is an
arithmetic expression using these arguments.
E.g.:
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”.
By using def
print(add_nums(1,2))3
by using Lambda
a=lambda x,y:x+y
print(a(1,2)) 3
def max_nums(x,y):
if x>y:
return x
else:
return y
O/p:print(max_nums(20,5))20
By using lambda
O/p:print(a(20,5))20
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]
print(odd_nums)
O/p:
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]
a=[1,2,3,4,5,6]
b=[4,10,11,1]
print(lst)[4, 1]
Map():
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]
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)
Since it's a built-in, map is always available and always works the same way.
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)
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)
for r in range(5):
print value
Output:
[0, 0]
[1, 1]
[4, 8]
[9, 27]
[16, 64]
Reduce()
x=reduce(func,seq)
The function continually applies the function func() to the sequence seq. It returns a single
value.
Syntax:
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)
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]
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)
print(a)2550
4. Self-keyword
249
5. Docstring
7. Constructor
9. Data hiding
11. Encapsulation
13. 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.
6. A class is the blueprint from which theindividual objects are created. Class is composed of
three things:
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):
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):
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):
ObjName=ClsName()
ObjName.function()
print(ClsName.__doc__)
Output:
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.
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
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.
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:
VarName = "Python"
def function(self):
In the above example, just one class is created with one variable and one function.
class ClsName:
VarName = "Python"
def function(self):
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.
1. The variables which are declared inside the class and outside all the methods are known as
class variables or static variables.
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.
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:
print(Myclass.j)
x1=Myclass()
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.
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.
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
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):
emp1=employee(101,"Sai",10000)
emp1.display()
emp2=employee(102,"Nani",20000)
emp2.display()
emp3=employee(103,"Renu",30000)
emp3.display()
Output:
257
E.g.,2:
class Myclass:
def method1(self):
self.i="Python"
def display(self):
print(self.i)
Obj1= Myclass ()
Obj1.display()
Obj1.i="It is very easy"
258
Obj2= Myclass ()
Obj2.display()
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():
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.
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.
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”.
b. Data should always be correct based on the validation requirement set in the
class methods.
E.g.:
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.
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
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:
2. Multi-level inheritance
3. Multiple inheritance
4. Hierarchical inheritance
The process of inheriting all attributes from one class to the other class is known
Class A
Class B
E.g.:
class A:a1=100
def methodA1(self):
def methodA2(self):
264
class B(A):
b1=200
def methodB1(self):
def methodB2(self):
ObjB=B()
print(ObjB.b1)
ObjB.methodB1()
ObjB.methodB2()
print(ObjB.a1)
ObjB.methodA1()
ObjB.methodA2()
Output:
200
100
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):
class B(A):
b1=200
def methodB1(self):
class C(B):
c1=300
def methodC1(self):
def methodC2(self):
class D(C):
d1=400
def methodD1(self):
def methodD2(self):
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
300
200
100
3. Hierarchical inheritance:
The process of inheriting all attributes from one base class into multiple derived classes is
called hierarchical inheritance.
Class A
class A:
a1=100
def methodA1(self):
def methodA2(self):
class B(A):
b1=200
def methodB1(self):
268
def methodB2(self):
class C(A):
c1=300
def methodC1(self):
def methodC2(self):
class D(A):
d1=400
def methodD1(self):
def methodD2(self)
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
100
300
100
200
270
100
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 D
E.g.:
class A:
a1=100
def methodA1(self):
def methodA2(self):
class B:
b1=200
def methodB1(self):
271
def methodB2(self):
class C:
c1=300
def methodC1(self):
def methodC2(self):
class D(C,B,A):
d1=400
def methodD1(self):
def methodD2(self):
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
300
200
100
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.
The concept of defining multiple methods with same name but different number of
parameters is called method overloading.
class classA:
def method1(self):
class classB:
def method1(self,a):
ObjB=classB()
ObjB.method1(10)
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):
class classB:
def method1(self):
ObjB=classB()
ObjB.method1()
Output:
class BankAccount:
def __init__(self,balance=10000):
self.balance=balance
def deposite(self,value):
self.balance=self.balance+value
def withdraw(self,value):
self.balance=self.balance-value
def __init__(self,balance=10000):
self.balance=balance
self.balance=self.balance+(value*1.03)
def __init__(self,balance=10000):
self.balance=balance
def withdraw(self,value):
if value>1000:
else:
self.balance=self.balance-value
CA=CurrentAccount()
while True:
print('1.Savings Account')
print("2.Current Account")
if MOption==1:
print('1.Withdraw')
print('2.Deposite')
if SOption==1:
SA.withdraw(value)
elif SOption==2:
SA.deposite(value)
else:
276
elif MOption==2:
print('1.Withdraw')
print('2.Deposite')
if SOption==1:
CA.withdraw(value)
elif SOption==2:
CA.deposite(value)
else:
print('You entered ',SOption,'Its invalid operation')
else:
Output1:
1.Savings Account
1.Withdraw
2.Deposite
Output2:
1.Savings Account
2.Current Account
1.Withdraw
2.Deposite
Output3:
1.Savings Account
2.Current Account
2.Deposite
Output4:
1.Savings Account
2.Current Account
1.Withdraw
278
Output5:
1.Savings Account
2.Current Account
1.Withdraw
2.Deposite
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.
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.
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('Users','Narayana','AppData','Local','Programs','Python','Python36-32')
'Users\\Narayana\\AppData\\Local\\Programs\\Python\\Python36-32'
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))
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'
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.”
…\ 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
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")
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