Sunteți pe pagina 1din 25

RCS 454:PHYTHON LANGUAGE PROGRAMMING LAB

The id() function returns identity (unique integer) of an object.


The syntax of id() is:

id(object)

id() Parameters: The id() function takes a single parameter object

Return Value from id():The id() function returns identity of the object. This is an integer which is unique for
the given object and remains constant during its lifetime

Program 1:
Demonstrate the working of ‘id’ and ‘type’ functions.

(i)Program:-
>>>list=[1,2,3]
>>>id(list[0])
21127896

>>>id(list[1])
21127884

>>>id(list[2])
21127872

(ii)Program:-
print('id of 5 =',id(5))
a=5
print('id of a =',id(a))
b=a
print('id of b =',id(b))
c = 5.0
print('id of c =',id(c))

Output:-

id of 5 = 140472391630016
id of a = 140472391630016
id of b = 140472391630016
id of c = 140472372786520

Hence, integer 5 has a unique id. The id of the integer 5 remains constant during the lifetime. Similar is
the case for float 5.5 and other objects.
Python type()
If a single argument (object) is passed to type() built-in, it returns type of the given object. If three
arguments (name, bases and dict) are passed, it returns a new type object.

Different forms of type() in Python are:

type(object)
type(name, bases, dict)

type() With a Single Object Parameter:

If the single object argument is passed to type(), it returns type of the given object.

(i)Program:-

numberList = [1, 2]

print(type(numberList))

numberDict = {1: 'one', 2: 'two'}

print(type(numberDict))

class Foo:

a=0

InstanceOfFoo = Foo()

print(type(InstanceOfFoo))

Output:-

<class 'dict'>
<class 'Foo'>

type() With name, bases and dict Parameters:-


If three parameters are passed to type(), it returns a new type object.
Three parameters to the type() function are:
 name - class name which becomes __name__ attribute
 bases - a tuple that itemizes the base class, becomes __bases__ attribute
 dict - a dictionary which is the namespace containing definitions for class body;
becomes __dict__ attribute
(ii)Program:-
o1 = type('X', (object,), dict(a='Foo', b=12))
print(type(o1))
print(vars(o1))
class test:
a = 'Foo'
b = 12
o2 = type('Y', (test,), dict(a='Foo', b=12))
print(type(o2))
print(vars(o2))

Output:-

<class 'type'>
{'b': 12, 'a': 'Foo', '__dict__': <attribute '__dict__' of 'X' objects>, '__doc__': None,
'__weakref__': <attribute '__weakref__' of 'X' objects>}
<class 'type'>
{'b': 12, 'a': 'Foo', '__doc__': None}

In the program, we have used Python vars() function return the __dict__ attribute. __dict__is used to store
object's writable attributes.
Program 2:
Python Program to Print all the Prime Numbers within a Given Range.
Program:-
# Python program to display all the prime numbers within an interval

# change the values of lower and upper for a different result

lower = 900

upper = 1000

# uncomment the following lines to take input from the user

#lower = int(input("Enter lower range: "))

#upper = int(input("Enter upper range: "))

print("Prime numbers between",lower,"and",upper,"are:")

for num in range(lower,upper + 1):

# prime numbers are greater than 1

if num > 1:

for i in range(2,num):

if (num % i) == 0:

break

else:

print(num)

Output:-

Prime numbers between 900 and 1000 are:

907
911
919
929
937
941
947
953
967
971
977
983
991
997
Program 3:
To Print ‘n terms of the Fibonacci series.

Program:-
# Program to display the Fibonacci sequence up to n-th term where n is provided by the user
# change this value for a different result
nterms = 10
# uncomment to take input from the user
#nterms = int(input("How many terms? "))
# first two terms
n1 = 0
n2 = 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count < nterms:
print(n1,end=' , ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Output:-
Fibonacci sequence upto 10 :
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
Program 4:
To demonstrate use of slicing in string
Slice. A snake appears near your foot. It moves from the invisible to the visible. Our vision reveals
(like a slice) only a part of the world.

A Python slice extracts elements, based on a start and stop. We take slices on many types in Python.
We specify an optional first index, an optional last index, and an optional step.

Slice syntax forms:

Get elements from...


values[1:3] Index 1 through index 3.
values[2:-1] Index 2 through index one from last.
values[:2] Start through index 2.
values[2:] Index 2 through end.
values[::2] Start through end, skipping ahead 2 places
each time.
List. This program takes a slice of a list. We first create a list with five numeric elements. We
specify in the slice two values: 1 and 3. At index 1, we have the value 200.

Python program that slices list

values = [100, 200, 300, 400, 500]


# Get elements from second index to third index.
slice = values[1:3]
print(slice)

Output

[200, 300]

Negative. The second index in slice notation may be negative. This means counting begins from
the last index. So a negative one means the same as "length minus one."

Python program that slices, negative second index

values = [100, 200, 300, 400, 500]


# Slice from third index to index one from
last.
slice = values[2:-1]
print(slice)

Output

[300, 400]
Start, end. In slicing, if you omit the first or second index, it means "start" or
"end." This is clearer than specifying 0 or the length.

Python program that slices, starts and ends

values = [100, 200, 300, 400, 500]


# Slice from start to second index.
slice = values[:2]
print(slice)

# Slice from second index to end.


slice = values[2:]
print(slice)

Output

[100, 200]
[300, 400, 500]

Strings. We use the slice notation on strings. In this example, we omit the first
index to start at the beginning, and then consume four characters total. We
extract the first four letters.Substring
Python program that slices string

word = "something"
# Get first four characters.
part = word[:4]
print(part)

Output

some

Copy. With slicing, we can copy sequences like lists. We assign a new list
variable to a slice with no specified start or stop values. So the slice copies the
entire list and returns it.Copy List
Python program that uses step, slices

values = "AaBbCcDdEe"

# Starting at 0 and continuing until end,


take every other char.
evens = values[::2]
print(evens)

Output

ABCDE
Program 5:
(a)Program to add 'ing' at the end of a given string (length should be at least 3). If
the given string is already ends with 'ing' then add 'ly' instead. If the string length
of the given string is less than 3, leave it unchanged

Program:-

1. def add_string(str1):
2. length = len(str1)
3.
4. if length > 2:
5. if str1[-3:] == 'ing':
6. str1 += 'ly'
7. else:
8. str1 += 'ing'
9.
10. return str1
11. print(add_string('ab'))
12. print(add_string('abc'))
13. print(add_string('string'))

Output:-
14. ab
15. abcing
16. stringly

(b)To get a string from a given string where all occurrences of its first char have
been changed to ‘$’ ,except the first char itself.

Program:
str1=input(“Enter a String:”)
Print(“Original String:”str1)
char=str1[0]
str1=str1.replace(char,’$’)
str1=char+str1[1:]
Print(“Replaced String:”,str1)

Output:
Enter a String:onion
Original String:onion
Replaced String:oni$n
Program 6:
(a)Write a program to compute the frequency of the words from the input. The
output should output after sorting the key alphanumerically.

Program:-
freq = {} # frequency of words in text
line = raw_input()
for word in line.split():
freq[word] = freq.get(word,0)+1

words = freq.keys()
words.sort()

for w in words:
print "%s:%d" % (w,freq[w])

Output:
Suppose the following input is supplied to the program:
New to Python or choosing between Python 2 and Python 3? Read Python 2 or
Python 3.
Then, the output should be:
2:2
3.:1
3?:1
New:1
Python:5
Read:1
and:1
between:1
choosing:1
or:2
to:1

(b) Write a program that accepts a comma separated sequence of words as input and prints the
words in a comma-separated sequence after sorting them alphabetically.

Program:-

items=[x for x in raw_input().split(',')]


items.sort()
print ','.join(items)

Output:-

Suppose the following input is supplied to the program:


without,hello,bag,world
Then, the output should be:
bag,hello,without,world
Program 7:
Write a program that accepts a sequence of whitespace separated words as input and prints the
words after removing all duplicate words and sorting them alphanumerically.

Program:-

s = raw_input()
words = [word for word in s.split(" ")]
print " ".join(sorted(list(set(words))))

Output:-

Suppose the following input is supplied to the program:


hello world and practice makes perfect and hello world again
Then, the output should be:
again and hello makes perfect practice world
Program 8:
To demonstrate use of List & related functions.

The list is a most versatile datatype available in Python which can be written as a list of comma-
separated values (items) between square brackets. Important thing about a list is that items in a
list need not be of the same type.

Program:-

(i)Accessing Values in Lists

#!/usr/bin/python

list1 = ['physics', 'chemistry', 1997, 2000];

list2 = [1, 2, 3, 4, 5, 6, 7 ];

print "list1[0]: ", list1[0]

print "list2[1:5]: ", list2[1:5]

Output:-

list1[0]: physics
list2[1:5]: [2, 3, 4, 5]

(ii)Updating Lists

#!/usr/bin/python

list = ['physics', 'chemistry', 1997, 2000];

print "Value available at index 2 : "

print list[2]

list[2] = 2001;

print "New value available at index 2 : "

print list[2]

Output:-

Value available at index 2 :


1997
New value available at index 2 :
2001
Built-in List Functions & Methods
(i) cmp(list1, list2)
Compares elements of both lists.
list1, list2 = [123, 'xyz'], [456, 'abc']

print cmp(list1, list2)

print cmp(list2, list1)

list3 = list2 + [786];

print cmp(list2, list3)

Output:-
1
1
-1

(ii) len(list)
Gives the total length of the list.
#!/usr/bin/python

list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']

print "First list length : ", len(list1)

print "Second list length : ", len(list2)

Output:-

First list length : 3


Second list length : 2

(iii) max(list)

Returns item from the list with max value.

#!/usr/bin/python

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]

print "Max value element : ", max(list1)

print "Max value element : ", max(list2)

Output:-
Max value element : zara
Max value element : 700
(iv) list(seq)

Converts a tuple into list.


#!/usr/bin/python

aTuple = (123, 'xyz', 'zara', 'abc');

aList = list(aTuple)

print "List elements : ", aList

Output:-
List elements : [123, 'xyz', 'zara', 'abc']
Program 9:
To demonstrate use of Dictionary & related functions.

To access dictionary elements, you can use the familiar square brackets along with the key to
obtain its value.

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

print "dict['Name']: ", dict['Name']

print "dict['Age']: ", dict['Age']

Output:-
dict['Name']: Zara
dict['Age']: 7

Updating Dictionary

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

dict['Age'] = 8; # update existing entry

dict['School'] = "DPS School"; # Add new entry

print "dict['Age']: ", dict['Age']

print "dict['School']: ", dict['School']

Output:-
dict['Age']: 8
dict['School']: DPS School

Built-in Dictionary Functions:


(i) cmp(dict1, dict2): Compares elements of both dict.
(ii) #!/usr/bin/python

(iii)

(iv) dict1 = {'Name': 'Zara', 'Age': 7};

(v) dict2 = {'Name': 'Mahnaz', 'Age': 27};

(vi) dict3 = {'Name': 'Abid', 'Age': 27};

(vii) dict4 = {'Name': 'Zara', 'Age': 7};

(viii) print "Return Value : %d" % cmp (dict1, dict2)

(ix) print "Return Value : %d" % cmp (dict2, dict3)

(x) print "Return Value : %d" % cmp (dict1, dict4


Output:
Return Value : -1
Return Value : 1
Return Value : 0

(ii) len(dict): Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7};

print "Length : %d" % len (dict)

Output:-
Length : 2

(iii) str(dict): Produces a printable string representation of a dictionary

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7};

print "Equivalent String : %s" % str (dict)

Output:-
Equivalent String : {'Age': 7, 'Name': 'Zara'}

(iv) type(variable)

Returns the type of the passed variable. If passed variable is dictionary,


then it would return a dictionary type.
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7};

print "Variable Type : %s" % type (dict)

Output:-
Variable Type : <type 'dict'>
Program 10:
To demonstrate use of tuple & related functions.

To access values in tuple, use the square brackets for slicing along with the index or indices to
obtain value available at that index.

#!/usr/bin/python

tup1 = ('physics', 'chemistry', 1997, 2000);

tup2 = (1, 2, 3, 4, 5, 6, 7 );

print "tup1[0]: ", tup1[0];

print "tup2[1:5]: ", tup2[1:5];

Output:-
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]

Updating Tuples

#!/usr/bin/python

tup1 = (12, 34.56);

tup2 = ('abc', 'xyz');

# Following action is not valid for tuples

# tup1[0] = 100;

# So let's create a new tuple as follows

tup3 = tup1 + tup2;

print tup3;

Output:
(12, 34.56, 'abc', 'xyz')

Built-in Tuple Functions:-


(i) cmp(tuple1, tuple2)
Compares elements of both tuples.
#!/usr/bin/python

tuple1, tuple2 = (123, 'xyz'), (456, 'abc')

print cmp(tuple1, tuple2)

print cmp(tuple2, tuple1)

tuple3 = tuple2 + (786,);

print cmp(tuple2, tuple3)


Output:
-1
1
-1

(ii)len(tuple)

Gives the total length of the tuple.


#!/usr/bin/python

tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')

print "First tuple length : ", len(tuple1)

print "Second tuple length : ", len(tuple2)

Output:
First tuple length : 3
Second tuple length : 2

(iii) max(tuple)

Returns item from the tuple with max value.


#!/usr/bin/python

tuple1, tuple2 = (123, 'xyz', 'zara', 'abc'), (456, 700, 200)

print "Max value element : ", max(tuple1)

print "Max value element : ", max(tuple2)

Output:
Max value element : zara
Max value element : 700

(iv) tuple(seq)

Converts a list into tuple.


#!/usr/bin/python

aList = (123, 'xyz', 'zara', 'abc');

aTuple = tuple(aList)

print "Tuple elements : ", aTuple

Output:
Tuple elements : (123, 'xyz', 'zara', 'abc')
Program 11:
To implement stact using list.

Stack works on the principle of “Last-in, first-out”. Also, the inbuilt functions in Python make the code short and
simple. To add an item to the top of the list, i.e., to push an item, we use append() function and to pop out an
element we use pop() function. These functions work quiet efficiently and fast in end operations.

# Python code to demonstrate Implementing


# stack using list
stack = ["Amar", "Akbar", "Anthony"]
stack.append("Ram")
stack.append("Iqbal")
print(stack)
print(stack.pop())
print(stack)
print(stack.pop())
print(stack)

Output:-

['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal']


Iqbal
['Amar', 'Akbar', 'Anthony', 'Ram']
Ram
['Amar', 'Akbar', 'Anthony']
Program 12:
To implement queue using List.

# Python code to demonstrate Implementing


# Queue using deque and list
from collections import deque
queue = deque(["Ram", "Tarun", "Asif", "John"])
print(queue)
queue.append("Akbar")
print(queue)
queue.append("Birbal")
print(queue)
print(queue.popleft())
print(queue.popleft())
print(queue)

Output:-
deque(['Ram', 'Tarun', 'Asif', 'John'])
deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar'])
deque(['Ram', 'Tarun', 'Asif', 'John', 'Akbar', 'Birbal'])
Ram
Tarun
deque(['Asif', 'John', 'Akbar', 'Birbal'])
Program 13:
To read and write from a file.

# Program to show various ways to read and


# write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]

# \n is placed to indicate EOL (End of Line)


file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes

file1 = open("myfile.txt","r+")

print "Output of Read function is "


print file1.read()
print

# seek(n) takes the file handle to the nth


# bite from the beginning.
file1.seek(0)

print "Output of Readline function is "


print file1.readline()
print

file1.seek(0)

# To show difference between read and readline


print "Output of Read(9) function is "
print file1.read(9)
print

file1.seek(0)

print "Output of Readline(9) function is "


print file1.readline(9)

file1.seek(0)
# readlines function
print "Output of Readlines function is "
print file1.readlines()
print
file1.close()
Output:-
Output of Read function is

Hello
This is Delhi
This is Paris
This is London

Output of Readline function is


Hello

Output of Read(9) function is


Hello

Th

Output of Readline(9) function is


Hello

Output of Readlines function is


['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
Program 14:
To Copy a file.

# Python Copy File - Sample Code

from shutil import copyfile


from sys import exit

source = input("Enter source file with full path: ")


target = input("Enter target file with full path: ")

# adding exception handling


try:
copyfile(source, target)
except IOError as e:
print("Unable to copy file. %s" % e)
exit(1)
except:
print("Unexpected error:", sys.exc_info())
exit(1)

print("\nFile copy done!\n")

while True:
print("Do you like to print the file ? (y/n): ")
check = input()
if check == 'n':
break
elif check == 'y':
file = open(target, "r")
print("\nHere follows the file content:\n")
print(file.read())
file.close()
print()
break
else:
continue
Program 15:
To demonstrate working of classes and objects.

class MyClass:
"This is my second class"
a = 10
def func(self):
print('Hello')

# Output: 10
print(MyClass.a)
# Output: <function MyClass.func at 0x0000000003079BF8>
print(MyClass.func)
# Output: 'This is my second class'
print(MyClass.__doc__)

Output:-
10

<function 0x7feaa932eae8="" at="" myclass.func="">

This is my second class

10
<function MyClass.func at 0x7fe50c74d598>
This is my second class

In [1]:
Objects:-

Program:-

class MyClass:
"This is my second class"
a = 10
def func(self):
print('Hello')

# create a new MyClass


ob = MyClass()

# Output: <function MyClass.func at 0x000000000335B0D0>


print(MyClass.func)

# Output: <bound method MyClass.func of <__main__.MyClass object at


0x000000000332DEF0>>
print(ob.func)

# Calling function func()


# Output: Hello
ob.func()

Output:-
<function MyClass.func at 0x7fe50f75a048>
<bound method MyClass.func of <__main__.MyClass object at 0x7fe50f7577b8>>
Hello
Program 16:
To demonstrate Constructors.

Program:-

class ComplexNumber:
def __init__(self,r = 0,i = 0):
self.real = r
self.imag = i

def getData(self):
print("{0}+{1}j".format(self.real,self.imag))

# Create a new ComplexNumber object


c1 = ComplexNumber(2,3)

# Call getData() function


# Output: 2+3j
c1.getData()

# Create another ComplexNumber object


# and create a new attribute 'attr'
c2 = ComplexNumber(5)
c2.attr = 10

# Output: (5, 0, 10)


print((c2.real, c2.imag, c2.attr))

# but c1 object doesn't have attribute 'attr'


# AttributeError: 'ComplexNumber' object has no attribute 'attr'
c1.attr

Output:-
2+3j
(5, 0, 10)

Traceback (most recent call last):


File "<stdin>", line 26, in <module>
c1.attr
AttributeError: 'ComplexNumber' object has no attribute 'attr'

S-ar putea să vă placă și