Python Lecture Notes
Python Lecture Notes
INTRODUCTION
Python is one of the most popular programming languages. It delivers both the power and general
applicability of traditional compiled languages with the ease of use of simpler scripting and interpreted languages.
Python is developed by Guido van Rossum.
Applications of Python:
Python is used to develop
✔ Artificial Intelligence Applications
✔ Automation and Web Applications
✔ GUI (Graphical User Interface) Applications
✔ Scientific and Business Applications
✔ Console Based Applications
✔ Audio & Video Based Applications
✔ Image Processing & 3D CAD Applications
✔ Enterprise Applications
Features of Python:
The following are set of python features that describes about python.
High Level:
Python is a high level language with more powerful concepts like lists, tuples and dictionaries. With help
of these concepts one can minimizes the development time as well as code size.
Object Oriented:
Object-oriented programming (OOP) adds another dimension to structured and procedural languages
where data and logic are discrete elements of programming. OOP allows for associating specific behaviors,
characteristics, and/or capabilities with the data that they execute on or are representative of. Python is an object-
oriented (OO) language, all the way down to its core. However, Python is not just an OO language like Java or Ruby.
It is actually a pleasant mix of multiple programming paradigms. For instance, it even borrows a few things from
functional languages like Lisp and Haskell.
Scalable
Python is scalable where we can grow our code from project to project, add other new or existing Python
elements, and reuse code.
Extensible
As the amount of Python code increases in your project, you will still be able to organize it logically by
separating your code into multiple files, or modules, and be able to access code from one module and attributes
from another.
Portable
Python can be found on a wide variety of systems, contributing to its continued rapid growth in today's
computing domain. Because Python is written in C, and because of C's portability, Python is available on practically
every type of platform that has an ANSI C compiler.
Easy to Learn
Python has relatively few keywords, simple structure, and a clearly defined syntax. This allows anyone to
pick up the language in a relatively short period of time.
Easy to Read
Python making it easier for others to understand your code faster and vice versa. Because of its syntax
and styles.
Easy to Maintain
Maintaining source code is part of the software development lifecycle. Much of Python's success is that
source code is fairly easy to maintain, dependent, of course, on size and complexity.
Robust
Python even gives you the ability to monitor for errors and take an evasive course of action if such an
error does occur during runtime. Python's robustness is beneficial for both the software designer and the user.
There is also some accountability when certain errors occur that are not handled properly. The stack trace that is
generated as a result of an error reveals not only the type and location of the error, but also in which module the
erroneous code resides.
Running Python
We can run python programs in command prompt itself by using python command.
In above screenshot >>> is called as python prompt where python programs will be typed and executed.
For example in the above pic, a small program is written in which a variable x is initialized with the value 10 and it
is printed.
It is possible to type and save our python programs through text editors like notepad and we can execute
the program with python command.
Example:
For example a small python program is typed using text editor and saved it as example.py
Now we can execute the same program by using python command in command prompt as follows.
Output
In above program both the values are concatenated because “input” method always reads the user inputs as
strings. We must convert those values into numbers before performing arithmetic operations. These concepts will
be explained after datatypes.
Python
PYTHONSyntax and &
SYNTAX Style
STYLE
i) Blocks are represented by indentation instead of curly braces.
For example while writing a block with if condition (or any type of block), please observe that
curly braces are not used to indicate starting and ending of the block. Instead of that indentation
is used. All the statements in that block are maintained the same indentation (spaces).
Example:
x = 10
if(x==10) :
In the above example colon ( : ) indicates the starting of the block. All the statements in the
block are maintain the same indentation (at least one space - generally 4 or 8 spaces to improve
understanding ability but not mandatory).
First 2 print statements maintained the same indentation (spaces at starting position) after colon
that indicates these two statements are belonged to the ‘ if ’ block.
Third print statement is written without indentation means it is not related to that block.
output
#This is a comment
x = 10 #this comment starts from here
Generally writing comments is good programming habit. It will improve program understand
ability and we can temporarily suspend executing some statements by putting them in
comments.
iii) Continuation ( \ ) operator
While developing projects, there are some cases where a single statement may occupies more
than one line. In that case if we use continuation operator then python interpreter can
understand and treat those multiple line statement as single statement.
Example
In the above example \ is placed at the end of first statement that indicates next line also
belonged to this statement only.
iv) Suites or Blocks
As mentioned in above examples, blocks are not represented by curly braces in python. Instead
of it colon and indentation are used. Colon indicates the starting of a block and indentation
indicates the statements that are belonged to the particular block.
Example
If(condition):
Statement1
Statement2
Consider the above block of statements. Please observe we did not use any open curly brace to
indicate starting of the block instead we used colon ( : ) symbol which indicates some block is
started at this point. All the statements related to this block are written with some indentation.
v) Use of Semicolons ( ; )
In python semicolons are not mandatory to use at the end of each and every statement.
If more than one statement is written in the same line then we will use semicolons to
separate one from the other.
Example
x=10;y=20
Example :
a=10 #integer
b=1.25 #float
c=1+6j #complex
As shown in above example we can assign multiple variables with same value or
multiple variables with multiple values.
Memory Management:
Python supports memory management automatically. Here we no need to allocate memory or deallocate
memory in manual way. In python we no need to declare the variables with datatypes. Whenever values are
assigned to the variables, corresponding data types will be decided and memory also allocated according to the
type. If you want to deallocate memory manually we can do that with ‘del’ statement.
Python deallocate the variables from memory, which are not in use. This process is called as Garbage
Collection.
Python Objects:
As python is object oriented language, every construct (variables etc.,) will be considered as an object.
NUMBERS IN PYTHON
Python numbers are immutable. That means new memory locations are allocated on changing the values
of numbers every time. Once a value is assigned in a memory location we can’t change the value.
Plain Integers :
It is universal integer type. We can assign decimal or octal or hexadecimal values to the variables.
Example :
X = 10 #decimals
long :
Whenever we want to work with large numbers then long type will be preferred and there will
be no ranges for the datatypes. The limit is virtual memory limit only. That means we can store a long
value as big as it occupies our full virtual memory space.
This can store double precision decimal values. In this we can store normal decimal point values
or exponent values also.
Example:
X = 1.25
Y = 1.45E+12
Z = float(10)
Complex Numbers :
Example:
x = 1+2j
#integers
x=4
y=5
print (x+y)
Output
Control statements in python are quite different in syntax when we compared with other languages.
If condition :
If condition:
Statement1
Statement2
elif condittion2:
Statement1
Statement2
else:
Statements
Example :
if x==15:
print("value is 15")
elif x<15:
print("x value less than 15");
else:
print("x value is greater than 15")
Output
for loop :
for loop in python uses range function. range(5) indicates 0 to 4. range(5,10) indicates 5 to 9.
range(0,10,3) indicates 0,3,6,9 (it starts from 0 and increments its value by 3 every time until the value reaches 10).
Syntax:
for i in range(n):
statements
Example:
Output:
Example2:
Output
We can run a for loop on lists also
Syntax:
for i in listname:
statements
Example 3:
Output
break statement:
Example
As the below output shows whenever condition met control terminated from the loop. That is why we are unable
to see the I values after 3.
Output:
continue statement:
Example:
Output:
As output show continue will skip the only iteration that meets the condition. That is why only printing the value 3
is skipped and loop continued from i=4.
pass statement :
Generally pass statement do nothing. This statement will be useful in some blocks that insists us to write
at least one statement but programmatically we don’t want to write any statement including print statement.
For example consider the following example where we want to print some value in all cases except I value is 3;
Example:
Output
Consider above example. I want to print I value in all cases except I value is 3. But whenever we write if condition if
expects at least one statement. So we wrote the pass statement here. So whenever i value is 3 then it does
nothing. In all other cases in prints the i value.
SEQUENCES IN PYTHON
Sequences allow us to store elements in a particular order and we can access those elements by using
their index.
1) Strings
2) Lists
3) Tuples
Strings:
Collection of characters is said to be a string. In python strings are case sensitive. So the variable ‘s’ is
different from variable ‘S’.
s = “ Python Tutorials”
s = ‘ Python Tutorials‘
Example:
Output
In python strings are immutable. That means we can’t change the value of a memory location related to an string
object. Every time we change the value, then a new memory location is allotted and that new reference is pointed
by the string object.
del cname;
We can retrieve the substring between index 0 to 4 as cname[0:5] where 0 is inclusive and 5 is exclusive
Example:
Output:
As shown in above example, string indexing starts from 0. And in the same way negative indexing (from -1) starts
from right to left as shown below.
s = "abcd"
-4 -3 -2 -1 Negative indexing
s= a b c d
0 1 2 3 Positive indexing
len method : We can calculate length of a string in python by using len method as follows.
output:
max(string) :
min(string) :
example
name="Python Tutorials"
print ("minimum of string name is :",min(name))
Output:
As character y has highest ASCII value among others in cname and b has small ASCII in name, these two were
returned.
string.capitalize()
string.center(width)
Returns a centered string and sets the total length of the string to given width.
endswith(substr,beg=0,end=len(string))
find(substr,beg,end)
Searches the string for a specified value and returns the position of where it was found
isalnum()
isalpha()
isdecimal()
isdigit()
islower()
Output:
Lists:
List is a collection which is ordered and changeable. Lists always allow storing duplicate elements. Lists
are also one type of sequences.
One more important point is list can store set of objects which are of different type. That means we can
store values that are belonged to different data types in the same list. We can insert, remove elements from the
list as we want.
s = [1,2,3,4,5,"Python Tutorials"]
we can update elements by assigning new value in place of existing one with the help of index as follows.
s[1] = 10
Above statement will replaces the element at index 1 in list s with the value 10 so new list becomes
s = [1,10,[3.5,4.2]]
del s[2]
Above statement removes 3rd element (element at index 2) from the list.
Example:
Output:
In above output last print statement returns error because we removed entire list by using del command and then
we are trying to print the list which does not exists. so it returns not defined error.
Operators on List:
We can apply different operators on lists to check where two lists are equal or not, whether one list is
greater than or less than the other list or not etc.,
> operator is used to check whether the first list is greater than second list or not]
< operator is used to check whether the first list is less than the second list or not
Membership operators (in, not in): These are used to check whether an item exists in list or not. in checks whether
the specified list item exists in the list or not, not in checks whether the list item does not exists in list or not
Concatenating Lists (+): We can concatenate two lists by using the concatenate operator +
Repetition Operator (*) : We can use the repetition operator to repeat all the elements of the list for the
specified number of times.
Example:
list.index(obj) : Returns the index of the first element with the specified value
s.append(10)
print("list after appended 10:",s)
s.insert(1,15)
print("list after inserted 15 is:",s)
s.reverse()
print("list after applied reverse method:",s)
Output
Tuples: ( )
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round
brackets.
It is also called as read only list which means both list and tuple are same with a small difference that once
a tuple is created with elements, we can’t update the elements.
Example:
s=(10,20,30)
Example Program
s[0]=2
Output
Above program returned error because we are trying to update the value of a tuple’s element which is not
possible.
DICTIONARIES IN PYTHON
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written
with curly brackets, and they have keys and values.
Dictionary stores the elements in key-value pairs. We can access the elements by using keys. and
Dictionaries are mutable which means we can update the elements any number of times.
We can insert elements at any time to the existing dictionary by using key value pairs as follows
del x['country']
We can remove all elements from the dictionary by using clear() method
x.clear()
We can delete the entire dictionary also by using del statement as follows
del x
Example Program
#adding element
x['mentor']= 'Sushal'
print("Dictionary after added element is:",x)
#removing element
del x['country']
print("Dictionary after removed element is:",x)
Output
FUNCTIONS IN PYTHON
A function is a block of code which only runs when it is called. You can pass data, known as parameters,
into a function. A function can return data as a result.
statement1
statement2
Example :
def sum(a,b):
print (a+b)
functions will be executed only whenever they are called. we can call the function as
Example Program:
#function definition
def sayhello():
print ("Hello Welcome to python Functions concept by PTS")
#function calling
sayhello()
Output:
In the above example we can pass the arguments also.
#function definition
def sayhello(name,course):
print ("Hello ",name,", Welcome to ",course," by PTS")
#function calling
sayhello("Sushal","Python")
sayhello("Deva","Java")
above function only will be called whenever we call with proper arguments that means sayhello will be executed
only whenever we call with two argument values.
Output:
functionname(argument1=value1,argument2=value2):
statements
Example:
#function definition
def sayhello(name="Sushal",course="Python"):
print ("Hello ",name,", Welcome to ",course," by PTS")
#function calling
sayhello()
sayhello("Deva","Java")
Output:
In the above example please observe in first function calling, sayhello function is called without
arguments. In this type of situations python will consider the default values Sushal & Deva which are provided in
function definition. Whenever we are passing values then these passed values will be considered.
Lambda Functions :
lambda arg1,arg2:statements
def f(arg1,arg2):
return arg1+arg2
Example :
print(f(10,20))
Please observe that the lambda function is assigned to variable f as lambda functions does not have any name.
Whenever we call this lambda function we can call with associated name ' f '.
Output: