+ All Categories
Home > Documents > Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4...

Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4...

Date post: 21-Jul-2020
Category:
Upload: others
View: 12 times
Download: 0 times
Share this document with a friend
27
Unit 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic language. ii) Easy to Learn iii) Free and Open Source Python is Free and Open Source Software (FOSS). We can freely distribute copies of this software, read it's source code, make changes to it and use pieces of it in new free programs. iv) High-level Language When we write programs in Python we need not bother about the low-level details such as managing the memory used by our program, etc. v) Portable Due to its open-source nature, Python has become portable. It can work on many platforms like Linux, Windows, FreeBSD, Macintosh, Solaris etc vi) Interpreted Python does not need compilation. The source code is first translated into a byte code and then to machine language. vii) Object Oriented Python supports procedure-oriented programming as well as object-oriented programming. In procedure- oriented languages, the program is built around procedures or functions which are nothing but reusable pieces of programs.In object- oriented languages, the program is built around objects which combine data and functionality. viii) Extensible If you need a critical piece of code to run very fast or want to have some piece of algorithm not to be open, you can code that part of your program in C or C++ and then use them from your Python program. ix) Embeddable You can embed Python within your C/C++ programs to give 'scripting' capabilities for your program's users. x) Extensive Libraries The Python Standard Library is huge. It can help you do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, ftp, email etc 1
Transcript
Page 1: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

Unit – 4 : PYTHON 1. Explain the features of Python.

i) Simple

Python is a simple and minimalistic language.

ii) Easy to Learn

iii) Free and Open Source

Python is Free and Open Source Software (FOSS). We can freely

distribute copies of this software, read it's source code, make

changes to it and use pieces of it in new free programs.

iv) High-level Language

When we write programs in Python we need not bother about the low-level

details such as managing the memory used by our program, etc.

v) Portable

Due to its open-source nature, Python has become portable. It can

work on many platforms like Linux, Windows, FreeBSD, Macintosh,

Solaris etc

vi) Interpreted

Python does not need compilation. The source code is first translated into

a byte code and then to machine language.

vii) Object Oriented

Python supports procedure-oriented programming as well as object-oriented

programming. In procedure- oriented languages, the program is built around

procedures or functions which are nothing but reusable pieces of programs.In object-

oriented languages, the program is built around objects which combine data and

functionality.

viii) Extensible

If you need a critical piece of code to run very fast or want to have some

piece of algorithm not to be open, you can code that part of your program in C or

C++ and then use them from your Python program.

ix) Embeddable

You can embed Python within your C/C++ programs to give 'scripting' capabilities for

your program's users.

x) Extensive Libraries

The Python Standard Library is huge. It can help you do various things involving

regular expressions, documentation generation, unit testing, threading, databases, web

browsers, CGI, ftp, email etc

1

Page 2: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

2. How will you install Python on Windows?

i) Down load windows version of Python from the website python.org

ii) Simply double-click on its file icon.

iii) Answer Yes or Next at every prompt to perform a default install.

iv) The default install includes Python‘s documentation set and support for Tkinter GUIs,

shelve databases, and the IDLE development GUI. Click Next

v) Python 2.7 is normally installed in the directory C:\Python27. To change the

destination folder use browse and select the drive and folder.

vi) Python interpreter‘s default behaviour can be changed. To do this edit

configuration file in C:\Python27.

vii) To have a GUI environment use IDLE or other IDE.

3. How will you install Python on Linux?

i) On Linux, Python is available as a package of one or more RPM (Redhat Package

Manager) files. Download the appropriate RPM file package.

ii) Unpack the files.

iii) One RPM for Python configures its own build procedure automatically according to

the system on which it is being compiled.

iv) Another RPM adds support for Tkinter GUIs and the IDLE environment.

v) Use command line or IDLE IDE to execute Python.

4. Ex[plain the operators in Python.

Arithmetic Operators

Comparison (i.e., Relational) Operators

Assignment Operators

Logical Operators

Bitwise Operators

Membership Operators

Identity Operators

i) Arithmetic operators: Arithmetic operators used in Python are:

‗+‘ Addition - Adds values on either side of the operator. The other arithmetic operators

are, „-„ Subtraction , „*‟ Multiplication , „/‟ Division , „%‟ Modulus , „**‟ Exponent ,

„//‟ Floor Division ,

ii) Relational Operators-

„==‟ Checks if the value of two operands are equal or not, if yes then

2

Page 3: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

condition becomes true. The other operators are,

„!=‟ NotEqual, „>‟ Greater Than, „<‟ Less Than , „>=‟ Grater Than or Equal To „<=‟

Less Than or Equal To

iii) Assignment Operators

„=‟ Simple assignment operator, Assigns values from right side operands to

left side operand

Compound assignment operators:

„+=‟ Add AND assignment operator, It adds right operand to the left

operand and assign the result to left operand

„-=‟ Subtract AND assignment operator, „*=‟ Multiply AND assignment operator,

„/=‟ Divide AND assignment operator, „%=‟ Modulus AND assignment operator,

„**=‟ Exponent AND assignment operator, „//=‟ Floor Dividion and assigns a value,

iv) Bitwise operators

„&‟ Binary AND Operator , „|‟ Binary OR Operator

„^‟ Binary XOR Operator, „~‟ Binary Ones Complement Operator

„<<‟ Binary Left Shift Operator, „>>‟ Binary Right Shift Operator

v) Logical operators

„and‟ – Logical AND operator

„or‟- Logical OR Operator

‗not‟- Logical NOT Operator

vi) Membership operators

„in‟ - Evaluates to true if it finds a variable in the specified sequence and false

otherwise.

„not in‟-Evaluates to true if it does not finds a variable in the specified sequence .

vii) Identity operators

„is‟- Evaluates to true if the variables on either side of the operator point to

the same object and false otherwise.

„is not‟- Evaluates to false if the variables on either side of the operator

point to the same object and true otherwise

5. Explain the different data types (or variables) in

Python. Python has five standard data types.

Numbers

String

List

Tuple

3

Page 4: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

Dictionary

i) Numbers

Number data types store numeric values. They are immutable data types which mean

that changing the value of a number data type results in a newly allocated object.

Number objects are created when you assign a value to them. For example,

>>> X =5

Python supports four different numerical types:

int (signed integers) eg- 10

long (long integers eg-567839933L

float (floating point real values) eg – 18.78

complex (complex numbers) eg 5-7i

ii) String

String is a sequence of characters. The characters in the string are stored and

fetched by their relative position through indexing. The string is enclosed within single

quote or double quotes. For multi line string triple quotes are used.

>>>‗sjhglkj‘,

>>> ―sfjkjkfeui3m‖.

>>> ‗‘‘ it is a

Multi line string ‗‘‘

String is an immutable object. It cannot be changed in-place after it is created.

iii) List

List is a sequence of mixed type objects, enclosed by [ ] .The objects in the list are

stored and fetched by their relative position through indexing. List has no fixed size. List is

mutable. Hence it can be modified in-place by assignment to offsets as well as a variety of

list method calls. Eg,

>>> [3,‘addd‘, 98.7, 8+7i]

iv) Tuple

Tuple is a sequence of mixed type objects, enclosed by ( ). The objects in the tuple

are stored and fetched by their relative position through indexing.

A tuple has a fixed size. Hence it cannot be appended. Tuple is immutable. Hence it

cannot be modified by in- place assignments.

>>> (5,’k’, ‘jhgjljk’.6+9i) v) Dictionary

Dictionary is a collection of mixed type objects enclosed within { } with the format,

{key1:value1,key2:value2, key3:value3, ...}. Elements of the dictionary are fetched by their

keys. Dictionary is mutable. Hence in-place modification of elements can be performed by

assignment. Dictionary can grow and shrink. Eg,

Page 5: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

>>> {‗name‘: ‗Ram‘,‘age‘:65,‘job‘:‘driver‘}

6. Explain about strings in Python

String is a sequence of characters. The characters in the string are stored and

fetched by their relative position through indexing. The string is enclosed within single quote

or double quotes. For multi line string triple quotes are used. Eg,

>>>‗sjhglkj‘,

>>> ―sfjkjkfeui3m‖.

>>> ‗‘‘ it is a

String is an immutable object. It cannot be changed in-place after it is created.

Characters are fetched from the string using indexing. Indexing starts from the offset

value 0. For forward indexing the offset value is positive. For reverse indexing the offset

value is negative.

>>> s = ‗behappy‘

>>> s [0] # returns the fist item in s

‗b‘

>>> s [1] # returns second item from left

‗e‘

>>> s[-1] # last item from the end

‗y‘

>>> s[-2] # second to last item from the end

‗p‘

Slicing is extracting a section (slice) from the string in a single step.

>>> s[1:3] # returns slice of s from offsets 1 through 2 (not 3)

‗eh‘

>>> s[1:] # returns everything after the first item

‗ehappy‘

>>> s[:-1] #everything except the last

‗behapp‘

>>> s[1:-1] #substring without first and last items

‗ehapp‘

>>>s[::-1] $reverse string

‗yppaheb‘

5

Page 6: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

String methods

Methods are functions attached to the objects. Some of the string methods are:

>>> s = ‗beHappy‘

>>> s.upper()

# returns upper case of s

‗BEHAPPY‘

>>>s.lower()

#returns the lower case of s

‗behappy‘

>>>s.swapcase()

# converts upper to lower and vice versa

‗BEhAPPY‘

>>>s.find(‗h‘)

# Gives the offset of the substring

2

>>>s.replace(‗ha‘,‘haaaa‘)

# Replaces

another

the occurrence of a string with

‗behaaaappy‘

7. Explain about lists in Python.

List is a sequence of mixed type objects, enclosed by [ ] .The objects in the list are

stored and fetched by their relative position through indexing. List has no fixed size. List is

mutable. Hence it can be modified in-place by assignment to offsets as well as a variety of list

method calls. Eg,

>>> [3,‘addd‘, 98.7, 8+7i]

Indexing operation on lists:

Objects are fetched from the list using indexing. Indexing starts from the offset value

1. For forward indexing the offset value is positive. For reverse indexing the offset value

is negative.

>>> L= [20,‘hi‘,5+8i, 45.7, ‗getlast‘]

>>> L[0] # First item of the list

20

>>> L[1] # Second item of the list

‗hi‘

>>> L[-1] #Last item of the list

‗getlast‘

>>>L[-2] #Second item from the last

‘45.7‘

6

Page 7: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

Slicing operations on lists

Slicing is extracting a section (slice) from the list in a single step.

>>> L[1:3] # Slice of L from offset 1 through 2 (not 3)

[‗hi‘,5+8i]

>>>L[1:] #Everything after the first item

[‗‘hi‘,5+8i,45.7,‘getlast‘]

>>> L[:-1] #everything except the last

[20,‘hi‘,5+8i,45.7]

>>> L[1:-1] # sub list without first and last items

[‗hi‘,5+8i,45.7]

>>> L[::-1] # Reverse list

[‗getlast‘,45.7,5+8i,‘hi‘20]

List methods

Methods are functions attached to the objects. Some of the list methods are:

>>>L.append(‗you‘) # append( ) adds object at the end

>>>L

[20,‘hi‘5+8i,45.7,‘getlast‘,‘you‘].

>>>L.pop(2) # pop() deletes item at position 2

>>>L

[20,‘hi‘,45.7,‘getlast‘,‘you‘]

>>> L.sort() # sort () sorts in ascending order

>>> L

[20,45.7,‘getlast‘,‘hi‘,‘you‘]

>>> L.sort(reverse=True) # Sorting descending order, reverse- flag set

>>> L

[‗you‘,‘hi‘,‘getlast‘, 45.7, 20]

>>> L.shuffle() # shuffle () shuffles the items

>>> L

[‗getlast‘,‘you‘,45.7,20,‘hi‘]

>>> L.insert(1,1000)

#

insert() inserts an item , position First argument , item is

# second argument

>>>L

[‗getlast‘,1000,‘you‘45.7,20.‘hi‘]

7

Page 8: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

8. Explain about tuple in Python.

Tuple is a sequence of mixed type objects, enclosed by ( ). The objects in the tuple

are stored and fetched by their relative position through indexing. A tuple has a fixed size.

Hence it cannot be appended. Tuple is immutable. Hence it cannot be modified by in- place

assignments.

>>> (5,‘k‘, ‗jhgjljk‘.6+9i)

Indexing operations on Tuple

Objects are fetched from the tuple using indexing. Indexing starts from

the offset value 0. For forward indexing the offset value is positive. For reverse

indexing the offset value is negative.

>>> T= [20,‘hi‘,5+8i, 45.7, ‗getlast‘]

>>> T[0] # First item of the tuple

20

>>> T[1] #Second item of the tuple

‗hi‘

>>> T[-1] #Last item of the tuple

‗getlast‘

>>>T[-2] #Second item from the tuple

‘45.7‘

Slicing operations on tuples

>>> T[1:3] # Slice of T from offset 1 through 2 (not 3)

(hi‘,5+8i)

>>>T[1:] #Everything after the first item

(‘hi‘,5+8i,45.7,‘getlast‘)

>>> T[:-1] #everything except the last

(20,‘hi‘,5+8i,45.7)

>>> T[1:-1] # sub tuple without first and last items

(hi‘,5+8i,45.7)

>>> T[::-1] # Reverse tuple

(‗getlast‘,45.7,5+8i,‘hi‘,20)

Tuple methods

Methods are functions attached to the objects. As tuple is immutable it has

no method which will modify it. Tuple has the following methods:

8

Page 9: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

>>> T.index(45.7) # index() To find the index position of an item

3

>>> T=(1,2,3,4,5,6,7,3,3,3)

>>>> t.count(3)

# count() To find the number of occurrences of an item

4

9. Explain about dictionary in Python.

Dictionary is a collection of mixed type objects enclosed within { } with the format,

{key1:value1,key2:value2, key3:value3, ...}. Elements of the dictionary are fetched by

their keys. Dictionary is mutable. Hence in-place modification of elements can be

performed by assignment. Dictionary can grow and shrink. Eg,

>>> {‗name‘: ‗Ram‘,‘age‘:65,‘job‘:‘driver‘} Basic operations

on a dictionary:

D={‗a‘:‘apple‘,‘b‘:‘banana‘,‘c‘:‘chocolate‘,‘d‘:‘dosai‘,‘e‘:‘eggs‘}

>>> D[‗a‘] # to know the value of a key

‗ apple‘

>>> del D[‗b‘] # To delete a key

>>> D

{‗a‘:‘apple‘,‘c‘:‘chocolate‘,‘d‘:‘dosai‘,‘e‘:‘eggs‘}

>>>D[‗c‘] = ‗curd rice‘ # To edit a value

>>>D

{‗a‘:‘apple‘,‘c‘:‘curd rice‘,‘d‘:‘dosai‘,‘e‘:‘eggs‘}

>>>D[‗b‘] =‘biscuits‘ # To add a new item

{‗a‘:‘apple‘,‘b‘:‘biscuits‘,‘c‘:‘curd rice‘,‘d‘:‘dosai‘,‘e‘:‘eggs‘}

>>> ‗c‘ in D # To find the presence of a key

>>> ‗F‘ in D

False

Methods are functions attached to the objects. Some of the dictionary methods,

>>> D.keys() # keys() - To find all the keys

[‗a‘,‘b‘,‘c‘,‘d‘,‘e‘]

>>>D.values() # values() - To find all the values

[‗apple‘,‘biscuits‘,‘curd rice‘,‘dosai‘,‘eggs‘]

>>>D.has_key[‘c‘] # has_key() - Key membership test

True

9

Page 10: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

>>>D.get(‗c‘) # get() - To find the value of a key

‗curd rice‘

>>>D.get(‗f‘) # For a missing key nothing returned

None

>>>D.pop() # pop() - To delete an item from the end

‗e‘

>>>D

{‗a‘:‘apple‘,‘b‘:‘biscuits‘,‘c‘:‘curd rice‘,‘d‘:‘dosai‘ }

>>>D.pop(1) # To delete an item by position ‗b‘

>>>D

{‗a‘:‘apple‘,‘c‘:‘curd rice‘,‘d‘:‘dosai‘ }

>>>D.pop(‗a‘) # To delete an item by giving key

‗apple‘

>>>D

{‘c‘:‘curd rice‘,‘d‘:‘dosai‘ }

>>>D1={1:‘one‘,2:‘two‘,3:‘three‘,6:‘six‘}

>>>D2={4:‘four‘,5:‘five‘}

>>> D1.update(D2) #Update() function is used to concatenate

>>>D1

{1:‘one‘,2:‘two‘,3:‘three‘, 4:‘four‘,5:‘five‘, 6:‘six‘}

>>>D3={1:‘onlyone‘,7:‘seven‘}

>>> D1.update(D3) # update function overwrites the values of same

key

>>> D1

{1:‘onlyone‘,2:‘two‘,3:‘three‘, 4:‘four‘,5:‘five‘, 6:‘six‘,7:‘seven‘}

10. Explain about sets in Python.

To create a set object built in set function [set()] is used. Mathematical set

operations can be performed on set objects. Set () has one argument. The argument may

be any object string, list etc.

Basic operations on set

>>> x = set('abcde')

>>> y = set('bdxyz')

>>> x

set(['a', 'c', 'b', 'e', 'd'])

10

Page 11: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

>>> 'e' in x # Set membership

True

>>> x – y # Set difference; items in x but not in y

set(['a', 'c', 'e'])

>>> x | y # Set union; all items in either x or y

set(['a', 'c', 'b', 'e', 'd', 'y', 'x', 'z'])

>>> x & y # Set intersection; items common to both x and y

set(['b', 'd'])

Set Methods

>>> engineers = set([‗Arul‘,‘Balu‘,‘Ram‘,‘Sam‘])

>>> managers=set([‗Balu‘,‘Sam‘,‘Tom‘])

>>>engineers.add(‗suresh‘) # add() - To add an element to a set

>>>engineers

set(['Arul', 'Ram', 'suresh', 'Balu', 'Sam'])

>>>engineers.discard(‗suresh‘) # discard() - To remove an item from a set

>>>engineers

set(['Arul', 'Ram', 'Balu', 'Sam'])

>>>engineers.union(managers) #union() - To perform union on sets

>>>engineers

set(['Sam', 'Tom', 'Arul', 'Ram', 'Balu'])

>>>engineers.difference(managers) # difference() - To perform difference on

sets

>>> engineers

set(['Arul', 'Ram'])

>>> engineers.intersection(managers) # intersection ()To perform intersection on

sets

set(['Balu', 'Sam'])

11. Explain about the conditional statement in Python? [or] Explain about the IF statement

in Python.

The general format of IF statement is,

if <test1>:

<statements1>

elif <test2>:

<statements2>

else:

11

Page 12: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

<statements3

X=10;y=20

if x>y:

print 'X is big'

elif x<y:

print 'X is small'

else:

print 'Both are equal'

Rules :

i) If is a compound statement . The statements in the block following ‗if<test1> ‗ will be

executed if the < test1> is TRUE. If <test1> fails , elif<test2> will be tested. If

<test2>is FALSE, else part will be executed.

ii) ‗elif‘ and ‗else ‗ blocks are optional

iii) The tests <test1> and <test2> need not be parenthesised.

iv) If ,elif and else header lines should be terminated by colon.

v) If block, elif block and else block all should have proper indentation.

vi) Statements need not be terminated by semicolon.

vii) If there is a semicolon after a statement it is taken as a statement separator.

12. Explain about for loop in Python.

The complete format of for loop can be written as:

for <target> in <object>:

<statements>

if <test>: break

if <test>: continue

else:

<statements>

Rules:

i) In the header line for and in are keywords.

ii) Header line should be terminated with colon.

iii) A for loop can step across any kind of sequence object like string, list and tuple.

iv) The <target> refers to the each individual item in the object.

12

Page 13: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

v) A break statement with the conditional if statement is optional. If break is used and

it is hit, else block will be skipped.

vi) A continue statement with the conditional if statement is optional. If continue is hit,

the control goes to the top of the loop.

vii) If the loop is exited without hitting break statement, the else block will be executed

viii) For loop can be nested.

(e.g)

>>>items = ["aaa", 111, (4, 5), 2.01]

>>> tests = [(4, 5), 3.14]

>>> for key in tests:

... for item in items:

... if item == key:

... print key, "was found"

... break

... else:

... print key, "not found!"

...

(4, 5) was found

3.14 not found!

13. Explain about while loop in Python.

The general format of the while loop looks like this:

while <test1>:

<statements1>

if <test2>: break

if <test3>: continue

else:

<statements2>

Rules:

i) In the header line while is keyword.

ii) Header line should be terminated with colon.

iii) A while loop repeatedly executes a block of statements as long as the <test1> is TRUE.

iv) A break statement with the conditional if statement is optional. If break is used and it

is hit, else block will be skipped.

v) A continue statement with the conditional if statement is optional. If continue is hit,

13

Page 14: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

the control goes to the top of the loop.

vi) If the loop is exited without hitting break statement, the else block will be executed

vii) while loop can be nested.

(e.g)

>>> a=0; b=10

>>> while a < b:

... print a,

... a = a + 1

...

0 1 2 3 4 5 6 7 8 9

14. Explain about functions in Python.

i) In Python functions are written with def statement.

ii) ‘def’ statements can be nested within if statement, for loop, while loop and even

within other def statements.

iii) Syntax for function:

def <name>(arg1, arg2,... argN):

<statements>

return <value>

iv) The header line should be terminated with colon.

v) When def is executed, it creates a function object and assign it the <name>.

vi) The function name can be assigned another name

vii)The arguments are passed by assignments.

viii) The scope of a variable inside the function body is local. To make it global,

the ‗global‘ statement should be used.

ix) The function returns the value using return statement.

x) In Python a type of function called ‗generator‘ uses ‗yield‘ statement to send the value

And suspend its state to resume it later.

xi) After the def statement we can call the function with function name followed by

parenthesis. The parenthesis contains the arguments to be passed into the function.

(e.g)

>>> def intersect(seq1,

seq2): res = []

for x in seq1:

if x in seq2:

res.append(x)

14

Page 15: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

return res

>>>intersect(‗ram‘,‘raj)

.... [‗r‘,‘a‘]

15. Explain about file handling in Python.

i) In Python file objects are accessed by built in open function.

ii) Open () has at least two string arguments; Third argument is optional.

iii) Open () creates and returns file object.

iv) The syntax for open function is:

file1=open(‗myfile.txt‘,‘mode‘,[‗buffering‘]):

‗myfile.txt‘ => name of the file

‗mode‘ => ‗r‘ for reading, ‗w‘ for writing for txt file; ‗b‘ added for binary file ‗

buffering‘ => optional argument; ‗0‘ for non buffering, ‗1‘ for buffering File1

=> name of the file object

v) File header line with open() should be terminated by colon.

vi) Once a file object is created its methods are used to read/write the files.

vii) Text is read from the file as string. Text passed for writing in a file is also passed

as string.

viii) Some of the basic file operations are:

>>>output = open('/tmp/spam', 'w') #Create output file ('w' means write)

>>>input = open('data', 'r') #Create input file ('r' means read) >>>input =

open('data') #Same as prior line ('r' is the default) >>>aString = input.read( ) #

Read entire file into a single string >>>aString = input.read(N) #Read next N

bytes into a string

>>>aString = input.readline( ) #Read next line (including end-of-line marker) into a string

>>>aList = input.readlines( ) #Read entire file into list of line strings

>>>output.write(aString) #Write a string of bytes into file

>>>output.writelines(aList) # Write all line strings in a list into file

>>>output.close( ) #Manual close

>>>outout.flush( ) #Flush output buffer to disk without closing

>>>anyFile.seek(N) #Change file position to offset N for next operation

[E.g)

>>> myfile = open('myfile.txt', 'w')

>>> myfile.write('hello text file\n')

# Open for output (creates file) #

Write a line of text into the file

Page 16: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

15

Page 17: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

>>> myfile.close( )

>>> myfile = open('myfile.txt')

>>> myfile.readline( )

'hello text file\n'

# closing the file

# Open for input: 'r' is default

# Read the line back

#output

16. Explain about exception handling in Python.

In Python, exceptions are triggered automatically on errors, and can be triggered and

intercepted by your code. They are processed by the following four statements

try/except

Catch and recover from exceptions raised by Python, or by you.

try/finally

Perform cleanup actions, whether exceptions occur or not.

raise

Trigger an exception manually in your code.

assert

Conditionally trigger an exception in your code.

‗try‘ is a compound statement; its most complete form is given below. It starts with a

try header line, followed by a block of (usually) indented statements, then one or more

except clauses that identify exceptions to be caught, and an optional else clause at the

end. The words try, except, and else are associated by indenting them to the same level

(i.e., lining them up vertically). The general format:

try:

<statements>

# Run this action first

except <name1>:

<statements>

# Run if name1 is raised during try block

except <name2>, <data>:

<statements>

# Run if name2 is raised, and get extra data

except (name3, name4):

<statements>

# Run if any of these exceptions occur

except:

<statements>

# Run for all (other) exceptions raised

else:

<statements>

# Run if no exception was raised during try block

16

Page 18: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

When a try statement is started, Python marks the current program context so it

can return to it if an exception occurs. The statements nested under the try header are run

first. What happens next depends on whether exceptions are raised while the try block‘s

statements are running:

• If an exception does occur while the try block‘s statements are running, Python

jumps back to the try, and runs the statements under the first except clause that

matches the raised exception. Control resumes below the entire try statement after

the except block runs (unless the except block raises another exception).

• If an exception happens in the try block, and no except clause matches, the

exception is propagated up to a try that was entered earlier in the program, or

to the top level of the process (which makes Python kill the program and print a

default error message).

• If no exception occurs while the statements under the try header run,

Python runs the statements under the else line (if present), and control then

resumes below the entire try statement.

The other type of the try statement is a specialization that has to do with finalization

actions. If a finally clause is included in a try, Python will always run its block of

statements ―on the way out‖ of the try statement, whether an exception occurred

while the try block was running or not. Its general form is:

try:

<statements>

# Run this action first

finally:

<statements>

# Always run this code on the way out

With this variant, Python begins by running the statement block associated with the

try header line. What happens next depends on whether an exception occurs

during the try block:

If no exception occurs while the try block is running, Python jumps back to run

the finally block, and then continues execution past the entire try statement.

If an exception does occur during the try block‘s run, Python still comes back

and runs the finally block, but then propagates the exception up to a higher try

or the top-level default handler; the program does not resume execution

below the try statement. That is, the finally block is run even if an exception is

raised, but unlike an except, the finally does not terminate the exception—it

continues being raised after the finally block runs.

(eg)

17

Page 19: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

Let us have a function,

>>> def hunter(obj,index):

return obj[index]

>>>x=['rabbit', 'goat', 'lion']

>>>print hunter (x,2)

... Lion ...

#output

>>>print hunter (x,3)

Traceback (most recent call last):

#in built exception raised by Python

....................

IndexError: string index out of range

To catch this exception by code,

>>>try:

print hunter (x,3)

except IndexError:

print 'got exception'

print 'continuing'

# output:

... got exception

.... continuing

17. Explain about assignment and references in Python.

In Python before assignment variables need not be declared. When 3 is assigned to

‗a‘,

>>> a = 3

1. Create an object to represent the value 3.

2. Create the variable a, if it does not yet exist.

3. Link the variable a to the new object 3.

The net result will be a structure inside Python that is like shown in the fig.

Names References Objects

a 3

18

Page 20: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

As shown in the fig variables and objects are stored in different parts of memory,

and are associated by links (the link is shown as a pointer in the figure). Variables always

link to objects, and never to other variables, but larger objects may link to other objects (for

instance, a list object has links to the objects it contains).

These links from variables to objects are called references in Python.A reference is a

kind of association, implemented as a pointer in memory. Whenever the variables are later

used (i.e., referenced), Python automatically follows the variable to- object links. This is all

simpler than the terminology may imply. In concrete terms:

• Variables are entries in a system table, with spaces for links to objects.

• Objects are pieces of allocated memory, with enough space to represent the

values for which they stand.

• References are automatically followed pointers from variables to objects.

>>> a = 3

>>> b = a

Typing these two statements generates the scene shown in Fig. As before, the

second line causes Python to create the variable b; the variable a is being used and not

assigned here, so it is replaced with the object it references (3), and b is made to reference

that object. The net effect is that variables a and b referencing the same object (that is,

pointing to the same location of memory). This kind of multiple names referencing the

same object is called a shared reference in Python.

Names References Objects

a 3

b

18. Explain about equality and identity of objects.

In Python to check the equality in the values of the objects == operator is used. To

check the identity of two objects ‗is‘ operator is used.

‘ ==‘ Operator checks whether two referenced objects have the same value or

not. ‗is‘ operator checks whether both names point to the same object.

‗==‘ operator checks value equality.

‗is‘ operator checks object identity.

>>>L1=[1,2,3]

>>>L2=[1,2,3]

19

Page 21: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

>>>L1==L2, L1 is L2

....True, False

>>>L1=L2

# both L1 & L2 have same values, but they are different objects.

# Shared reference, L1 & L2 are same objects.

>>>L1==L2, L1 is L2

....True, True

19. Explain about list sorting.

Lists can be sorted using sorted() function or list.sort() method.

>>> L=[1,5,4,3,10]

>>> L.sort() ( or)

>>>L

sorted(L)

......[1,3,4,5,10]

To sort in reverse order,

>>>L=[1,5,4,3,10]

>>>L.sort(Reverse=True)

.>>>L

....[10,5,4,3,1]

If the data is of string type,

>>>L=[‗300‘,‘500‘,‘100‘,‘200‘]

>>>L.sort(Key=int)

>>>L

>>>[‗100‘,‘200‘,‘300‘,‘500‘]

20. Explain string formatting with tuple in Python.

>>> T=(500,50,5)

>>> ‗First Item:{:d},Second Item:{:d},and third item:{:d}.‘.format(*t)

.... First Item:500, Second Item:50, and Third Item:5

‗d‘ is the format code for integer. Similarly ‗f‘ and ‗s‘ codes can be used for

floating point values and strings respectively.

21. Explain about internal dictionary.

A dictionary can be nested with other dictionaries. (eg),

>>> rec = {'name': {'first': 'Bob', 'last': 'Smith'},

'job': ['dev', 'mgr'],

'age': 40.5}

Here, we have a three-key dictionary at the top (keys ―name,‖ ―job,‖

and ―age‖), The values are: a nested dictionary for the name

20

Page 22: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

to support multiple parts, a nested list for the job to support multiple roles and

age. We can access the components of this structure using dictionary keys.

>>> rec['name']

# 'Name' is a nested dictionary

{'last': 'Smith', 'first': 'Bob'}

>>> rec['name']['last']

# Index the nested dictionary

'Smith'

>>> rec['job']

# 'Job' is a nested list

['dev', 'mgr']

22. How will you make copies of dictionaries?

A dictionary (d) can be copied by using its copy method, d.copy(). To deep

copy compound objects the module copy can be used.

>>>import copy

>>> x = copy.copy(y)

# make a shallow copy of y

>>> x = copy.deepcopy(y) # make a deep copy of y

A shallow copy constructs a new compound object and then (to the extent

possible) inserts references into it to the objects found in the original.

import copy

old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

new_list = copy.copy(old_list)

old_list[1][1] = 'AA'

print("Old list:", old_list)

print("New list:", new_list)

output:

Old list: [[1, 1, 1], [2, 'AA', 2], [3, 3, 3]]

New list: [[1, 1, 1], [2, 'AA', 2], [3, 3, 3]]

A deep copy constructs a new compound object and then, recursively, inserts copies into

it of the objects found in the

original.

Page 23: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

23. What is limited size list in Python? What are Python arrays?

In Python list is a mutable object. It can be expanded and reduced. But to create

a fixed size empty list Python‘s None type can be used as follows:

>>>L=[None]*10

>>>L

.... [None, None, None, None, None, None, None, None, None, None]

>>>L[4]=‘hai‘

>>>L

......... [None, None, None, None,‘ hai‘, None, None, None, None, None]

Python has a special purpose data type called array. It is more like ‗C‘ array.

It is little used in Python.. To create,

>>> from array import array

>>> intarray=array(‗i‘) 21

Page 24: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

Type code (i) for integer, (f) for float, (s) for string.

24. What are persistent variables?

persistent variables are local to the function in which they are declared; yet their values

are retained in memory between calls to the function. Persistent variables are similar to global

variables.

Any variable which is changed or created inside of a function is local, if it hasn‘t been

declared as a global variable. To tell Python, that we want to use the global variable, we have to

use the keyword “global”, as can be seen in the following example:

Example

def f(): global s print s s = "Look for Geeksforgeeks Python Section" print s # Global Scope s = "Python is great!" f() print s

Output:

Python is great!

Look for Geeksforgeeks Python Section.

Look for Geeksforgeeks Python Section.

25. What are Python sequences?

String, list and tuple are Pyhton sequences.

String is a sequence of characters. The characters in the string are stored and fetched by their

relative position through indexing. The string is enclosed within single quote or double quotes. For

multi line string triple quotes are used.

>>>‗sjhglkj‘,

List is a sequence of mixed type objects, enclosed by [ ] .The objects in the list are stored and

fetched by their relative position through indexing. List has no fixed size. List is mutable. Hence it can

be modified in-place by assignment to offsets as well as a variety of list method calls. Eg,

>>> [3,‘addd‘, 98.7, 8+7i]

Tuple is a sequence of mixed type objects, enclosed by ( ). The objects in the tuple are stored

and fetched by their relative position through indexing.

A tuple has a fixed size. Hence it cannot be appended. Tuple is immutable. Hence it cannot be

modified by in- place assignments.

>>> (5,’k’, ‘jhgjljk’.6+9i) *********************

22

Page 25: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

Lab Exercises

1. Using ‘for’ loops:

import random

#using a sequence-string

for letter in 'python':

print 'current letter:',letter fruits

= ['banana', 'apple', 'mango']

#using a sequence-list

for fruit in fruits:

print 'Current fruit :', fruit

#by using range---

for num in range(1,5):

print 'cuurnt num:',num

#by using sequence index'

fruits = ['banana', 'apple', 'mango']

for index in range(len(fruits)):

print 'Current fruit :', fruits[index]

''' To have result of for loop as a list....'''

print [x for x in range(1,9)]

''' To have result of for loop as a list with a condition...'''

print random.sample([x for x in range(1,9) if x % 2==0],1)

2. Find out the Armstrong numbers in a range

for x in range(100,1001):

y=str(x)

if x==int(y[0])**3+int(y[1])**3+int(y[2])**3:

print x

''' for x in range(100,1001):

if x==(x%10)**3+((x/10)%10)**3+(x//100)**3:

print x'''

3. Accept a string or sentence. Find out the count of each character in the string

while True:

string=raw_input("Enter the string:")

if not string:

break

else:

character_list=set(string)

for character in character_list:

print character, string.count(character)

4. Write a program to Count number of vowels in s entence:

sentence = ‘’My name is Raju. I am 27 years old. I am coming from Chennai."

low_sentence = sentence.lower() print (low_sentence) length = len(sentence) print length

# make counts for all the vowels a_count = low_sentence.count('a') e_count = low_sentence.count('e') i_count = low_sentence.count('i') o_count = low_sentence.count('o') u_count = low_sentence.count('u')

# print the counts

print("No of 'a': " + str(a_count)) print("No of 'e': " + str(e_count)) print("No of 'i': " + str(i_count)) print("No of 'o': " + str(o_count)) print("No of 'u': " + str(u_count))

23

Page 26: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

5. Capitalizing a sentence lines = [] while True:

s = raw_input() if s:

lines.append(s.upper()) else:

break; for sentence in lines:

print sentence

6. Convert Temperature from Fahrenheit to

Celsius and vice versa *:

while True: x=raw_input('Enter temperature:') if not x:

break if x[-1]== 'C' or x[-1]== 'c' and x[:-1].isdigit():

print 'your temp',x, '''in

Farenheit is''', str(float(x[:-1])*9/5+32)+'F'

elif x[-1]== 'F' or x[-1]== 'f' and x[:-1].isdigit(): print 'your temp',x,'in Centigrade is',str

((float(x[:-1])-32)*5/9)+'C'

else : print 'Enter temp in coreect format....'

7. Write a program to validate mobile/ landline Phone Numbers *:

import re

phone=re.compile

(r'0[1-9]\d{9}$')

mobile=re.compile(r'[^1-6]\d{9}$') while True:

p=raw_input("Enter contact

number") if not p:

break if phone.match(p):

print "your phone no "+p

elif mobile.match(p):

print "your mobile no " +p else :

print "invalid number"

8. Accept a string. Write a function to find it is palindrome or not.

def is_polyndrome(x):

rev=x[::-1]

if x==rev:

return (1)

else:

return (0)

print rev

x=raw_input("Enter string:")

if (is_polyndrome(x)):

print x + ' is palindrome'

else:

print x+'is not palindrome'

9. Write functions to print sum and product of numbers in a list. def sum(x):

sum=0

for i in x:

sum=int(i)+sum

print sum

def multiply(x):

prod=1

for i in x:

prod=int(i)*prod

print prod

x= raw_input("Enter the list:").split(',')

print x

sum(x)

multiply(x)

24

Page 27: Unit 4 : PYTHON 1. Explain the features of Pythonspc.edu.in/public/uploads/OSS U4.pdf · Unit – 4 : PYTHON 1. Explain the features of Python. i) Simple Python is a simple and minimalistic

10. Write a program to read the contents of file and directory *:

import os

#import os.path

path = 'c:/python27/temp/temp1/' data={} files= os.listdir(path) print 'The files in the directory are:\n',files

for file in files: #print file dir_path=os.path.join(path,file) print dir_path

if os.path.isfile(dir_path): f= open (dir_path,'r') data[file]=f.read() f.close()

print 'The contents of the files are:',data

11. Write a function that accepts a list of words and a

length and displays the words which are greater than

the length.

def filter_long_words(n,x):

li=[]

for word in x:

if len(word)>n:

li.append(word)

print li

x=raw_input("Enter words:").split(',')

n=int(raw_input("Enter length:"))

filter_long_words(n,x)

12. GUI basics: from Tkinter import *

def function_name1(): print 'Bye!!!!!' label1['text']='Bye!!!'

def function_name2(): print 'Good Morning!!!!!' label2['text']='Good Morning!!!'

root=Tk() root.geometry("700x700") root.title("GUI Basics")

label1=Label(root,text="I am a Label") #label1.pack() # Default side=TOP, options:LEFT,RIGHT,BOTTOM #label1.grid() # Deafult row=0, column=0 label1.place(x=300,y=0) # Layout managers:pack(), grid(),place()

textbox=Entry(root, width=20) textbox.insert(0,"I am a text box") # (index,string) textbox.place(x=300,y=30)

button2=Button(root,text="I am Second Button",command=function_name2) button2.place(x=300,y=100) button1=Button(root,text="I am First Button",command=function_name1) button1.place(x=300,y=70)

label2=Label(root,text='I am second label') label2.place(x=300,y=130) button2.bind("<Double-1>",function_name2)

frame=Frame(root,bg='red') frame.place(x=300,y=170)

listbox=Listbox(frame, selectmode=EXTENDED) listbox.pack(side=LEFT)

scrollbar=Scrollbar(frame,orient=VERTICAL) # problem slider not appearing scrollbar.pack(side=RIGHT, fill=BOTH)

for item in ['one','two','three']: listbox.insert(END,item)

listbox.config(yscrollcommand=scrollbar.set) scrollbar.config(command=listbox.yview)

root.mainloop()

25


Recommended