Python_Core_Tutorial
Python_Core_Tutorial
Introduction to PYTHON
Python is a general purpose, dynamic, high level and interpreted programming language. It supports
Object Oriented programming approach to develop applications. It is simple and easy to learn and
provides lots of high-level data structures.
Python is easy to learn yet powerful and versatile scripting language which makes it attractive for
Application Development.
Python's syntax and dynamic typing with its interpreted nature, makes it an ideal language for scripting
and rapid application development.
Python supports multiple programming pattern, including object oriented, imperative and functional or
procedural programming styles.
Python is not intended to work on special area such as web programming. That is why it is known as
multipurpose because it can be used with web, enterprise, 3D CAD etc.
We don't need to use data types to declare variable because it is dynamically typed so we can write
a=10 to assign an integer value in an integer variable.
Python makes the development and debugging fast because there is no compilation step included in
python development and edit-test-debug cycle is very fast.
PYTHON FEATURES
Python is easy to learn and use. It is developer-friendly and high level programming language.
2) Expressive Language
Python language is more expressive means that it is more understandable and readable.
3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line at a time. This makes
debugging easy and thus suitable for beginners.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh etc. So, we
can say that Python is a portable language.
Python language is freely available at offical web address.The source-code is also available. Therefore it
is open source.
6) Object-Oriented Language
Python supports object oriented language and concepts of classes and objects come into existence.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can be used
further in our python code.
Python has a large and broad library and prvides rich set of module and functions for rapid application
development.
10) Integrated
PYTHON HISTORY
The implementation of Python was started in the December 1989 by Guido Van Rossum at CWI(Centrum
Wiskunde & Informatica) in Netherland.
In February 1991, van Rossum published the code (labeled version 0.9.0) to alt.sources.
In 1994, Python 1.0 was released with new features like: lambda, map, filter, and reduce.
Python 2.0 added new features like: list comprehensions, garbage collection system.
On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify
fundamental flaw of the language.
ABC programming language is said to be the predecessor of Python language which was capable of
Exception Handling and interfacing with Amoeba Operating System.
ABC language.
Modula-3
Python is known for its general purpose nature that makes it applicable in almost each domain of
software development. Python as a whole can be used in any sphere of development.
1) Web Applications
We can use Python to develop web applications. It provides libraries to handle internet protocols such
as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser etc. It also provides
Frameworks such as Django, Pyramid, Flask etc to design and develop web based applications. Some
important developments are: PythonWikiEngines, Pocoo, PythonBlogSoftware etc.
Python provides Tk GUI library to develop user interface in python based application. Some other useful
toolkits wxWidgets, Kivy, pyqt that are useable on several platforms. The Kivy is popular for writing
multitouch applications.
3) Software Development
Python is helpful for software development process. It works as a support language and can be used for
build control and management, testing etc.
Python is popular and widely used in scientific and numeric computing. Some useful library and package
are SciPy, Pandas, IPython etc. SciPy is group of packages of engineering, science and mathematics.
5) Business Applications
Python is used to build Bussiness applications like ERP and e-commerce systems. Tryton is a high level
application platform.
We can use Python to develop console based applications. For example: IPython.
Python is awesome to perform multiple tasks and can be used to develop multimedia applications.
Some of real applications are: TimPlayer, cplay etc.
8) 3D CAD Applications
To create CAD application Fandango is a real application which provides full features of CAD.
9) Enterprise Applications
Python can be used to create applications which can be used within an Enterprise or an Organization.
Some real time applications are: OpenErp, Tryton, Picalo etc.
Using Python several application can be developed for image. Applications developed are: VPython,
Gogh, imgSeek etc.
There are several such applications which can be developed using Python
PYTHON VARIABLES
Variable is a name which is used to refer memory location. Variable also known as identifier and used to
hold value.
In Python, we don't need to specify the type of variable because Python is a type infer language and
smart enough to get variable type.
Variable names can be a group of both letters and digits, but they have to begin with a letter or an
underscore.
It is recomended to use lowercase letters for variable name. Rahul and rahul both are two different
variables.
Python does not bound us to declare variable before using in the application. It allows us to create
variable at required time.
We don't need to declare explicitly variable in Python. When we assign any value to the variable that
variable is declared automatically.
Eg:
a=10
name=”ravi”
salary=15000
print(a)
print(name)
print(salary)
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement which is also known as
multiple assignment.
We can apply multiple assignments in two ways either by assigning a single value to multiple variables or
assigning multiple values to multiple variables. Let’s see given examples.
x=y=z=50
print(x)
print(y)
print(z)
Output:
50
50
50
Output:
5
10
15
PYTHON OPERATORS
Operators are particular symbols that are used to perform operations on operands. It returns result that
can be used in application.
Example
4+5=9
Here 4 and 5 are Operands and (+) , (=) signs are the operators. This expression produces the output 9.
Types of Operators
• Arithmetic Operators.
• Relational Operators.
• Assignment Operators.
• Logical Operators.
• Membership Operators.
• Identity Operators.
Arithmetic Operators
The following table contains the arithmetic operators that are used to perform arithmetic operations.
Operators Description
Relational Operators
The following table contains the relational operators that are used to check relations.
Operators Description
< Less than
> Greater than
<= Less than or equal to
Assignment Operators
The following table contains the assignment operators that are used to assign values to the variables.
Operators Description
= Assignment
/= Divide and Assign
+= Add and assign
-= Subtract and Assign
*= Multiply and assign
%= Modulus and assign
**= Exponent and assign
//= Floor division and assign
Logical Operators
The following table contains the arithmetic operators that are used to perform arithmetic operations.
Operators Description
and Logical AND(When both conditions are true output will be true)
or Logical OR (If any one condition is true output will be true)
not Logical NOT(Compliment the condition i.e., reverse)
Example
a=5>4 and 3>2
print(a)
b=5>4 or 3<2
print(b)
c=not(5>4)
print(c)
Output:
True
True
False
Membership Operators
Operators Description
in Returns true if a variable is in sequence of another variable, else false.
not in Returns true if a variable is not in sequence of another variable, else false.
Example
a=10
b=20
list=[10,20,30,40,50]
if (a in list):
print("a is in given list")
else:
print("a is not in given list")
if(b not in list):
print("b is not given in list")
else:
print("b is given in list")
Output:
a is in given list
b is given in list
Identity Operators
Operators Description
is Returns true if identity of two operands are same, else false
is not Returns true if identity of two operands are not same, else false.
Example
a=20
b=20
if(a is b):
print( “a, b have same identity” )
else:
print(“a, b are different” )
b=10
if(a is not b):
print(“ a, b have different identity” )
else:
print(“a,b have same identity “ )
Output
PYTHON COMMENTS
Python supports two types of comments:
eg:
#single line comment
print("Hello Python")
'''''This is
multiline comment'''
PYTHON IF STATEMENTS
The Python if statement is a statement which is used to test specified condition. We can use if
statement to perform conditional operations in our Python application.
The if statement executes only when specified condition is true. We can pass any valid expression into
the if parentheses.
Example
a=10
if (a==10):
print( "Welcome to javatpoint" )
Output:
Hello User
Example
a=10
if (a>=20):
print("Condition is True")
else:
if (a>=15):
print("Checking second value" )
else:
print("All Conditions are false")
Output:
All Conditions are false.
Loops in PYTHON
FOR LOOP
Python for loop is used to iterate the elements of a collection in the order that they appear. This
collection can be a sequence(list or string).
Explanation:
Firstly, the first value will be assigned in the variable.
Secondly all the statements in the body of the loop are executed with the same value.
Thirdly, once step second is completed then variable is assigned the next value in the sequence and step
second is repeated.
Finally, it continues till all the values in the sequence are assigned in the variable and processed.
Example
num=2
for a in range (1,6):
print( num * a )
Output:
2
4
6
8
10
for <expression>:
for <expression>:
Body
Example
for i in range(1,6):
for j in range (1,i+1):
print(i,end=’’)
print( )
Output:
1
22
333
4444
55555
Explanation:
For each value of Outer loop the whole inner loop is executed.
For each value of inner loop the Body is executed each time.
Python Nested Loop Example 2
for i in range (1,6):
for j in range (5,i-1,-1):
print("*", end=’’)
print( )
Output:
* * * * *
* * * *
* * *
* *
*
Here, loop Body will execute till the expression passed is true. The Body may be a single statement or
multiple statement.
a=10
while (a>0):
print("Value of a is",a)
a=a-2
print("Loop is Completed")
Output:
Value of a is 10
Value of a is 8
Value of a is 6
Value of a is 4
Value of a is 2
Loop is Completed
Explanation:
Firstly, the value in the variable is initialized.
Secondly, the condition/expression in the while is evaluated. Consequently if condition is true, the
control enters in the body and executes all the statements . If the condition/expression passed results in
false then the control exists the body and straight away control goes to next instruction after body of
while.
Thirdly, in case condition was true having completed all the statements, the variable is incremented or
decremented. Having changed the value of variable step second is followed. This process continues till
the expression/condition becomes false.
Finally Rest of code after body is executed.
PYTHON BREAK
Break statement is a jump statement which is used to transfer execution control. It breaks the current
execution and in case of inner loop, inner loop terminates immediately.
When break statement is applied the control points to the line following the body of the loop, hence
applying break statement makes the loop to terminate and controls goes to next line pointing after loop
body.
for i in [1,2,3,4,5]:
if i==4:
print("Element found")
break
print(i,end=’’)
Output:
1 2 3 Element found
We can use continue statement with for as well as while loop in Python.
print(a)
print("End of Loop")
Output:
1
3
5
End of Loop
PYTHON PASS
In Python, pass keyword is used to execute nothing it means, when we don't want to execute code, the
pass can be used to execute empty. It is same as the name refers to. It just makes the control to pass by
without executing any code. If we want to bypass any code pass statement can be used.
PYTHON STRINGS
Python string is a built-in type text sequence. It is used to handle textual data in python. Python Strings
are immutable sequences of Unicode points. Creating Strings are simplest and easy to use in Python.
We can simply create Python String by enclosing a text in single as well as double quotes. Python treat
both single and double quotes statements same.
name="Rajat"
length=len(name)
i=0
for n in range(-1,(-length-1),-1):
print(name[i],"\t",name[n])
i+=1
Output:
R t
a a
j j
a a
t R
Expression Output
'10' + '20' '1020'
"s" + "007" 's007'
'abcd123' + 'xyz4' 'abcd123xyz4'
NOTE: Both the operands passed for concatenation must be of same type, else it will show an
error.
Eg:
'abc' + 3
output:
Traceback (most recent call last):
File "", line 1, in
'abc' + 3
TypeError: cannot concatenate 'str' and 'int' objects
Expression Output
"soono"*2 'soonosoono'
3*'1' '111'
'$'*5 '$$$$$'
NOTE: We can use Replication operator in any way i.e., int * string or string * int. Both the parameters
passed cannot be of same type.
1) in:"in" operator returns true if a character or the entire substring is present in the specified
string, otherwise false.
2) not in:"not in" operator returns true if a character or entire substring does not exist in the
specified string, otherwise false.
There can be many forms to slice a string, as string can be accessed or indexed from both the direction
and hence string can also be sliced from both the directions.
<string_name>[startIndex:endIndex],
<string_name>[:endIndex],
<string_name>[startIndex:]
Python String Slice Example 1
str="Nikhil"
str[0:6]
'Nikhil'
str[0:3]
'Nik'
str[2:5]
'khi'
str[:6]
'Nikhil'
str[3:]
'hil'
Note: startIndex in String slice is inclusive whereas endIndex is exclusive.
String slice can also be used with Concatenation operator to get whole string.
Methods Descriptions
find(substring ,beginIndex, It returns the index value of the string where substring
endIndex) is found between begin index and end index.
isdigit() It returns True if all the characters are digit and there is
at least one character, otherwise False.
startswith(str ,begin=0,end=n) It returns a Boolean value if the string starts with given
str between begin and end.
Welcome to sssit
2
2
True
False
False
False
str="Welcome to SSSIT"
substr1="come"
substr2="to"
print(str.find(substr1))
print(str.find(substr2))
print(str.find(substr1,3,10))
Output:
3
8
3
3
17
3
Traceback (most recent call last):
File "C:/Python27/fin.py", line 7, in
print(str.index(substr2,19)
ValueError: substring not found
str="Welcome to sssit"
print(str.isalnum())
str1="Python47"
print(str1.isalnum())
Output:
False
True
True
False
string1="HelloPython"
print(string1.isdigit())
string2="98564738"
print(string2.isdigit())
Output:
False
True
string1="Hello Python"
print(string1.islower())
string2="welcome to "
print(string2.islower())
Output:
False
True
string1="Hello Python"
print(string1.isupper())
string2="WELCOME TO"
print(string2.isupper())
Output:
False
True
string1=" "
print(string1.isspace())
string2="WELCOME TO WORLD OF PYT"
print(string2.isspace())
Output:
True
False
string1=" "
print(len(string1))
string2="WELCOME TO SSSIT"
print(len(string2))
Output:
4
16
string1="Hello Python"
print(string1.lower())
string2="WELCOME TO SSSIT"
print(string2.lower())
Output:
hello python
welcome to sssit
string1="Hello Python"
print(string1.upper())
string2="welcome to SSSIT"
print(string2.upper())
Output:
HELLO PYTHON
WELCOME TO SSSIT
string1="Hello Python"
print(string1.startswith('Hello'))
string2="welcome to SSSIT"
print(string2.startswith('come',3,7))
Output:
True
True
string1="Hello Python"
print(string1.swapcase())
string2="welcome to SSSIT"
print(string2.swapcase())
Output:
hELLO pYTHON
WELCOME TO sssit
Hello Python
welcome to world to SSSIT
Hello Python
@welcome to SSSIT
x = "#".join(myTuple)
print(x)
Output:
John#Peter#Vicky
Output:
True
Output:
I like apples
PYTHON LIST
Python list is a data structure which is used to store various types of data.
In Python, lists are mutable i.e., Python will not create a new list if we modify an element of the list.
It works as a container that holds other objects in a given order. We can perform various operations
like insertion and deletion on list.
A list can be composed by storing a sequence of different type of values separated by commas.
Python list is enclosed between square([]) brackets and elements are stored in the index basis with
starting index 0.
data1=[1,2,3,4]
data2=['x','y','z']
data3=[12.5,11.6]
data4=['raman','rahul']
data5=[]
data6=['abhinav',10,56.4,'a']
A list can be created by putting the value inside the square bracket and separated by comma.
Elements in a Lists:
Following are the pictorial representation of a list. We can see that it allows to access elements from
both end (forward and backward).
Data=[1,2,3,4,5]
Note: '+'operator implies that both the operands passed must be list else error will be shown.
list1=[1,2,4,5,7]
print(list1[0:2])
print(list1[4])
list1[1]=9
print(list1)
Output:
[1, 2]
7
[1, 9, 4, 5, 7]
Note: If the index provided in the list slice is outside the list, then it raises an Index Error exception.
data1=[5,10,15,20,25]
print("Values of list are: ")
print(data1)
data1[2]="Multiple of 5"
print("Values of list are: ")
print(data1)
Output:
list1=[10,"rahul",'z']
print("Elements of List are: ")
print(list1)
list1.append(10.45)
print("List after appending: ")
print(list1)
Output:
Deleting Elements
In Python, del statement can be used to delete an element from the list. It can also be used to delete
all items from startIndex to endIndex.
list1=[10,'rahul',50.8,'a',20,30]
print(list1)
del list1[0]
print(list1)
del list1[0:3]
print(list1)
Output:
This method is used to get min value from the list (only numbers).
list1=[101,981,189,228,105.22]
list2=[701,981,989,928,105.22]
print("Minimum value in List1: ",min(list1))
print("Minimum value in List2: ",min(list2))
Output:
list1=[101,981,189,228,105.22]
list2=[701,981,989,928,105.22]
print("Maximum value in List : ",max(list1))
print("Maximum value in List : ",max(list2))
Output:
list1=[101,981,'abcd','xyz','m']
list2=['aman','shekhar',100.45,98.2]
print("No. of elements in List1: ",len(list1) )
print("No. of elements in List2: ",len(list2))
Output:
This method is used to form a list from the given sequence of elements.
seq=(145,"abcd",'a')
data=list(seq)
print("List formed is : ",data)
Output:
Methods Description
index(object) It returns the index value of the object.
count(object) It returns the number of times an object is repeated in list.
pop()/pop(index) It returns the last object or the specified indexed object. It removes the
popped object.
insert(index,object) It inserts an object at the given index.
extend(sequence) It adds the sequence to existing list.
remove(object) It removes the object from the given List.
reverse() It reverses the position of all the elements of a list.
sort() It is used to sort the elements of the List.
sum() It is used to display the sum of the elements of the List.
data = [786,'abc','a',123.5]
print("Index of 123.5:", data.index(123.5))
print("Index of a is", data.index('a'))
Output:
Index of 123.5 : 3
Index of a is 2
data = [786,'abc','a',123.5,786,'rahul','b',786]
print("Number of times 123.5 occured is", data.count(123.5)
print("Number of times 786 occured is", data.count(786)
Output:
data = [786,'abc','a',123.5,786]
print("Last element is", data.pop())
print("2nd position element:", data.pop(1))
print(data )
Output:
data=['abc',123,10.5,'a']
data.insert(2,'hello')
print(data)
Output:
data1=['abc',123,10.5,'a']
data2=['ram',541]
data1.extend(data2)
print(data1)
print(data2 )
Output:
data1=['abc',123,10.5,'a','xyz']
data2=['ram',541]
print(data1)
data1.remove('xyz')
print(data1)
print(data2 )
data2.remove('ram')
print(data2)
Output:
list1=[10,20,30,40,50]
list1.reverse()
print(list1 )
Output:
[50, 40, 30, 20, 10]
list1=[10,50,13,44,8]
list1.sort()
print(list1 )
Output:
[8,10, 13, 44, 50]
data =[10,50,13,44,8]
print("Sum:", sum(data))
Output:
Sum: 125
PYTHON TUPLE
A tuple is a sequence of immutable objects, therefore tuple cannot be changed. It can be used to
collect different types of object.
Tuple is similar to list. Only the difference is that list is enclosed between square bracket, tuple
between parenthesis and List has mutable objects whereas Tuple has immutable objects.
There can be an empty Tuple also which contains no object. Let’s see an example of empty tuple.
Tuple1=(10,)
tupl1='a','mahesh',10.56
tupl2=tupl1,(10,20,30)
print(tupl1)
print(tupl2)
Output:
('a', 'mahesh', 10.56)
(('a', 'mahesh', 10.56), (10, 20, 30))
Accessing Tuple
Accessing of tuple is pretty easy we can access tuple in the same way as List. See, the following
example.
Output:
1
(1, 2)
('x', 'y')
(1, 2, 3, 4)
('x', 'y')
Elements in a Tuple
Data= (1,2,3,4,5,10,19,17)
data1=(1,2,3,4)
data2=('x','y','z')
data3=data1+data2
print(data1)
print(data2 )
print(data3 )
Output:
(1, 2, 3, 4)
('x', 'y', 'z')
(1, 2, 3, 4, 'x', 'y', 'z')
tuple1=(10,20,30)
tuple2=(40,50,60)
print(tuple1*2)
print(tuple2*3)
Output:
(10, 20, 30, 10, 20, 30)
(40, 50, 60, 40, 50, 60, 40, 50, 60)
data1=(1,2,4,5,7)
print(data1[0:2])
print(data1[4])
print(data1[:-1])
print(data1[-5:])
print(data1)
Output:
(1, 2)
7
(1, 2, 4, 5)
(1, 2, 4, 5, 7)
(1, 2, 4, 5, 7)
Note: If the index provided in the Tuple slice is outside the list, then it raises an IndexError exception.
Elements of the Tuple cannot be updated. This is due to the fact that Tuples are immutable. Whereas
the Tuple can be used to form a new Tuple.
Example
data=(10,20,30)
data[0]=100
print(data)
Output:
Traceback (most recent call last):
File "C:/Python27/t.py", line 2, in
data[0]=100
TypeError: 'tuple' object does not support item assignment
data1=(10,20,30)
data2=(40,50,60)
data3=data1+data2
print(data3)
Output:
(10, 20, 30, 40, 50, 60)
data=(10,20,'rahul',40.6,'z')
print(data)
del data #will delete the tuple data
print(data) #will show an error since tuple data is already deleted
Output:
(10, 20, 'rahul', 40.6, 'z')
Traceback (most recent call last):
File "C:/Python27/t.py", line 4, in
print(data
NameError: name 'data' is not defined
Functions of Tuple
There are following in-built Type Functions
Function Description
min(tuple) It returns the minimum value from a tuple.
max(tuple) It returns the maximum value from the tuple.
len(tuple) It gives the length of a tuple
tuple(sequence) It converts the sequence into tuple.
data=(10,20,55,40.6,87)
print(min(data))
Output:
10
Output:
98
data=(10,20,'rahul',40.6,'z')
print(len(data) )
Output:
5
tuple(sequence):
Eg:
dat=[10,20,30,40]
data=tuple(dat)
print(data )
Output:
(10, 20, 30, 40)
PYTHON SETS
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are
List, Tuple, and Dictionary, all with different qualities and usage.
* Note:
Set items are unchangeable, but you can remove items and add new items.
1 and True consider the same value.
0 and False consider the same value.
Eg:
ss = {"apple", "banana", "cherry"}
print(ss)
Function Description
all() Returns True if all elements of the set are true (or if the set is empty).
any() Returns True if any element of the set is true. If the set is empty, returns
False.
enumerate() Returns an enumerate object. It contains the index and value for all the
items of the set as a pair.
len() Returns the length (the number of items) in the set.
max() Returns the largest item in the set.
min() Returns the smallest item in the set.
sorted() Returns a new sorted list from elements in the set(does not sort the set
itself).
sum() Returns the sum of all elements in the set.
1) all():
The all() function returns True if all elements in the given iterable are true. If not, it
returns False.
Eg:
boolean_list = ['True', 'True', 'True']
# Output: True
2) any():
The any() function returns True if any element of an iterable is True. If not, it returns
False.
Eg:
boolean_list = ['True', 'False', 'True']
# Output: True
3) enumerate():
The enumerate() function adds a counter to an iterable and returns it (the enumerate
object).
Eg:
languages = ['Python', 'Java', 'JavaScript']
enumerate_prime = enumerate(languages)
4) len():
The len() function returns the number of items (length) in an object.
Eg:
languages = ['Python', 'Java', 'JavaScript']
# Output: 3
5) max():
The max() function returns the largest item in an iterable. It can also be used to find the
largest item between two or more parameters.
Eg:
numbers = [9, 34, 11, -4, 27]
# Output: 34
6) min():
The min() function returns the smallest item in an iterable. It can also be used to find the
smallest item between two or more parameters.
Eg:
numbers = [9, 34, 11, -4, 27]
# Output: -4
7) sorted():
The sorted() function sorts the elements of a given iterable in a specific order (ascending
or descending) and returns it as a list.
Eg:
numbers = [4, 2, 12, 8]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
8) sum():
The sum() function adds the items of an iterable and returns the sum.
Eg:
marks = [65, 71, 68, 74, 61]
# Output: 339
Additional Functions:
Method Description
type() It returns the data types of the sets
set() Make the set
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or
more sets
difference_update() Removes the items in this set that are also included in
another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in
other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
union() Return a set containing the union of sets
update() Update the set with the union of this set and others
PYTHON DICTIONARY
Dictionary is an unordered set of key and value pair. It is a container that contains data, enclosed
within curly braces.
The pair i.e., key and value is known as item. The key passed in the item must be unique.
The key and the value is separated by a colon(:). This pair is known as item. Items are separated from
each other by a comma(,). Different items are enclosed within a curly brace and this forms Dictionary.
Output:
{100: 'Ravi', 101: 'Vijay', 102: 'Rahul'}
plant={}
plant[1]='Ravi'
plant[2]='Manoj'
plant['name']='Hari'
plant[4]='Om'
print(plant[2] )
print(plant['name'])
print(plant[1])
print(plant)
Output:
Manoj
Hari
Ravi
{1: 'Ravi', 2: 'Manoj', 4: 'Om', 'name': 'Hari'}
Output:
Id of 1st employer is 100
Id of 2nd employer is 101
Name of 1st employer is Suresh
Profession of 2nd employer is Trainer
Example
data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}
data2={'Id':101, 'Name':'Ramesh', 'Profession':'Trainer'}
data1['Profession']='Manager'
data2['Salary']=20000
data1['Salary']=15000
print(data1 )
print(data2 )
Output:
Example
data={100:'Ram', 101:'Suraj', 102:'Alok'}
del data[102]
print(data)
del data
print(data) #will show an error since dictionary is deleted.
Output:
Functions Description
len(dictionary) It returns number of items in a dictionary.
str(dictionary) It gives the string representation of a dictionary.
Methods Description
get(key) It returns the value of the given key. If key is not present it returns none.
23
None
PYTHON FUNCTIONS
Types of Functions:
There are two types of Functions.
a) Built-in Functions: Functions that are predefined and organized into a library. We have used
many predefined functions in Python.
b) User- Defined: Functions that are created by the programmer to meet the requirements.
Defining a Function
A Function defined in Python should follow the following format:
1) Keyword def is used to start and declare a function. Def specifies the starting of function
block.
3) Parameters are passed inside the parenthesis. At the end a colon is marked.
def <function_name>(parameters):
</function_name>
Example
def sum(a,b):
4) Python code requires indentation (space) of code to keep it associate to the declared block.
Function Definition provides the information about function name, parameters and the definition
what operation is to be performed. In order to execute the function definition, we need to call the
function.
<function_name>(parameters)
</function_name>
Python Function Example
sum(a,b)
Here, sum is the function and a, b are the parameters passed to the function definition.
total=sum(10,20)
print(“Print(ing Outside: “,total
msg()
print("Rest of code"
Output:
1) The First type of data is the data passed in the function call. This data is called “arguments”.
2) The second type of data is the data received in the function definition. This data is called
‘parameters’.
Arguments can be literals, variables and expressions. Parameters must be variable to hold incoming
values.
Alternatively, arguments can be called as actual parameters or actual arguments and parameters can
be called as formal parameters or formal arguments.
def addition(x,y):
print(x+y)
x=15
addition(x ,10)
addition(x,x)
y=20
addition(x,y)
Output:
25
30
35
Passing Parameters
Apart from matching the parameters, there are other ways of matching the parameters.
2) Default argument.
Positional/Required Arguments:
When the function call statement must match the number and order of arguments as defined in the
function definition. It is Positional Argument matching.
sum(10,20)
sum (20)
Output:
30
</module>
Explanation:
1) In the first case, when sum() function is called passing two values i.e., 10 and 20 it matches with
function definition parameter and hence 10 and 20 is assigned to a and b respectively. The sum is
calculated and print(ed.
2) In the second case, when sum() function is called passing a single value i.e., 20 , it is passed to
function definition. Function definition accepts two parameters whereas only one value is being
passed, hence it will show an error.
#Function Definition
def msg(Id,Name,Age=21):
print("Printing the passed value" )
print(Id)
print(Name)
print(Age)
return
#Function call
msg(Id=100,Name='Ravi',Age=20)
msg(Id=101,Name='Ratan')
Output:
100
Ravi
20
101
Ratan
21
Explanation:
1) In first case, when msg() function is called passing three different values i.e., 100 , Ravi and 20,
these values will be assigned to respective parameters and thus respective values will be print(ed.
2) In second case, when msg() function is called passing two values i.e., 101 and Ratan, these values
will be assigned to Id and Name respectively. No value is assigned for third argument via function call
and hence it will retain its default value i.e, 21.
def msg(id,name):
print("Printing passed value")
print(id)
print(name)
return
msg(id=100,name='Raj')
msg(name='Rahul',id=101)
Output:
100
Raj
101
Rahul
Explanation:
1) In the first case, when msg() function is called passing two values i.e., id and name the position of
parameter passed is same as that of function definition and hence values are initialized to respective
parameters in function definition. This is done on the basis of the name of the parameter.
2) In second case, when msg() function is called passing two values i.e., name and id, although the
position of two parameters is different it initialize the value of id in Function call to id in Function
Definition. same with name parameter. Hence, values are initialized on the basis of name of the
parameter.
#Function Definiton
square=lambda x1: x1*x1
Example:
Normal function:
#Function Definiton
def square(x):
return x*x
#Function Definiton
square=lambda x1: x1*x1
Scope of Variable:
Scope of a variable can be determined by the part in which variable is defined. Each variable cannot be
accessed in each part of a program. There are two types of variables based on Scope:
1) Local Variable.
2) Global Variable.
Variables declared inside a function body is known as Local Variable. These have a local access thus
these variables cannot be accessed outside the function body in which they are declared.
def msg():
a=10
print("Value of a is",a)
return
msg()
Value of a is 10
</module>
Variable defined outside the function is called Global Variable. Global variable is accessed all over
program thus global variable have widest accessibility.
b=20
def msg():
a=10
print("Value of a is",a)
print("Value of b is",b)
return
msg()
print(b)
Output:
Value of a is 10
Value of b is 20
20
PYTHON MODULE
Modules are used to categorize Python code into smaller parts. A module is simply a Python file,
where classes, functions and variables are defined. Grouping similar code into a single file makes it
easy to access. Have a look at below example.
If the content of a book is not indexed or categorized into individual chapters, the book might have
turned boring and hectic. Hence, dividing book into chapters made it easy to understand.
In the same sense python modules are the files which have similar code. Thus module is simplifying a
python code where classes, variables and functions are defined.
1) Reusability: Module can be used in some other python code. Hence it provides the facility of code
reusability.
Importing a Module:
There are different ways by which you we can import a module. These are as follows:
Syntax:
Save the file by the name addition.py. To import this file "import" statement is used.
import addition
addition.add(10,20)
addition.add(30,40)
Create another python file in which you want to import the former python file. For that, import
statement is used as given in the above example. The corresponding method can be used by
file_name.method (). (Here, addition. add (), where addition is the python file and add () is the
method defined in the file addition.py)
Output:
30
70
NOTE: You can access any function which is inside a module by module name and function name
separated by dot. It is also known as period. Whole notation is known as dot notation.
1) msg.py:
def msg_method():
print("Today the weather is rainy")
return
2) display.py:
def display_method():
print("The weather is Sunny")
return
3) multiimport.py:
import msg,display
msg.msg_method()
display.display_method()
Output:
Syntax:
from <module_name> import <attribute1,attribute2,attribute3,...attributen>
</attribute1,attribute2,attribute3,...attributen></module_name>
def circle(r):
print(3.14*r*r
return
def square(l):
print(l*l)
return
def rectangle(l,b):
print(l*b)
return
def triangle(b,h):
print(0.5*b*h)
return
2) area1.py
100
10
Syntax:
1) area.py
2) area1.py
100
10
78.5
100.0
1) math:
Using math module , you can use different built in mathematical functions.
Functions:
Function Description
ceil(n) It returns the next integer number of the given number
sqrt(n) It returns the Square root of the given number.
exp(n) It returns the natural logarithm e raised to the given number
floor(n) It returns the previous integer number of the given number.
log(n,baseto) It returns the natural logarithm of the number.
pow(baseto, exp) It returns baseto raised to the exp power.
sin(n) It returns sine of the given radian.
cos(n) It returns cosine of the given radian.
tan(n) It returns tangent of the given radian.
import math
a=4.6
print(math.ceil(a))
print(math.floor(a))
b=9
print(math.sqrt(b))
print(math.exp(3.0))
print(math.log(2.0))
print(math.pow(2.0,3.0))
print(math.sin(0))
print(math.cos(0))
print(math.tan(45))
Output:
5.0
4.0
3.0
20.0855369232
0.69314718056
8.0
0.0
1.0
1.61977519054
2) random:
The random module is used to generate the random numbers. It provides the following two
built in functions:
Function Description
random() It returns a random number between 0.0 and 1.0 where 1.0 is exclusive.
randint(x,y) It returns a random number between x and y where both the numbers are
inclusive.
import random
print(random.random())
print(random.randint(2,8))
Output:
0.797473843839
7
Exception can be said to be any abnormal condition in a program resulting to the disruption in the
flow of the program.
Whenever an exception occurs the program halts the execution and thus further code is not executed.
Thus exception is that error which python script is unable to tackle with.
Exception in a code can also be handled. In case it is not handled, then the code is not executed
further and hence execution stops when exception occurs.
Common Exceptions
Exception Handling:
The suspicious code can be handled by using the try block. Enclose the code which raises an exception
inside the try block. The try block is followed by except statement. It is then further followed by
statements which are executed during exception and in case if exception does not occur.
Syntax:
try:
malicious code
except Exception1:
execute code
except Exception2:
execute code
....
....
except ExceptionN:
execute code
else:
In case of no exception, execute the else block code.
try:
a=10/0
print(a )
except ArithmeticError:
print("This statement is raising an exception")
else:
print("Welcome")
Output:
Explanation:
The malicious code (code having exception) is enclosed in the try block.
Try block is followed by except statement. There can be multiple except statement with a single try
block.
Except statement specifies the exception which occurred. In case that exception is occurred, the
corresponding statement will be executed.
At the last you can provide else statement. It is executed when no exception is occurred.
Python Exception(Except with no Exception) Example
Except statement can also be used without specifying Exception.
Example
try:
a=10/0
except:
print("Arithmetic Exception")
else:
print("Successfully Done")
Output:
Arithmetic Exception
Example
try:
a=10/0
except ArithmeticError,StandardError:
print("Arithmetic Exception")
else:
print("Successfully Done")
Output:
Arithmetic Exception
Finally Block:
In case if there is any code which the user want to be executed, whether exception occurs or not then
that code can be placed inside the finally block. Finally block will always be executed irrespective of
the exception.
Example
try:
a=10/0
print("Exception occurred")
finally:
print("Code to be executed")
Output:
Code to be executed
Traceback (most recent call last):
File "C:/Python27/noexception.py", line 2, in <module>
a=10/0
ZeroDivisionError: integer division or modulo by zero
In the above example finally block is executed. Since exception is not handled therefore exception
occurred and execution is stopped.
Raise an Exception:
You can explicitly throw an exception in Python using raise statement. raise will cause an exception to
occur and thus execution control will stop in case it is not handled.
Example
try:
a=10
print(a)
raise NameError("Hello")
except NameError as e:
print("An exception occurred")
print(e)
Output:
10
An exception occurred
Hello
Explanation:
ii) Exception can be provided with a value that can be given in the parenthesis. (here, Hello)
iii)To access the value "as" keyword is used. "e" is used as a reference variable which stores the value
of the exception.
PYTHON FILEHANDLING
Python has several functions for creating, reading, updating, and deleting files.
File Handling
• The key function for working with files in Python is the open() function.
1. "r" - Read - Default value. Opens a file for reading, error if the file does not exist
2. "a" - Append - Opens a file for appending, creates the file if it does not exist
3. "w" - Write - Opens a file for writing, creates the file if it does not exist
4. "x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
The code above is the same as:
f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exists, or else you will get an error.
Assume we have the following file, located in the same folder as Python:
demofile.txt
The open() function returns a file object, which has a read() method for reading the content of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
Read Only Parts of the File
By default the read() method returns the whole text, but you can also specify how many character you
want to return:
Example
Return the 5 first characters of the file:
f = open("demofile.txt", "r")
print(f.read(5))
Read Lines
You can return one line by using the readline() method:
Example
Read one line of the file:
f = open("demofile.txt", "r")
print(f.readline())
By calling readline() two times, you can read the two first lines:
Example
Read two lines of the file:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
By looping through the lines of the file, you can read the whole file, line by line:
Example
Loop through the file line by line:
f = open("demofile.txt", "r")
for x in f:
print(x)
Example
Open the file "demofile.txt" and append content to the file:
f = open("demofile.txt", "a")
f.write("Now the file has one more line!")
Example
Open the file "demofile.txt" and overwrite the content:
f = open("demofile.txt", "w")
f.write("Woops! I have deleted the content!")
Note: the "w" method will overwrite the entire file.
• "x" - Create - will create a file, returns an error if the file exist
• "a" - Append - will create a file if the specified file does not exist
• "w" - Write - will create a file if the specified file does not exist
Example
Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Result: a new empty file is created!
Example
Create a new file if it does not exist:
f = open("myfile.txt", "w")
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
Example
Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
Example
Check if file exist, then delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
To delete an entire folder, use the os.rmdir() method:
Example
Remove the folder "myfolder":
import os
os.rmdir("myfolder")
Note: You can only remove empty folders.