Vous êtes sur la page 1sur 15

UNIT - 1

1.What are the features of python. Explain the PVM.

Ans : Following are some important features of python.

 Simple: When we read a python program, we feel like reading English


sentences. It means more clarity and less understanding the syntax of
language.
 Easy to learn: Python uses very few keywords. Its programs use very
simple structure.
 Open source: There is no need to pay for software. python can be freely
downloaded from www.python.org website. Its source can be read, modified
and can be used in programs as desired by the programmers.
 High level language: programming languages are of two types: low level
and high level. A low level language uses machine code instructions to
develop programs. High level languages uses English words to develop
program.
 Dynamically typed: In python, we need not declare anything. If a name is
assigned to an object of one type, it may be assigned to an object of a
different type. This is the meaning of the saying that python is a dynamically
typed language.
 Platform independent : When a python program is compiled using a
python compiler, it generates byte code. Using python virtual machine
(PVM) ,anybody can run these byte code instructions on any computer
system.
 Portable : When a program yields the same result on any computer in the
world , the it is called a portable program.
 Procedure and object oriented : Python is a procedure oriented as an
object oriented programming language.
 Interpreted : A program code is called source code. We should compile the
source code using Python compiler. Python compiler translates the Python
program into an intermediate code called byte code. This byte code is then
executed by PVM. Inside the PVM, an interpreter converts the byte code
instructions into machine code so that processor will understand and run that
machine code to produce results.

1
 Extensible : The programs or pieces of code written in C or C++ can be
integrated into Python and executed using PVM.
 Embeddable : We can insert Python programs into C or C++ program.
PVM(Python virtual machine):
Let’s assume that we write Python program with the name x.py. Here ,x is the
program name and the .py is the extension name. The next step is to compile the
program using python compiler. The compiler converts the python program into
another code called byte code.
Byte code represents a fixed set of instructions that represents all operations like
arithmetic operations, comparision operations etc.
The next step is to run the program. If we directly give the byte code to the
computer, it cannot execute the code. Any computer can execute only binary code
which comprises 1s and 0s.
PVM uses interpreter which understands the byte code and converts it into
machine code. PVM understands the processor and OS in our computer. Then it
converts the byte code into machine code understandable to that processor. These
machine code instructions are then executed by the processor and results are
displayed.
An interpreter translates the program source code line by line.

2
2. Program to generate random numbers stored in array. Then find min, max
and sum of array elements and display array elements using slicing operators.
Program :
from random import*;
from array import*;
import sys
arr = array("f",[])

n = int(input("Enter the range of random numbers : "))


for i in range(n):
num = random()
arr.append(num)
print("Array elements is : ",arr)
print("\nMin Element in array is : ",min(arr))
print("\nMax Element in array is : ",max(arr))
print("\nSum of all Element in array is : ",sum(arr))
print("\nThe first 3 array elements is : ",arr[:3])

3
3.Write a program to demonstrate the usage of DICTIONARY and TUPLE
Program :

"""DICTIONARY"""

#How to access elements from a dictionary?


print("Adding the items to the my_dict")
my_dict = {'name':'Jack', 'age': 26}

print("print the name")


print(my_dict['name'])

print("print the age")


print(my_dict.get('age'))

print("Updating the age to 27")


my_dict['age'] = 27

print("After the updation")


print(my_dict)

print("Adding the address")


my_dict['address'] = 'Downtown'
print(my_dict)

print("remove a particular item age")


my_dict.pop("age")
print(my_dict)

print("remove all items")


my_dict.clear()

print(my_dict)

"""TUPLES"""

print("Tuples..")
4
#input("Enter the number of tuple values want to update : ")

a=("BMSCE","Bangalore")
print("Position value is : ",a[int(input("Enter the position of a tuple : "))])

b=(1,2,3,4,[5,6])

print("concatinating the a and b tuples")


tup3 = a+b
print(tup3)

print("Replacing the value 5 by 10")

b[4][0]=10

print(tup3)

del a
print("After deleting tup : ")
if tup3 != None:
print(b)
else:
print("Tuple is deleted")

5
4.Write a program to use the all possible operations in Arrays and List.

Program :

print('Create an Array')
arr = [10, 20, 30, 40, 50]
print(arr)

print('Access elements of an Array')


print(arr[0])
print(arr[4])

print('Accessing elements of array using negative indexing')


print(arr[-2])

print('Find length of an Array')


num_arr = len(arr)
print(num_arr)

print('Add an element to an Array')


arr.append(60)
print(arr)

print('Remove elements from an Array')


del arr[4]
arr.remove(10)
arr.pop(3)
print(arr)

print('Modify elements of an Array')


arr[1] = 10
arr[-1] = 5
print(arr)

print('Python operators to modify elements in an Array')


arr=[20, 10, 5]
arr+=[1,2,3,4]
print(arr)

'''print('Repeating elements in array using * operator')


6
arr = ['a']
arr = arr * 5
print(arr)'''

print('Slicing an array using Indexing')


print(arr[1:4])
print(arr[ : 3])
print(arr[-4:])
print(arr[-3:-1])

print(' empty list')


my_list = []
print(my_list)

print('list of integers')
my_list = [1, 2, 3]
print(my_list)

print('list with mixed datatypes')


my_list = [1, "Hello", 3.4]
print(my_list)

print(my_list[-1])
print(my_list)

7
5. Write a program to demonstrate the usage of operstors.
Program :

#Arithmetic operators in Python


x=int(input('Enter x value:'))
y=int(input('Enter y value:'))
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)

#Comparison operators in Python

print('x > y is',x>y)


print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)

#Logical operators

x = True
y = False
8
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)

# Identity operators in Python


x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]

print(x1 is not y1)


print(x2 is y2)
print(x3 is y3)

#Membership operators

x = 'Hello world'
y = {1:'a',2:'b'}

print('H' in x)
print('hello' not in x)
print(1 in y)
print('a' in y)
9
UNIT - 2

1.Python Program to Append, Delete and Display Elements of a List Using Classes

Problem Solution

1. Create a class and using a constructor initialize values of that class.


2. Create methods for adding, removing and displaying elements of the list and return the
respective values.
3.Create an object for the class.
4. Using the object, call the respective function depending on the choice taken from the
user.
5. Print the final list.
6. Exit
class check():
def __init__(self):
self.n=[]
def add(self,a):
return self.n.append(a)
def remove(self,b):
self.n.remove(b)
def dis(self):
return (self.n)

obj=check()
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Delete")
print("3. Display")
choice=int(input("Enter choice: "))
if choice==1:
n=int(input("Enter number to append: "))
obj.add(n)
print("List: ",obj.dis())
elif choice==2:
n=int(input("Enter number to remove: "))
obj.remove(n)
print("List: ",obj.dis())

elif choice==3:
print("List: ",obj.dis())
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")

print()

10
2. Python Program to create dictionary with a cricket player names and scores in a
match. Retrieve runs by entering the player’s name.

x = {}
n = int(input("How many players?"))
for i in range(n):
k = input("Enter Player's name:")
v = input("Enter Player's Score:")
x.update({k:v})
print('\n Players in this match:\n')
for pname in x.keys():
print(pname)
name = input('Enter the Player\'s name:')
runs = x.get(name,-1)
if(runs == -1):
print('Player not found')
else:
print('{}\'s score is {}'.format(name,runs))

3.Recursive function

def recur_fibo(n):
"""Recursive function to
print Fibonacci sequence"""
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = int(input("How many terms? "))

if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))

11
4.Tower of Hanoi

def TowerOfHanoi(n , from_rod, to_rod, aux_rod):


if n == 1:
print("Move disk 1 from rod",from_rod,"to rod",to_rod)
return
TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)
print("Move disk",n,"from rod",from_rod,"to rod",to_rod)
TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)

n=4
TowerOfHanoi(n, 'A', 'C', 'B')

5) Write a program that simulates a simple ATM machine based on transaction


code
Entered by customer
1 – Withdrawal
2 – Deposit
3 – Check Balance
4 – Exit.

12
UNIT - 3

1) What is the output of the following program?

def outerFunction():
global a
a = 20
def innerFunction():
global a
a = 30
print('a =', a)
a = 10
outerFunction()
print('a =', a)

ANS: 20

2) What is the output of the following program?

class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y

def __sub__(self, other):


x = self.x + other.x
y = self.y + other.y
return Point(x,y)
p1 = Point(3, 4)
p2 = Point(1, 2)
result = p1-p2
print(result.x, result.y)

ANS: 4 6

13
3) Create a class TV with the attribute channel, volume, and switch indicating
whether
TV is On / Off. The methods needs to define:
a. Turn the TV ON or Off
b. Set the channel number 0 to 99
c. Raise the volume by one unit, Range from 0 to 20 d) View TV status (ON
/OFF), channel and volume.
Newly TV object is set to off with the channel set to 2 and volume initially 10.

class Tv:
def __init__(self):
self.status="OFF"
self.vol=10
self.channel=2
def changestatus(self):
if self.status=="OFF":
self.status="ON"
else:
self.status="OFF"
def changechannel(self):
ch=int(input("ENTER CHANNEL"))
if ch>=0 and ch<=99:
self.channel=ch
def setvol(self):
if self.vol<=20:
self.vol+=1
def display(self):
print(self.status,self.channel,self.vol)

tv=Tv()
while(True):
print("ENTER 1.TV STATUS 2.CHANGE CHANNEL 3.RAISE VOLUME 4.DISPLAY")
c=int(input("ENTER YOUR CHOICE"))
if c==1:
tv.changestatus()
tv.display()
elif c==2:
tv.changechannel()
tv.display()
elif c==3:
tv.setvol()

14
tv.display()
elif c==4:
tv.display()
else:
break

4) Create an abstract class Accounts with members balance,


account number, account holder Name, address and methods withdrawal (),
deposit(), display(). Create a subclass Savings Account with rate of Interest,
calculate amount (), display(). Create another subclass of Account class as Current
Account with overdraft limit, display (). Create these objects call their methods
using appropriate constructors.

UNIT -4

1.Write a program for user defined exception that checks the internal and external
marks; if the internal marks greater than 40 it raises the exception “Internal Marks
is Exceed”; if the external marks is greater than 60 it raises the exception and
displays the message “The External Marks is Exceed”. Create the above exception
and implement in program.

15

Vous aimerez peut-être aussi