python full notes
python full notes
Python is designed to be highly readable. It has fewer syntactical constructions than other languages.
• Python is Interpreted: Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
• Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
• Python is a Beginner's Language: Python is a great language for the beginner-level programmers
and supports the development of a wide range of applications from simple text processing to
WWW browsers to games.
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research
Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk,
and Unix shell and other scripting languages.
Python is now maintained by a core development team at the institute, although Guido van Rossum still
holds a vital role in directing its progress.
Python Features
Python's features include:
• Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
• Easy-to-read: Python code is more clearly defined and visible to the eyes.
1
• Easy-to-maintain: Python's source code is fairly easy-to-maintain.
• A broad standard library: Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
• Interactive Mode:Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
• Portable: Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.
• Extendable: You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
• GUI Programming: Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.
• Scalable: Python provides a better structure and support for large programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good features, few are listed below:
• It can be used as a scripting language or can be compiled to byte-code for building large
applications.
• It provides very high-level dynamic data types and supports dynamic type checking.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
2
Python Basic Syntax
The Python language has many similarities to Perl, C, and Java. However, there are some definite
differences between the languages.
In the python input and output operations will be done by using input() and print() functions
ex:
print(“hello”)
a=”raju”
print(“hello”+a)
x=50
print(x)
pirnt(“x =”,x)
a=5 b=6
print(a,b)
Python provides the input() function to take the input from the standard input devices.
Syntax
input(“prompt”)
ex:
3
name=input(“enter your name”)
a=int(input(“enter a no”))
ex
a=5;
b=1.5
name=”nishitha”
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object. An
identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case
sensitive programming language. Thus, Manpower and manpower are two different identifiers in
Python.
• Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
• Starting an identifier with a single leading underscore indicates that the identifier is private.
• Starting an identifier with two leading underscores indicates a strongly private identifier.
• If the identifier also ends with two trailing underscores, the identifier is a language-defined special
name.
4
Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use them as
constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.
assert Finally or
def If return
elif In while
else Is with
The number of spaces in the indentation is variable, but all statements within the block must be indented
the same amount. For example –
If True:
print“True”
5
else:
print“False”
If True:
print“Answer”
print“True”
else:
print“Answer”
print“False”
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the line
continuation character (\) to denote that the line should continue. For example –
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation character.
For example –
days =[‘Monday’,‘Tuesday’,‘Wednesday’,
‘Thursday’,‘Friday’]
Quotation in Python
Python accepts single (‘), double (“) and triple (‘’’ or “””) quotes to denote string literals, as long as the
same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following are legal
–
word =‘word’
sentence =“This is a sentence.”
Paragraph =“””This is a paragraph. It is
made up of multiple lines and sentences.”””
6
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the
end of the physical line are part of the comment and the Python interpreter ignores them.
#!/usr/bin/python
# First comment
print“Hello, Python!”# second comment
Hello,Python!
Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by
one or more lines which make up the suite. For example –
if expression :
suite
elif expression :
suite
else:
suite
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.
7
Assigning Values to Variables
Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the =
operator is the value stored in the variable. For example –
print counter
print miles
print name
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For example –
a = b = c =1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory
location. You can also assign multiple objects to multiple variables. For example –
a,b,c =1,2,”raju”
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string
object with the value “john” is assigned to the variable c.
8
Python has five standard data types –
• Numbers
• String
• List
• Tuple
• Dictionary
Python Numbers
Number data types store numeric values. Number objects are created when you assign a value to them.
For example –
var1 =1
var2 =10
• long (long integers, they can also be represented in octal and hexadecimal)
Examples
Here are some examples of numbers –
• Python allows you to use a lowercase l with long, but it is recommended that you use only an
uppercase L to avoid confusion with the number 1. Python displays long integers with an
uppercase L.
9
• A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj,
where x and y are the real numbers and j is the imaginary unit.
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python
allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator
([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the
end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For
example –
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists
Lists are the most versatile of Python’s compound data types. A list contains items separated by commas
and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference
between them is that all the items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in
the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation
operator, and the asterisk (*) is the repetition operator. For example –
10
list =[‘abcd’,786,2.23,‘john’,70.2]
tinylist =[123,‘john’]
Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values
separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements
and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can
be thought of as read-only lists. For example –
tuple =(‘abcd’,786,2.23,‘john’,70.2)
tinytuple =(123,‘john’)
11
print tuple[2:]# Prints elements starting from 3rd element
print tinytuple *2# Prints list two times
print tuple + tinytuple # Prints concatenated lists
The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed.
Similar case is possible with lists –
tuple =(‘abcd’,786,2.23,‘john’,70.2)
list =[‘abcd’,786,2.23,‘john’,70.2]
tuple[2]=1000# Invalid syntax with tuple
list[2]=1000# Valid syntax with list
Python Dictionary
Python’s dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl
and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers
or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square
braces ([]). For example –
#!/usr/bin/python
dict ={}
dict[‘one’]=“This is one”
dict[2]=“This is two”
tinydict ={‘name’:‘john’,’code’:6734,‘dept’:‘sales’}
12
print dict[‘one’]# Prints value for ‘one’ key
print dict[2]# Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys()# Prints all the keys
print tinydict.values()# Prints all the values
This is one
This is two
{‘dept’: ‘sales’, ‘code’: 6734, ‘name’: ‘john’}
[‘dept’, ‘code’, ‘name’]
[‘sales’, 6734, ‘john’]
Dictionaries have no concept of order among elements. It is incorrect to say that the elements are “out of
order”; they are simply unordered.
There are several built-in functions to perform conversion from one data type to another. These functions
return a new object representing the converted value.
Function Description
Long(x [,base] ) Converts x to a long integer. Base specifies the base if x is a string.
13
Str(x) Converts object x to a string representation.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
14
Types of Operator
Python language supports the following types of operators.
• Arithmetic Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
- Subtraction Subtracts right hand operand from left hand operand. A–b=-
10
% Modulus Divides left hand operand by right hand operand and returns remainder b%a=0
15
// Floor Division – The division of operands where the result is the quotient in 9//2 = 4
which the digits after the decimal point are removed. But if one of the and
operands is negative, the result is floored, i.e., rounded away from zero 9.0//2.0 =
(towards negative infinity): 4.0, -
11//3 = -
4, -
11.0//3 =
-4.0
== If the values of two operands are equal, then the condition becomes true. (a == b) is not
true.
!= If values of two operands are not equal, then condition becomes true.
> If the value of left operand is greater than the value of right operand, then (a > b) is not
condition becomes true. true.
< If the value of left operand is less than the value of right operand, then (a < b) is true.
condition becomes true.
>= If the value of left operand is greater than or equal to the value of right (a >= b) is not
operand, then condition becomes true. true.
<= If the value of left operand is less than or equal to the value of right operand, (a <= b) is
then condition becomes true. true.
16
Operator Description Example
= Assigns values from right side operands to left side operand c=a+b
assigns value of
a + b into c
+= Add AND It adds right operand to the left operand and assign the result to left c += a is
operand equivalent to c
=c+a
-= Subtract AND It subtracts right operand from the left operand and assign the result c -= a is
to left operand equivalent to c
=c–a
*= Multiply It multiplies right operand with the left operand and assign the result c *= a is
AND to left operand equivalent to c
=c*a
/= Divide AND It divides left operand with the right operand and assign the result to c /= a is
left operand equivalent to c
= c / ac /= a is
equivalent to c
=c/a
%= Modulus It takes modulus using two operands and assign the result to left c %= a is
AND operand equivalent to c
=c%a
**= Exponent Performs exponential (power) calculation on operators and assign c **= a is
AND value to the left operand equivalent to c
= c ** a
17
//= Floor It performs floor division on operators and assign value to the left c //= a is
Division operand equivalent to c
= c // a
a = 0011 1100
b = 0000 1101
~a = 1100 0011
[ Show Example ]
& Binary AND Operator copies a bit to the result if it exists in both operands (a & b) (means
0000 1100)
18
^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49
(means 0011
0001)
~ Binary Ones It is unary and has the effect of ‘flipping’ bits. (~a ) = -61
Complement (means 1100
0011 in 2’s
complement
form due to a
signed binary
number.
<< Binary Left Shift The left operands value is moved left by the number of bits A << = 240
specified by the right operand. (means 1111
0000)
>> Binary Right Shift The left operands value is moved right by the number of bits A >> = 15
specified by the right operand. (means 0000
1111)
and return true if the both the statements are true a>5 and a<10
not reverse the result return false if the result is true not(a>5 and a<10)
19
Operator Description Example
in Evaluates to true if it finds a variable in the specified sequence and false X in y, here in
otherwise. results in a 1
if x is a
member of
sequence y.
Not in Evaluates to true if it does not finds a variable in the specified sequence and X not in y,
false otherwise. here not in
results in a 1
if x is not a
member of
sequence y.
print(“hello “+name)
a=int(input(“enter a no”))
c=a+b
print(“sum = “,c)
20
program to accept maths,physics,computer marks and find out total and avg marks
total=m+p+cs
avg=total/3
print(“total = “,total)
print(“avg = “,avg)
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need
to determine which action to take and which statements to execute if outcome is TRUE or FALSE
otherwise.
Following is the general form of a typical decision making structure found in most of the programming
languages –
21
Python programming language assumes any non-zero and non-null values as TRUE, and if it is
either zero or null, then it is assumed as FALSE value.
Python programming language provides following types of decision making statements. Click the
following links to check their detail.
Statement Description
nested if statements You can use one if or else if statement inside another if or else
if statement(s).
Syntax of if
if (condition):
statement 1
statement 2
Syntax of if else
if (condition):
statement 1
statement 2
else:
statement 1
statement 2
Nested if
22
Syntax
if (condition1):
if (condition2):
statements
If else ladder
syntax
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
n=int(input("enter a no"))
if n>0:
print("positive no")
else:
print("negative no")
23
Program to test given number is odd or even
n=int(input("enter a no"))
if n%2==0:
print("even no")
else:
print("odd no")
a=int(input("ener a no"))
if a>b:
print("max =",a)
else:
print("max = ",b)
n=int(input("enter a no"))
if n>0:
print("positive no")
elif n<0:
print("negative no")
24
else:
print("zero")
a=int(input("ener a no"))
if a>b:
if a>c:
print("max =",a)
else:
print("max =",c)
else:
if b>c:
print("max =",b)
else:
print("max =",c)
25
Python Loops
In general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on. There may be a situation when you need to execute a block of code
several number of times.
Programming languages provide various control structures that allow for more complicated execution
paths.
A loop statement allows us to execute a statement or group of statements multiple times. The following
diagram illustrates a loop statement −
Python programming language provides following types of loops to handle looping requirements.
for loop Executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable.
nested loops You can use one or more loop inside any another while, for or
do..while loop.
26
Example programs of loops
print 1 to 10 numbers
i=1
while(i<=10):
print(i)
i=i+1
print 10 to 1 numbers
i=10
while(i>1):
print(i)
i=i-1
n=int(input("enter a no"))
i=1
while(i<=10):
print(n,"*",i,"=",n*i)
i=i+1
27
for loop example
for i in range(5):
print(i)
o/p 0 1 2 3 4
range() is a predifined function which create the sequence of numbers starts from 0
nested loops
i=1
while i<=5:
j=1
while j<=i:
print(j," ",end="")
j=j+1
print("")
i=i+1
28
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed.
Python supports the following control statements. Click the following links to check their detail.
break statement Terminates the loop statement and transfers execution to the
statement immediately following the loop.
continue statement Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
pass statement The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.
if i == 4:
print(i)
29
# Using continue statement
if j == 3:
print(j)
1.
for i in range(5):
2. a=["aa","bb","cc","dd"]
for i in a:
if(i=="bb"):
continue
else:
print(i)
30
Functions
A function is a block of organized, reusable code that is used to perform an action. Functions provide better modularity for
As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a function in Python.
• Function blocks begin with the keyword def followed by the function name and parentheses ( ) .
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression to the caller. A return
Syntax
function_suite
return[expression] #optional
31
By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.
Example
The following function takes a string as input parameter and prints it on standard screen.
De0 fprintme(str):
printstr
return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the
blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the
printme("welcome")
printme("python funcitons")
example program
def printme(str):
print(str)
return
32
# funcion calling
printme("this is a function")
printme("hello")
def add(a,b):
c=a+b
print("sum = ",c)
return
a=int(input("enter a no"))
add(a,b)
def add(a,b):
c=a+b
return c
33
a=int(input("enter a no"))
c=add(a,b)
print("sum =",c)
Local Variables
Local variables are those which are initialized inside a function and belongs only to that particular function. It cannot be
Def abc():
print("Inside Function", s)
abc()
Global Variables
The global variables are those which are defined outside any function and which are accessible throughout the program i.e.
34
defabc():
print("Inside Function", s)
# Global scope
s = "welcome to python"
abc()
print("Outside Function", s)
Python utilizes a system, which is known as “Call by Object Reference” or “Call by assignment”. In the event that you pass
arguments like int,float, strings or tuples to a function, the passing is like call-by-value because you can not change the value of
the immutable objects being passed to the function. Whereas passing mutable objects like list can be considered as call by
reference because when their values are changed inside the function, then it will also be reflected outside the function.
def change(a):
a=a+1
a=5
35
change(a)
Output
De fadd_more(list):
list.append(50)
list = [10,20,30,40]
add_more(list)
Output
36
Note:
A mutable object can be changed after it is created, and an immutable object can't. ... Objects of built-in types like (int, float,
bool, str, tuple) are immutable. Objects of built-in types like (list, set, dict) are mutable.
Python defines a set of functions that are used to generate or manipulate random numbers through the random module.
Functions in the random module rely on a pseudo-random number generator function random(), which generates a random
float number between 0.0 and 1.0. These particular type of functions is used in a lot of games, lotteries, or any application
random():- This method is used to generate a float random number less than 1 and greater or equal to 0.
Example program
import random
print(random.random())
choice() :- choice() is an inbuilt function in the Python programming language that returns a random item from a list, tuple, or
string.
import random
list1 = [1, 2, 3, 4, 5, 6]
print(random.choice(list1))
37
# prints a random item from the string
string = "welcome"
print(random.choice(string))
randrange(beg, end, step):- The random module offers a function that can generate random numbers from a specified range
randint(beg,end) :- this function can generate random number from a specified range
math Module
Python has a built-in module that you can use for mathematical tasks.
fabs(x)
factorial(x)
ceil(x)
38
floor(x)
gcd(*integers)
isfinite(x)
isnan(x)
pow(x, y)
sin(x)
cos(x)
tan(x)
Modules in python
39
A module is simply a Python file with a .py extension that can be imported inside another Python program. The name of the
Python file becomes the module name. The module contains definitions and implementation of classes, variables, and
Creating a module
defprintme():
def add(a,b):
print(a+b)
def sub(a,b):
print(a-b)
name="nishitha"
save the above file as my.py and execute it. Then module name becomes my
import my
40
my.printme()
print(my.name)
print(my.add(4,5))
print(my.sub(10,5))
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file
Following are some of the built in functions to work with the files
Open()
Before performing any operation on the file like read or write, first we have to open that file. For this, we should use Python’s
But at the time of opening, we have to specify the mode, which represents the purpose of the opening file.
syntax
f = open(filename, mode)
w: open an existing file for a write operation. If the file already contains some data then it will be overridden.
a: open an existing file for append operation. It won’t override existing data.
r+: To read and write data into the file. The previous data in the file will not be deleted.
41
w+: To write and read data. It will override existing data.
a+: To append and read data from the file. It won’t override existing data.
write()
read()
append()
close()
file = open('abc.txt','w')
file.close()
42
print (file.read( )) # read all the contents
file.close()
file=open('abc.txt','r')
file.close()
print (each)
excepton handling
exception is an error which will occur while executing the program. The process of handling the exceptions are called as
exception handling. For this python provided try and except statements
try will try the exceptions and except is used to handle the exceptions
a = [1, 2, 3]
43
try:
except:
Sequences
In Python, sequence is the generic term for an ordered set. There are several types of sequences in Python;
the following three are the most important.
Lists are the most versatile sequence type. The elements of a list can be any object, and lists are mutable -
they can be changed. Elements can be reassigned or removed, and new elements can be inserted.
Tuples are like lists, but they are immutable - they can't be changed.
Strings are a special type of sequence that can only store characters, and they have a special notation.
However, all of the sequence operations described below can also be used on strings.
Sequence Operations
+ combines two sequences in a process called concatenation. For example, [1,2,3]+[4,5] will evaluate to
[1,2,3,4,5].
* repeats a sequence a (positive integral) number of times. For example, [1,11]*3 will evaluate to
[1,11,1,11,1,11].
x in mySeq will return True if x is an element of mySeq, and False otherwise. You can negate this
statement with either not (x in mySeq) or x not in mySeq.
mySeq[i] will return the i'th character of mySeq. Sequences in Python are zero-indexed, so the first
element has index 0, the second has index 1, and so on.
44
mySeq[-i] will return the i'th element from the end of mySeq, so mySeq[-1] is the last element of mySeq,
mySeq[-2] is the second-to-last element, etc.
Useful Functions
len(mySeq), short for length, returns the number of elements in the sequence mySeq.
Searching
mySeq.index(x) returns the index of the first occurrence of x in mySeq. Note that if x isn't in mySeq
index will return an error. (Use in with an if statement first to avoid this.)
min(mySeq) and max(mySeq) return the smallest and largest elements of mySeq, respectively. If the
elements are strings this would be the first and last elements in lexicographic order (the order of words in
a dictionary). Note that if any two elements in mySeq are incomparable (a string and a number, for
example), min and max will return errors.
mySeq.count(x) returns the number of occurrences of x in mySeq (that is, the number of elements in
mySeq that are equal to x).
List
Lists are used to store multiple items in a single variable.
Lists are the most versatile sequence type. The elements of a list can be any object, and lists are mutable -
they can be changed. Elements can be reassigned or removed, and new elements can be inserted.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set,
and Dictionary, all with different qualities and usage.
Example
Create a List:
print(fruits)
List items are indexed, the first item has index [0], the second item has index [1] etc.
45
When we say that lists are ordered, it means that the items have a defined order, and that order will not
change.
Note: There are some list methods that will change the order, but in general: the order of the items will
not change.
The list is changeable, meaning that we can change, add, and remove items in a list after it has been
created.
Since lists are indexed, lists can have items with the same value:
Example
print(fruits)
List Slicing
In Python, list slicing is a common practice and it is the most used technique for programmers to solve
efficient problems. Consider a python list, In-order to access a range of elements in a list, you need to
slice a list. One way to do this is to use the simple slicing operator i.e. colon(:)
With this operator, one can specify where to start the slicing, where to end, and specify the step. List
slicing returns a new list from the existing list.
Syntax:
a=[1,2,3,4,5,6,7,8]
46
fruits=["apple","banana","orange","mango","cherry","papaya"]
print(fruits)
if a in fruits:
print("found")
else:
print("not found")
List methods
Python has a set of built-in methods that you can use on lists.
Method Description
extend() Add the elements of a list to the end of the current list
index() Returns the index of the first element with the specified value
pop() Removes the element at the specified position by default last value
append(): Used for appending and adding elements to List. It is used to add elements to the last position
of List.
47
Syntax:
list.append (element)
ex: names=["prasad","raju","srinu","venu","madhu"]
names.append(“ramu”)
ex:
a=[5,3,1,8,45,32]
b=a.copy()
print(b)
Syntax:
List.count(element)
Syntax:
List1.extend(List2)
Ex:
a=[1,2,3,4,5]
b=[10,11,12]
a.extend(b)
print(a)
index(): Returns the index of first occurrence. Start and End index are not necessary parameters.
Syntax:
List.index(element[,start[,end]])
48
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2)) o/p 1
print(List.index(2,2,5))
Syntax:
list.insert(position, element)
ex:
names.insert(2,”aaa”)
pop(): Index is not a necessary parameter, if not mentioned takes the last index.
Syntax:
list.pop([index])
Syntax:
list.remove(element)
ex:
a=[5,3,1,8,45,32]
a.sort()
print(a)
a=[5,3,1,8,45,32]
49
a.reverse()
print(a)
Syntax:
sum(List)
Syntax:
len(list)
Syntax:
min(List)
Syntax:
max(List)
names=["prasad","raju","srinu","venu","madhu"]
print(names)
print(len(names))
marks=[45,67,43,21,89,43]
print("min marks",min(marks))
print("max marks",max(marks))
50
print("43 repeated ",marks.count(43)," times")
list=[1,2,3,4,5,6]
for i in list:
print(i)
print(i)
for i in range(0,len(list)):
print(list[i])
Multi-dimensional lists
There can be more than one additional dimension to lists in Python. Keeping in mind that a list can hold
other lists, that basic principle can be applied over and over. Multi-dimensional lists are the lists within
lists. Usually, a dictionary will be the better choice rather than a multi-dimensional list in Python.
51
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
print(a) o/p[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
for record in a:
print(record)
a = [ [2, 4, 6, 8 ],
[ 1, 3, 5, 7 ],
[ 8, 6, 4, 2 ],
[ 7, 5, 3, 1 ] ]
for i in range(len(a)) :
for j in range(len(a[i])) :
print()
Output:
2468
1357
8642
52
7531
Tuple
Tuples are used to store multiple items in a single variable.
Ex:
print(fruits)
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been
created.
Tuple methods
Count()
Index()
Min()
Max()
Len()
a=(1,2,3,4,5,6,7,8)
print(a)
53
print("min value from tuple is ",min(a))
print("5 is repeated",a.count(5),"times")
sub=("maths","computers","physics","english","telugu")
print(sub)
for i in sub:
print(i)
Strings
String is nothing but a group of characters. Strings in Python can be created using single quotes or double
quotes or even triple quotes.
Ex:
In Python, individual characters of a String can be accessed by using the method of Indexing. Index starts
from 0. Indexing allows negative address references to access characters from the back of the String, e.g.
-1 refers to the last character, -2 refers to the second last character, and so on.
While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be
passed as an index, float or other types that will cause a TypeError.
54
0 1 2 3 4 5 6
W e l c o m e
-7 -6 -5 -4 -3 -2 -1
S1=”welcome”
String Slicing
To access a range of characters in the String, the method of slicing is used. Slicing in a String is done by
using a Slicing operator (colon).
print(s1)
print("string from 4th character ",s1[3:]) # disply from 4th character (index 3)
print("string from index 3 to 9",s1[3:10]) # display from index 3 (4th char) to index 9 (10th char)
In Python, Updating or deletion of characters from a String is not allowed. This will cause an error because
item assignment or item deletion from a String is not supported. Although deletion of the entire String is
possible with the use of a built-in del keyword. This is because Strings are immutable; hence elements of a
String cannot be changed once it has been assigned. Only new strings can be reassigned to the same name.
String methods
Method Description
55
endswith() Returns true if the string ends with the specified value
index() Searches the string for a specified value and returns the position of where it was found
isalpha() Returns True if all characters in the string are in the alphabet
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
word="welcome"
rollno="101"
name="Prasad"
56
print(name.istitle()) #test if string contains title words
sets
Sets are used to store multiple items in a single variable. It is a collection which is unordered, un indexed
and do not allow duplicate values. Sets are created by using { }
Ex:
S1={1,2,3,4,5}
S2={10,20,30,40,50}
Set methods
Method Description
57
Program for set operations
s1={1,2,3,4,5}
s2={10,20,30,40,50}
# print(s1[0]) invalid sets are not subscriptable because they are unordered
print(s1)
print(len(s1))
s1.pop()
s3=s1.copy()
s3.clear()
s2.remove(30)
Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values unlike other Data
Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided
in the dictionary to make it more optimized.
In Python, a Dictionary can be created by placing a sequence of elements within curly { } braces, separated
by ‘comma’. Dictionary holds pairs of values, one being the Key and the other corresponding value. Values
58
in a dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and must be
immutable.
Dictionary methods
Method Description
items() Returns a list containing a tuple for each key value pair
print(a)
print(a.keys())
print(a.values())
59
b=a.copy()
print("after copying",b)
b.clear()
a.pop(2)
a.popitem()
stu={"rollno":101,"name":"raju","marks":60}
print(stu)
print("rollno is ",stu["rollno"])
print("name is ",stu["name"])
print("marks = ",stu["marks"])
Recursion
It is a process in which a function calls itself here calling function and called functions are same.
The term Recursion can be defined as the process of defining something in terms of itself
A complicated function can be split down into smaller sub-problems utilizing recursion.
Sequence creation is simpler through recursion than utilizing any nested iteration.
A lot of memory and time is taken through recursive calls which makes it expensive for use.
60
Recursive functions are challenging to debug.
Def abc()
------
------
abc()
Example 1:
def fibo(n):
if n <= 1:
return n
else:
return(fibo(n-1) + fibo(n-2))
n = 20
if n <= 0:
else:
print("Fibonacci series:")
for i in range(n):
print(fibo(i))
61
Example 2:
# Recursive function
def recursive_factorial(n):
if n == 1:
return n
else:
return n * recursive_factorial(n-1)
# user input
num = 6
if num < 0:
elif num == 0:
else:
62
In Python, object-oriented Programming (OOPs) is a programming paradigm that uses objects and
classes in programming. It aims to implement real-world entities . The main concept of OOPs is
to bind the data and the functions that work on that together as a single unit so that no other part
of the code can access this data.
Class
Objects
Polymorphism
Encapsulation
Inheritance
Class
A class is specification of an object where it contain two thing variables and functions.A class is a
collection of objects. A class contains the blueprints or the prototype from which the objects are
being created. It is a logical entity that contains some attributes and methods.
In the python class is created using a keyword called class. Attributes are the variables that belong
to a class.
Syntax:
class ClassName:
# Statement-1
# Statement-N
Object
Instance of a class is called an object. The object is an entity that has a state and behavior associated
with it. It may be any real-world object like a mouse, keyboard, chair, table, pen, etc.
An object consists of :
63
State: It is represented by the attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by the methods of an object. It also reflects the response of an object
to other objects.
Identity: It gives a unique name to an object and enables one object to interact with other objects.
Syntax
Objectname=classname( )
The self
Class methods must have an extra first parameter in the method definition. We do not give a value
for this parameter when we call the method, Python provides it
If we have a method that takes no arguments, then we still have to have one argument.
The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object of a
class is instantiated. The method is useful to do any initialization you want to do with your object.
Example program
class stu:
rollno=10
name="abc"
def disp(self):
print("rollno ",self.rollno)
print("name ",self.name);
64
s1.disp()
example 2
class stu:
rollno=10
name="abc"
def store(self,r,n):
self.rollno=r
self.name=n
def disp(self):
print("rollno ",self.rollno)
print("name ",self.name);
s1.disp()
s2=stu()
s2.store(20,"xyz")
s2.disp()
inheritance
It is a process of creating new class from an existing class. Here existing
class is called as base class(super,parent class) and new class is called as
sub class (derived ,child class).
65
Derived class inherits features from the base class where new features can
be added to it. This results in re-usability of code.
Syntax
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Example program for inheritance
class Person: # creating person class
self.name = name
self.age = age
def printperson(self):
print(self.name, self.age)
super().__init__(name, age)
self.rollno = rollno
self.marks=marks
def printstudent(self):
print("age ",self.age)
66
print("rollno ",self.rollno)
print("marks ",self.marks)
x = Student("rajkumar",20,101,80)
x.printstudent()
Polymorphism
The word polymorphism means having many forms i.e Using same entity in many ways. This can
be achieved in many ways in that one way is function overloading
Function overloading means same function name (but different signatures) being used for different
types.
num1 = 1
num2 = 2
print(num1+num2)
str1 = "Python"
str2 = "Programming"
print(str1+" "+str2)
here + operator is used to add two integers and same operator is used to concatenate two strings
67
Polymorphism in Class Methods
class Cat:
self.name = name
self.age = age
def info(self):
def make_sound(self):
print("Meow")
class Dog:
68
self.name = name
self.age = age
def info(self):
def make_sound(self):
print("Bark")
dog1 = Dog("Fluffy", 4)
animal.make_sound()
animal.info()
animal.make_sound()
output
Meow
Meow
Bark
Bark
69