Unit Ii Final
Unit Ii Final
2.1 Introduction
A Python program is read by a parser. Python was designed to
be a highly readable language. The syntax of the Python
programming language is the set of rules which defines how a
Python program will be written.
Need of Python
Python is an open source, object-oriented, high-level
powerful programming language.
Developed by Guido Van Rossum in the early 1990s. Named
after Monty Python
Python runs on many Operating Systems such as Unix, Mac,
and on Windows etc.
Python Program
Python programs are composed of modules
Modules contain statements
High-level Language:
Portable:
High level languages are portable, which means they are able to
run across all major hardware and software platforms with few or no
change in source code. Python is portable and can be used on Linux,
Windows, Macintosh, Solaris, FreeBSD, OS/2, Amiga, AROS, AS/400
and many more.
Object-Oriented: Python is a full-featured object-oriented
programming language, with features such as classes, inheritance,
objects, and overloading.
APPLICATIONS OF PYTHON
Python Definition
1. Web Development
2. Game Development
5. Desktop GUI
9. CAD Applications
Source Interpreter
Processing or Processing Output
Code
Intermediate
The first three lines contain information about the interpreter and the operating
system it is running on.
The last line >>> is a PROMPT(chevron)
The version number is 3.6.0. It begins with 2, if the version is python 2.
That indicates that the interpreter is ready to enter code. If the user types a line
of code and hits Enter, the interpreter displays the result.
Example :
>>>5+7
12
>>>print(“HELLO”)
HELLO
>>>num=10
>>>num=num/2
>>>print(num)
5.0
The interpreter mode is the mode where the scripted and finished .py files are run in the
python interpreter.
2.2.3 Debugging
Debugging is the process of finding and fixing the errors in your program.
Error:
An error can sometimes called a “bug” is anything in the code that prevents a program
from compiling and running correctly .
Types of error:
There are three types of error
Compile time error
Run time error
Logical error
Compile time error:
Errors that occur during compilation are called compile time error.
Compilation is nothing but the process the computer takes to convert a high level
programming language into machine language that the computer an understand.
It can be classified into two categories
1. Syntax error
2. Semantic error
1. Syntax error:
Syntax errors occur when rules of a programming language are misused.
Syntax refers to formal rules governing the construction of valid statements in a
language.
Example :
print(HELLO) //wrong syntax
print(“HELLO”) //correct syntax
2. Semantic error:
It occurs when statements are not meaningful.
Semantic refers to the set of rules which gives the meaning to a statement.
Example:
X*Y=Z
Logical error:
These are encountered when the program does not give he desired output due to
wrong logic of the program.
For example, assigning a value to the wrong variable may cause a series of
unexpected program errors.
Multiplying two numbers instead of adding them together may also produce
unwanted results. So these types of errors are referred to logical errors.
Runtime error:
Errors that occur during the execution of a program are called runtime errors.
Some runtime errors stops the execution of the program which is called “crashed” or
“abnormally terminated”.
(i) Integer
(ii) float
(iii) Boolean
(iv) String
(v) list
(i) Integers
Integers are whole number without decimal point. The integer (or
int) data type indicates values that are whole numbers. Integer can be
positive or negative values. Integer have unlimited size in python.
Example
>>> a = 6
>>> b = -25
>>> c = 9587
>>>print b
-25
>>> 1 + 2
3
>>> a=5
>>> type(a)
<type ‘int’>
(ii) Float
Example
>>> print(5 > 3)
True
>>> print ( 6 = = 6)
True
>>> print (5 < 3)
False
>>>test = (3 < 4)
<type ‘bool’>
Boolean operators
Boolean operations are performed using the and, or, and not
keywords in Python
‘and’ operator:
A B A and B
True True True
True False False
False False False
False False False
‘and’ operator:
A B A or B
True True True
True False True
False False True
False False False
‘not’ operator:
A not A
True False
False True
Example
String H E L L O
Positive 0 1 2 3 4
indexing
Negativ -5 -4 -3 -2 -1
e
indexing
Example:
>>>a=”Hello”
>>>a
Hello
<class ‘str’>
>>>a[0]
‘H’
>>>[-1]
‘o’
Escape sequence Characters
An escape character lets you use characters that are otherwise impossible to put
into a string. An escape character consists of a backslash
(\) followed by the character you want to add to the string.
Escape
Purpose Example
Characters
Prints single >>> print("India\'s")
\’
Quote India's
>>> print("India is \"our\"
Prints double
\” Country")
quotes
India is "our" Country
Prints TAB >>> print("hai\thello")
\t
Space hai hello
>>> print("hai\nhello")
Prints NEW
\n hai
line space
hello
Print Back >>> print("hai\\hello")
Slash hai\hello
(v) Lists:
Python offers a range of compound datatypes often referred to as sequences.
List is one of the most frequently used and very versatile datatype used in Python. In
Python programming, a list is created by placing all the items (elements) inside a
square bracket [ ], separated by commas(,). It can have any number of items and
they may be of different data types (integer, float, string etc.).
Example
Empty List
>>> list=[ ]
>>> list
[]
Integer List
>>> list1=[1,2,3]
>>> list1
[1, 2, 3]
List with mixed data types
>>> list2=[10,25.5,'Agnes']
>>> list2
[10, 25.5, 'Agnes']
List operations
>>> print(list1 + list2)
[1, 2, 3, 10, 25.5, 'Agnes']
>>> list3=['Agnes','10']
>>> print(list3 * 2)
['Agnes', '10', 'Agnes', '10']
Nested List
>>> list4=["Pavi",
[10,20,30],'Agnes']
>>> list4
['Pavi', [10, 20, 30], 'Agnes']
List Index
User can use the index operator [] to access an item in a list. Index starts from
0. So, a list having 5 elements will have index from 0 to 4.
Trying to access an element other than this will raise an Index Error. The index
must be an integer. We can’t use float or other types, if given means this will result
into Type Error.
Example
>>> list=[10,20,30,40,50]
>>> print(list[0])
10
>>> print(list[3])
40
>>> list=['a', 'b', 'c', 'd']
>>> list[3]
'd'
>>> list=['Pavi', 'Agnes', 'Priyanka']
>>> print(list[2])
Priyanka
>>> list4=["Pavithra",
[10,20,30],'Santhosh']
>>> list4[0]
'Pavithra'
>>> list4[0][0]
'P'
>>> list4[1][0]
10
>>> list4[2][0]
'S'
2.4 VARIABLES
A variable is a reserved memory location to store values. In other words a variable in
a program gives data to the computer to work on it. 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.
Every value in Python has a data type. Different data types in Python are Numbers,
List, Tuple, Strings, Dictionary, etc. Variables can be declared by any name which starts
with alphabet.
Rules for variables:
Variables can be a combination of letters in lower case (a to z) or upper case (A to Z)
or digits (0 to 9) or an underscore (_).
It can be of any length.
Example :
a, name, a12, A, A12, reg_no // these are valid variable declaration
Variable cannot start with a digit.
Keywords cannot be used as variables,
We cannot use special symbols like ! ,@,#,$,% etc.,
Keywords in Python:
Keywords are the reserved words in python.
We cannot use a keyword as variable name, function name or any other identifier.
Keywords are case sensitive.
Keyword Description
And Logical and
As Part of the with-as statement
Assert Assert that something true
Break Stop this loop right now
Class Define a class
Continue Continue the loop
Def Define a function
Del Delete from dictionary
Elif Else if condition
Else Else condition
Except For any exception, do this
Exec Run a string as python
Finally Ignore exceptions
For For loop
From Get specific parts of a module
Global Declaring a global variable
If If condition
Import Import a module part of for-loops
In Part of for-loops
Is Like = = to test equality
Lambda Anonymous function
Not Logical not
Or Logical or
Pass This block is empty
Print Print this string
Raise Raise an exception
Return Function return value
Try Try this block
While While loop
With With an expression
Yield Pause here and return to caller
All keywords should be written in lower case
>>> name="Pavi"
>>> print(name)
Pavi
>>> age=24
>>> print(age)
24
>>> skills=['C', 'C++', 'JAVA', 'PHP']
>>> print(skills)
['C', 'C++', 'JAVA', 'PHP']
Here, name, age and skills are variables used in Python interactive mode.
There are two types of variables: global variables and local variables. A global
variable can be reached anywhere in the code, a local only in the scope.
Local variable:
Variables that are defined inside a function body.It can be accessed only inside
the function.
Global variable:
Variable that are defined outside a function body.It can be accessed by all the
functions of program.
[
A global variable (x) can be reached and modified anywhere in the code, local
variable (z) exists only in block 3.
In Python use the same variable for rest of the program or module and declare it
global variable, while if want to use the variable in a specific function or method you use
local variable.
Operations on variables:
1. Delete a variable
Python support delete operation of variable used in the program. Keyword used to
delete the variable is “del”. This delete the variable from the memory space, when user
print or use the deleted variable it gives error message.
Example
>>> a=10
>>> print(a)
10
>>> del a
>>> print(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined, 'PHP']
2. Swap variables
Python swap values in a single line and this applies to all objects in python.
Syntax :
Example
>>> a=10
>>> b=20
>>> print(a)
10
>>> print(b)
20
>>> a,b = b,a
>>> print(a)
20
>>> print(b)
10
2.5 Expression
An expression is a combination of values, variables, and operators. If user types an
expression on the command line, the interpreter evaluates it and displays the result.
>>> x=10
>>> x=x+5 //Expression
>>> x
15
>>> 10+30 //Expression
40
2.6 STATEMENTS
A statement is a unit of code that the Python interpreter can execute. A statement is
an instruction that the Python interpreter can execute. There are two kinds of statements:
print and assignment.
When you type a statement in interactive mode, the interpreter executes it and
displays the result, if there is one.
A script usually contains a sequence of statements. If there is more than one
statement, the results appear one at a time as the statements execute.
Example
print(1) //Print statement
x=10 //Assignment statement
print(x)
OUTPUT
1
10
Multi-line statement
>>> a=1+2+3+\
... 4+5+6+\
... 7+8+9
>>> a
45
>>> a=(1+2+3+
... 4+5+6+
... 7+8+9)
>>> a
45
>>> a=[1+2+3+
... 4+5+6+
... 7+8+9]
>>> a
[45]
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block
of code. Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the
first un-indented line. The amount of indentation is up to you, but it must be consistent
throughout that block.
Generally four whitespaces are used for indentation and is preferred over tabs.
Example
for i in range(1,11):
print(i)
if i == 5:
break
2.7 TUPLE ASSIGNMENT
A tuple is a sequence of immutable Python objects. Tuples are sequences of elements
of different types, just like lists. The differences between tuples and lists are, the values of
tuples cannot be changed but values of list can be updated. Tuples use parentheses “( )”,
whereas lists use square brackets “[ ]”.
Creating a tuple is as simple as putting different comma-separated values. Optionally
you can put these comma-separated values between parentheses also. Python has a very
powerful tuple assignment feature that allows a tuple of variables on the left of an
assignment to be assigned values from a tuple on the right of the assignment.
Example
>>> tup=(10,20,30)
>>> print(tup)
(10, 20, 30)
>>> tup2=('a','b','c')
>>> tup2
('a', 'b', 'c')
>>> tup3=("prema","latha","ravi")
>>> tup3
('prema', 'latha', 'ravi')
>>> tup4=(10,20.5,'a',"prema")
>>> tup4
(10, 20.5, 'a', 'prema')
Tuple operation
>>> tup + tup2
//Concatenation
(10, 20, 30, 'a', 'b', 'c')
>>> tup * 2 //Repetition
(10, 20, 30, 10, 20, 30)
>>> tup[0]
10
Basic Tuples Operations
Tuples respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new tuple, not a string.
TUPLE LIST
Tuple is collection of different List is collection of different
data type values data type values
Tuple defined using parenthesis List defined using square
“( )” brackets “[ ]”
Tuples are immutable Lists are mutable
Values of tuple cannot be Values of list can be
changed or updated changed or updated
>>> tup=(10,20,30) >>> list=[10,20,30]
>>> print(tup) >>> print(list)
(10, 20, 30) [10, 20, 30]
>>> tup[1]=40 >>> list[1]=40
Traceback (most recent call last): >>> print(list)
File "<stdin>", line 1, in [10, 40, 30]
<module>
TypeError: 'tuple' object does not
support item assignment
2.8 PRECEDENCE OF OPERATORS
Python support various operators to perform mathematical operation. Basic operators in
python are Addition, Subtraction, Multiplication, Division, Exponent etc. When more than one
operator occurs in an expression, the order of the evaluation depends on the rules of
precedence. Python follow mathematical convention acronym PEMDAS. The precedence is
used to determine how an expression involving more than one operator is evaluated.
Operators with highest level of precedence are evaluated first. When operators of the
same precedence occur in same expression, then it is evaluated from left to right.
P Parenthesis First
Exponents (include power, square
E
root)
MD Multiplication and Division (left-right)
AS Addition and Subtraction (left-right)
Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary mi- nus, Bitwise NOT
*, /, % Multiplication, Division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <,
Comparison,
<=
is, is not, in, not in Identity, Membership operators
Not Logical NOT
And Logical AND
Or Logical OR
Hierarchy of operators in Python
1. Expression within parenthesis is evaluated first. If more than one parenthesis occurs in
same expression, then inner most parenthesis is evaluated first.
2. Unary operators are evaluated.
3. Then priority is given for multiplication and division. If both operators occur is same
expression, then it is evaluated from left to right.
4. Next addition and subtraction is performed from left to right.
5. Relational operators evaluated next.
6. Logical operations performed
7. Finally assignment operator is carried out.
Example
Multiplication and Division have equal priority. If both operators occur is same
expression it can be evaluated from left to right.
>>> 25/5*2
10.0
>>> 50*2/4
25.0
3. Multiplication and other operators (+,-)
>>> 5*2+6*3
28
>>> 2+7*4-5
25
>>> 100+25-50+5
80
>>> 2+3-5+8-4+2-9
-3
>>> (2+8)*(5-2)+(8*3)
54
Answer=(2+8)*(5-2)+(8*3)
= 10*3+24
= 30+24
= 54
Example
>>> 17/2%2*3**3
13.5
Answer = 17/2%2*3**3
= 17/2%2*27
= 8.5%2*27
= 0.5*27
= 13.5
2.9 COMMENTS
Comment line is a statement which is not interpreted during the execution of the
program. Comment line is ignored during the program execution. Comments are used
mainly for the end users to understand the logic of the program.
Comments are very important while writing a program. It describes what's going on
inside a program so that a person looking at the source code does not take more time to
understand the logic.
In Python, the hash (#) symbol is used to start writing a comment. It extends up to
the newline character. Comments are for programmers for better understanding of a
program. Python Interpreter ignores comment.
Example
Multiline comment
If we have comments that extend multiple lines, one way of doing it is to use hash
(#) in the beginning of each line.
Example
Another way of doing this is to use triple quotes, either single quotation
(''') or double quotation ("""). These triple quotes are generally used for multi-line strings.
But they can be used as multi-line comment as well.
Example
Program 1:
Program 2:
def circulate(A,N):
For(I in range(1,N+1):
B=A[i:]+A[:i]
print(“Circulation”,i,”=”,B)
return
X=[91,92,93,94,95,96]
Y=int(input(“Enter Y:”)) #circulating count
circulate(X,Y)
OUTPUT
Enter Y : 3
Circulation 1= 92,93,94,95,96,91
Circulation 2= 93,94,95,96,91,92
Circulation 2= 94,95,96,91,92,93
Program 3:
import math
x1=int(input("Enter value of x1:"))
x2=int(input("Enter value of x2:"))
y1=int(input("Enter value of y1:"))
y2=int(input("Enter value of y2:"))
distance=math.sqrt((x2-x1)**2+(y2-y1)**2))
print(“Distance between two points=”,distance)
OUTPUT
Enter value of x1:5
Enter value of x2:3
Enter value of y1:4
Enter value of y2:5
Distance between two points=2.23606797749979
Additional Program
Output
G:\PYTHON\PROGRAM>python leap.py
Enter year to be checked:2017
The year isn't a leap year!
G:\PYTHON\PROGRAM>python leap.py
Enter year to be checked:2016
The year is a leap year!
UNIT II
2 MARKS
1. Definepython
Python is an object-oriented, high level language, interpreted, dynamic and
multipurpose programming language.
In immediate mode, you type Python expressions into the Python Interpreter
window, and the interpreter immediately shows the result.
Alternatively, you can write a program in a file and use the interpreter to
execute the contents of the file. Such a file is called a script. Scripts have
the advantage that they can be saved to disk, printed, and so on.
a
b
c
d
9. What is tuple ? What is the difference between list and tuple?
A tuple is another sequence data type that is similar to the list. A tuple
consists of a number of values separated by commas.
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. Eg:
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operator
Logical Operators
Bitwise Operators
Membership Operators
Identity Operator
PART B