PP Unit-1 Material
PP Unit-1 Material
Unit-1(PART-1)
Introduction to Python:
• High Level language: python is in English. So, we can write and understand very easily.
• Interpreted language: python script is processed at runtime by the interpreter(without any
compilation we can the python script )
• Interactive language: we can easily interact with the interpreter to write and run our python script
• Object Oriented: python is an object oriented, it supports all object oriented concepts like classes,
object, inheritance, exception handling and many other.
• Scripting Language: python is a scripting language
[Scripting language: it is a computer language with the series of commands within a file that
capable of being executed without being compile]
Applications of Python:
python is very powerful and it is used to develop Software ,Web and Internet based applications,
Desktop based application, Graphic design, Scientific and computational applications, Image processing,
Text processing and Enterprise level applications and many other.
• Python is used to build 3D software: By using maya tool 3D softwares will build.
Example:
Quora, Google App, Odoo
• Python is used to develop GUI based Desktop applications using following tools
WxPython
Pyqt
Pygtk
• Python is used for Image Processing and python have following tools for doing image
processing
2D: Python has many packages/tools for 2D which are as follows
Inkscape
GIMP
PaintshopPro
Scribus
• Python is used to develop games and tools useful to develop games is as follow
PyGame
PySoy
Example:
Civilization-IV, Disney’s toon town online, Vega Strike
• Operating system:
Ubuntu----Ubiquity installer
Fedora----Red Hat
Linux----Anaconda Installer
• Language Development:
Python design and module architecture is used to develop other languages like BOO, Apple swift,
coffee Script, cobra, ocaml
• Python is used for mathematics , science and engineering people(TOOL NAME: Scipy)
• Python is used for Teaching: It is perfect language for teaching programs at the inductory as well
as advanced level
Input-Processing-Output:
• Input: Any information or data sent to a computer for processing is considered input. Input or user
input is sent to a computer using an input devices.
• Processing: Work being done in program
• Output: Any information that is processed by and sent out from a computer or other electronic
device is considered output.
Example:
Question: Write a Program to add two numbers?
Program:
a=int(input(“Enter a ”))
b=int(input(“Enter b”))
c=a+b
print(c)
For above Programs,
Input: let any two integers a,b
Processing: c=a+b
Output: c
Program Development Cycle is a process that consists of a series of planned activities to develop a
Program.
REPL: REPL stands for Read–Eval–Print Loop and is an interactive computer programming
environment that READ single user input, EVALUATE them, and PRINT the result. And the script
written in a REPL environment is executed piecewise.
• To enter into interactive REPL shell type python command in command prompt
vahida@vahida-HP-Notebook:~$ python
Python 2.7.11+ (default, Apr 17 2016, 14:00:29)
Type "help", "copyright", "credits" or "license" for more information.
>>>
• Three greater than symbols (>>>) are used to indicate that we are inside a shell or an interpreter and
it is wait for our instruction.
Example:
vahida@vahida-HP-Notebook:~$ python
Python 2.7.11+ (default, Apr 17 2016, 14:00:29)
Type "help", "copyright", "credits" or "license" for more information.
>>> print ("Hello Python World")
Hello Python World
>>> 2+3
5
>>> x=10
>>> y=20
>>> x+y
30
>>>
Python Identifiers: An identifier is a name given to entities like variables, functions, class, modules and
others objects in the python.
c/c++/java: c/c++/java are termed as static typed language because before using any variable we need to
specify explicitly what type of date variable will hold by variable declaration.
Example:
int a=10,b=20,c;
c=a+b;
print(c)
python: python is a dynamic typed language. So, No need to specify explicitly what type of data each
variable holds.
Example:
a=10
b=20
c=a+b
print(c)
Literals:
➢ A literal is a notation for representing a fixed value in source code.
➢ In other words, which type of data we are storing into a variable is treated as literal in python
Python supports following literals
• Int literals:
Example: a=0,b=1,c=2,d=-1,e=-2
• Float literals:
Example: x=3.12,z=6.77893456
• Complex literals: (a+bj)
Example: s=1+12j
• Boolean literals:
Example: status1=True,status2=False
• Special literals:
Example: a=None
• List literal:
Example: a=[10,20,30,40,50,60]
• tuple literal:
Example: a=(10,20,30,40,50,60,10)
• Set literal :
Example: s={10,20,30,40,50,60,10}
• Dictionary literal:
Example: d={key1:value1,key2:value2…}
student_details={1:”ramu”,2:”raju”,3:”suma”}
Assignment: Assignment is associating a name to a value (name=value). The associated name is usually
called a variable.
Case 1: if we try to use a name that is not associated with any value, python gives an error message.
Example:
>>> b
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'b' is not defined
>>> b = 4
>>> b
4
Case 2: If you re-assign a different value to an existing variable, the new value overwrites the old value.
Example:
>>> x = 4
>>> x
4
>>> x = 'hello'
>>> x
'hello'
Example:
>>> a, b = 1, 2
>>> a
1
>>> b
2
>>> a + b
3
Note:
When executing assignments, python evaluates the right hand side first and then assign these vales to
the variable specified in the left hand side
Keywords:
In Every programming language there are certain words which have a pre-defined meaning, Those words
are called keywords or reserve words. We can’t change its meaning and We can’t be used as an identifier.
Python have following keywords.
And Del from not while
As Elif global or with
Assert Else If pass yield
Break Except import print
Class Exec In raise
continue finally Is return
Def For lambda try
Indentation:
Python forces the user to program in a structured format. Code blocks are determined by the amount
of indentation used. In python, indentation is used to represent start and end of each code block Statements
which go together must have the same indentation. Wrong indentation can give error .For code block use
four spaces for indentation (recommended).
Example without indentation
Script:
print ("hai")
print ("welcome to Python")
C:\Users\HP-PC>python indent.py
File "indent.py", line 2
print("welcome to Python")
^
IndentationError: unexpected indent
Example with indentation
Script:
print("hai")
print("welcome to Python")
C:\Users\HP-PC>python indent.py
Hai
Welcome to Python
Input and Output:
Example:
print(“hai welcome to python lab”)
(or)
print(‘hai welcome to python lab’)
Result : hai welcome to python lab
Syntax:
print (vn1, vn2, vn3,…….)
Example:
x=10
y=20
print(x,y)
Result:10 20
Example:
x=10
y=20
print("sum of x and y is",x+y)
Result:
sum of x and y is 30
variable=input(“message here”)
Example:
x=int(input(“enter x value”))
y=int(input(“enter y value”))
print("sum of x and y is",x+y)
result:
enter x value10
enter y value20
sum of x and y is 30
Comments in Python:
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments will be ignored at the time of program execution.
Single Line Comment:
The line which start with # is treated as single line comment in python.
Multiline Comment:
Multi line comment starts with """(three double quotes) and ends with """(three double quotes).
Example:
Example:
a = float (input (“enter a number”))
b= float (input (“enter b value “))
print (“Addition of “,a,” and “, b,” is “,a+b)
print (“Subtraction of “,a,” and “,b,” is “,a-b)
print(“Product of “,a,” and “,b,” is “,a*b)
print (“Division of “,a,” and “,b,” is “,a/b)
print(“Modulus division of “,b,” and “,a,” is “,b%a)
print(“Floor division of “,a,” and “,b,” is “,a//b)
print(“Exponent of “,a,” and “,b,” is “,a**b)
Comparison Operator: (Relational Operators):
• It is used to compare the values on its either sides (Left and Right) of the operator and
determines the relation between them.
• Let a = 100, b = 200
== It returns true if the two values on either side of the operator a==b FALSE
are exactly same
!= It returns true if the two values on either side of the operator a!=b TRUE
are not same
< It returns true if the value at LHS of the operator is less than a<b TRUE
the value at the RHS of the operator, otherwise false
> It returns true if the value at LHS of the operator is greater a>b FALSE
than the value at the RHS of the operator, otherwise false
<= It returns true if the value at LHS of the operator is less than a<=b TRUE
or equal to the value at the RHS of the operator, otherwise
false
>= It returns true if the value at LHS of the operator is greater a>=b FALSE
than or equal to the value at the RHS of the operator,
otherwise false
Example:
a = float(input(“Enter the value of a: “))
b = float(input(“Enter the value of b: “))
print(a,” == “,b,a==b)
print(a,” != “,b,a!=b)
print(a,” < “,b,a<b)
print(a,” > “,b,a>b)
print(a,” <= “,b,a<=b)
print(a,” >= “,b,a>=b)
Assignment and In place OR shortcut operators
Assignment Operator: It is used to assign a value to the operand.
Syntax: variablename=value
variablename=Expression
In place Operator:
In place operators are called as shortcut operators that includes +=,-=, *=, /=, %=, //=, **= allow
you to write code like num = num + 10 more concisely as num+ = 3
Operator Description Example
= Assign right side value to the left hand side variable a=b
+= Add and assign a+=b=> a=a+b
-= Subtract and assign a-=b=> a=a-b
*= Multiply and assign a*=b=> a=a*b
/= Divide and assign a/=b=> a=a/b
%= Modulus and assign a%=b=> a=a%b
//= Floor division and assign a//=b=> a=a//b
**= Exponent and assign a**=b=> a=a**b
Example:
str1 = “Good ”
str2 = “Morning”
str1+str2
T T T
T F F
F T F
F F F
Example:
Let a = 10, b = 20, c = 30, d = 40
(a<d) and (b>c)
(True) && (False)
Result = False
Logical OR (or): If one or both the expressions is true then the whole expression is true.
Truth Table:
T T T
T F T
F T T
F F F
• Logical NOT operator takes a single expression and negates the value of expression.
• Logical NOT produces a zero if the expression evaluates to a non-zero and produces 1 if the
expression produces zero.
Truth Table:
Expression !(Expression)
T (1) F (0)
F (0) T (1)
Bitwise Operators: Bitwise Operators perform operations at bit level. These operators include
1. Bitwise AND (&)
2. Bitwise OR (|)
3. Bitwise NOT (~)
4. Bitwise XOR (^)
5. Bitwise Shift
Bitwise operators expect their operands to be of integers and track them as a sequence of bits.
Bitwise AND (&):
The bit in the first operand is Anded with the corresponding bit in the second operand. If both
the bits are 1 then the corresponding bit result is 1 and 0 otherwise.
Truth Table:
1 1 1
1 0 0
0 1 0
0 0 0
Example:
1010101010
&
1111010101
1010000000
Bitwise OR (|):
The bit in the first operand is Ored with the corresponding bit in the second operand. If either
of the bits are 1 then the corresponding bit result is 1 and 0 otherwise.
Truth Table:
1 1 1
1 0 1
0 1 1
0 0 0
Example:
1010101010
|
1111010101
1111111111
Bitwise XOR (^):
The bit in the first operand is XORed with the corresponding bit in the second operand. If one
of the bits is 1, then the corresponding bit result is 1 otherwise 0
Truth Table:
1 1 0
1 0 1
0 1 1
0 0 0
Example:
1010101010
^
1111010101
0101111111
Bit ~(Bit)
0 1
1 0
Example:
~ (1 0 1 0 1 0 1 0) = 0 1 0 1 0 1 0 1
Shift Operators:
0 0 0 1 1 0 0 1
X
LSB MSB
• Example 1: shift Left
x=3
x<<2
0 0 0 1 1 0 0 1
0
0 0 1 1 0 0 1 0 Vacant space is filled with zero
0 0 0 0 0 0 1 1
1
0 0 0 0 0 0 0 1
Vacant space is filled 1
with zero
Membership Operators:
Python supports two types of membership operators
• in
• not in
The names itself suggests that, test for membership in a sequence such as string, list, tuple.
In – The operator returns true if a variable is found in the specified sequence and false otherwise.
Example: a in nums - it returns one if ‘a’ is present in the nums
not in – The operator returns true if a variable is not found in the sequence.
Example: a not in nums - it returns 1 if ‘a’ is not present in the nums
Identity Operators:
These operators compare the memory locations of two objects. Python supports two types of
Identity Operators
Is operator: It returns true if operands (or) values on both sides of the operator point to the same
object and False otherwise.
Example: If a is b – it returns 1 if id (a) is same as id (b)
is not operator : It returns true if operands (or) values on both sides of the operator do not point to
the same object and False otherwise.
Example: If a is b – it returns 1 if id (a) is not same as id (b)
Operator Precedence and Associativity:
The following table is the list from higher precedence to lower precedence.
** Exponentiation
~, +, - Unary Operator
Expressions in Python:
• An expression is any logical combination of symbols (like variables, constants and operators)
that represent a value.
• Every language has some set of rules to define whether the expression is valid/invalid.
• In python, an expression must have at least have one operand can have one or more operators.
Example: a+b*c-5
In above expression
“ +, *, - “ are operators
“ a, b, c ” are operators
“ 5 “ is operators
• Valid Expression:
x = a/b
y = a*b
z = a^b
x = a>b
• Invalid Expressions: a+<y++
Types of Expression:
Infix expression: In this type of expression the operator is placed in between the operands
Example: a=b-c
Prefix expression: In this type of expression the operator is placed before the operands
Example: a=-bc
Post fix expression: In this type of expression the operator is placed after the operands
Example: a=bc-
Data types in Python: In Python, Variables can store data of different types. Python supports the
following data types:
Tuple Operations:
set: A set is mutable and an unordered collection of items with no duplicate values.
Example:
>>> s={10,20,30,40,50,10,50,20}
>>> s
{40, 10, 50, 20, 30}
>>> type(s)
<class 'set'>
Set operations:
• Length
• Membership
• Concatenation
• Min()
• Max()
• Sorted()
• comparision
Set Methods:
• add()
• update()
• remove()
• pop()
• discard()
• clear()
• issubset()
• issuperset()
• union()
• intesection()
Dictinaory:
• A dictionary is an unordered set of key-value pair.
• Each key is separated from its value by a colon (:), and consecutive items are separated by
commas.
• The entire items in a dictionary are enclosed in curly brackets ({ }).
Syntax: dictionary_name= {‘key1’:’value1’, ‘key2’:’value2’,………..}
Example: airports={'LHR':'Hearthrow',
'LAX':'Los angeles',
'SIN':'Changi',
'FRA':'Frankfrut',
'ORD':'O hare',
'BOM':'Chhatrapati shivaji‘ }
Type Conversion:
Process of Converting one type of object into another type of object.the following are predefined
functions used for type conversion.
• int()
• float()
• complex()
• str()
• ord()
• hex()
• oct()
• bin()
• list()
• tuple()
• set()
• dict()
Example:
>>> int(12.6)
12
>>> float(2)
2.0
>>> complex(1,2)
(1+2j)
>>> str(12)
'12'
>>> oct(123)
'0o173'
>>> bon(15)
>>> bin(15)
'0b1111'
>>> hex(37)
'0x25'
>>> ord('c')
99
Using Functions and modules:
Function:
A function is a block of code which which perform specific task.
Module:
A module is collection of variables, functions and classes.
Types of functions:
1. Built-in (or) Pre-defined functions
print(),input()
2. User-defined functions
Functions which are defined by user
Predefined function inside a module can be accessed using import statements.
Syntax 1: (This syntax will import all the functions inside a module)
import module-name
Example
import math
print(math.sqrt(25))
Syntax 2: (This syntax will import only specified functions inside a module)
from module-name import functions
Example:
from math import sqsssrt
print(math.sqrt(25))